From 45f281524760c170aa22fedcf86a173ab97bdc74 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 12 Nov 2026 20:19:19 +0330 Subject: [PATCH] last works ... --- Documents/Codes/IXBotProvider.cs | 119 + Documents/Codes/XBotMessageRequest.cs | 134 + Documents/Codes/XBotProvider.cs | 973 + .../xDashboard-xAiApi-20261109_152617.txt | 39256 ---------------- .../xDashboard-xAiModels-20261109_152619.txt | 12301 ----- .../xDashboard-xAiService-20261109_152620.txt | 1947 - .../xDashboard-xApi-20261109_152617.txt | 1319 - ...shboard-xApiSDKHolder-20261112_120913.txt} | 104 +- ...xDashboard-xBotService-20261111_121519.txt | 67 - ...xDashboard-xBotService-20261111_153912.txt | 1011 - ...board-xCategoryService-20261109_152622.txt | 10095 ---- ...=> xDashboard-xClient-20261112_120855.txt} | 548 +- .../xDashboard-xCommons-20261109_152619.txt | 8783 ---- ...hboard-xContentService-20261109_152621.txt | 2675 -- ...Dashboard-xDataService-20261109_152620.txt | 13507 ------ ...Dashboard-xDataService-20261111_120055.txt | 13507 ------ ...ashboard-xEventService-20261109_152621.txt | 2460 - ...xDashboard-xExceptions-20261109_152620.txt | 253 - ...Dashboard-xFileService-20261109_152620.txt | 3351 -- ...eworkComponentsHolder-20261112_120934.txt} | 716 +- ...-xFrameworkCoreHolder-20261112_120917.txt} | 162 +- ...workIdentitySDKHolder-20261112_120926.txt} | 78 +- ...workPushServiceHolder-20261112_120931.txt} | 24 +- ...ameworkServicesHolder-20261112_120921.txt} | 62 +- ...hboard-xFrameworkTest-20261112_120905.txt} | 308 +- ...Dashboard-xHttpService-20261109_152620.txt | 767 - ...hboard-xIdentityHelper-20261109_152621.txt | 4316 -- ...hboard-xIdentityModels-20261109_152621.txt | 4294 -- ...board-xIdentityService-20261109_152622.txt | 13017 ----- .../xDashboard-xIds-20261109_152616.txt | 29682 ------------ ...hboard-xLoggingService-20261109_152621.txt | 1246 - ...hboard-xMessageService-20261109_152621.txt | 727 - .../xDashboard-xModels-20261109_152619.txt | 1620 - ...Dashboard-xPushService-20261109_152620.txt | 6502 --- .../xDashboard-xServices-20261109_152618.txt | 1516 - ...hboard-xStorageService-20261109_152621.txt | 1653 - ...shboard-xStringService-20261109_152621.txt | 7011 --- ...xDashboard-xTagService-20261109_152620.txt | 5044 -- ...xDashboard-xTagService-20261111_121235.txt | 5044 -- ...msAndConditionsService-20261109_152622.txt | 574 - ...hboard-xWebinarService-20261109_152621.txt | 2038 - Documents/OpenApi/Swagger/xApi-swagger.json | 479 +- Documents/Resources/Json/Requests.md | 127 + Modules/xBotService | 2 +- Modules/xHttpService | 2 +- Modules/xIdentityService | 2 +- Modules/xLoggingService | 2 +- Modules/xServices | 2 +- 48 files changed, 2833 insertions(+), 196594 deletions(-) create mode 100644 Documents/Codes/IXBotProvider.cs create mode 100644 Documents/Codes/XBotMessageRequest.cs create mode 100644 Documents/Codes/XBotProvider.cs delete mode 100644 Documents/GeneratedContext/xDashboard-xAiApi-20261109_152617.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xAiModels-20261109_152619.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xAiService-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xApi-20261109_152617.txt rename Documents/GeneratedContext/{xDashboard-xApiSDKHolder-20261109_153852.txt => xDashboard-xApiSDKHolder-20261112_120913.txt} (96%) delete mode 100644 Documents/GeneratedContext/xDashboard-xBotService-20261111_121519.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xBotService-20261111_153912.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xCategoryService-20261109_152622.txt rename Documents/GeneratedContext/{xDashboard-xClient-20261109_153842.txt => xDashboard-xClient-20261112_120855.txt} (97%) delete mode 100644 Documents/GeneratedContext/xDashboard-xCommons-20261109_152619.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xContentService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xDataService-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xDataService-20261111_120055.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xEventService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xExceptions-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xFileService-20261109_152620.txt rename Documents/GeneratedContext/{xDashboard-xFrameworkComponentsHolder-20261109_153906.txt => xDashboard-xFrameworkComponentsHolder-20261112_120934.txt} (97%) rename Documents/GeneratedContext/{xDashboard-xFrameworkCoreHolder-20261109_153855.txt => xDashboard-xFrameworkCoreHolder-20261112_120917.txt} (95%) rename Documents/GeneratedContext/{xDashboard-xFrameworkIdentitySDKHolder-20261109_153901.txt => xDashboard-xFrameworkIdentitySDKHolder-20261112_120926.txt} (96%) rename Documents/GeneratedContext/{xDashboard-xFrameworkPushServiceHolder-20261109_153904.txt => xDashboard-xFrameworkPushServiceHolder-20261112_120931.txt} (91%) rename Documents/GeneratedContext/{xDashboard-xFrameworkServicesHolder-20261109_153858.txt => xDashboard-xFrameworkServicesHolder-20261112_120921.txt} (97%) rename Documents/GeneratedContext/{xDashboard-xFrameworkTest-20261109_153847.txt => xDashboard-xFrameworkTest-20261112_120905.txt} (96%) delete mode 100644 Documents/GeneratedContext/xDashboard-xHttpService-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xIdentityHelper-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xIdentityModels-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xIdentityService-20261109_152622.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xIds-20261109_152616.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xLoggingService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xMessageService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xModels-20261109_152619.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xPushService-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xServices-20261109_152618.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xStorageService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xStringService-20261109_152621.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xTagService-20261109_152620.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xTagService-20261111_121235.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xTermsAndConditionsService-20261109_152622.txt delete mode 100644 Documents/GeneratedContext/xDashboard-xWebinarService-20261109_152621.txt diff --git a/Documents/Codes/IXBotProvider.cs b/Documents/Codes/IXBotProvider.cs new file mode 100644 index 0000000..4412ae7 --- /dev/null +++ b/Documents/Codes/IXBotProvider.cs @@ -0,0 +1,119 @@ +using xBotService.Models; +using System.Threading.Tasks; +using System.Collections.Generic; +using xBotService.Constants; +using System.Threading; + +namespace xBotService.Interfaces +{ + public interface IXBotProvider + { + /// + /// Retrieve Bot Info ... + /// + /// + /// + Task GetMe( + CancellationToken cancellationToken = default + ); + + /// + /// Sending Simple String Message to Bot ... + /// + /// + /// + /// + /// + /// + /// + Task SendMessage( + long chatId, + string text, + XBotReplyMarkup replyMarkup = null, + XBotMessageParseMode parseMode = XBotMessageParseMode.Html, + CancellationToken cancellationToken = default + ); + + /// + /// Sending Verification Request Menu ... + /// + /// + /// + /// + /// + Task SendVerificationMenu( + long chatId, + string label = "🔐 دریافت کد وریفیکیشن", + CancellationToken cancellationToken = default + ); + + /// + /// Send Verification Code to Requests ... + /// + /// + /// + /// + /// + /// + Task SendVerificationCode( + long chatId, + string code, + int ttlSeconds, + CancellationToken cancellationToken = default + ); + + /// + /// an Accept for Exit Loading on Bot ... + /// + /// + /// + /// + /// + /// + Task AnswerCallbackQuery( + string callbackQueryId, + string text = null, + bool showAlert = false, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Inline Keyboard After Click (Optional) ... + /// + /// + /// + /// + /// + Task RemoveInlineKeyboard( + long chatId, + long messageId, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Messages ... + /// + /// + /// + /// + /// + Task> GetUpdates( + long offset = 0, + int timeout = 30, + CancellationToken cancellationToken = default + ); + + /// + /// Set Webhook for Retrieve Messages on Recieved ... + /// + /// + /// + /// + /// + Task SetWebhook( + string webhookUrl, + string secretToken = null, + CancellationToken cancellationToken = default + ); + } +} \ No newline at end of file diff --git a/Documents/Codes/XBotMessageRequest.cs b/Documents/Codes/XBotMessageRequest.cs new file mode 100644 index 0000000..5765c20 --- /dev/null +++ b/Documents/Codes/XBotMessageRequest.cs @@ -0,0 +1,134 @@ +using Newtonsoft.Json; +using xCommons.Extensions; +using xBotService.Constants; +using System.Collections.Generic; + +namespace xBotService.Models +{ + // public class XBotMessageRequest + // { + // public long ChatId { get; set; } + // public string Text { get; set; } + // public XBotReplyMarkup ReplyMarkup { get; set; } = null; + // public string ParseMode { get; set; } = XBotMessageParseMode.Html.GetStringValue(); + // } + + // public class XBotReplyMarkup + // { + // public List> InlineKeyboard { get; set; } + // } + + // public class XBotInlineButton + // { + // public string Text { get; set; } + // public string Url { get; set; } + // public string CallbackData { get; set; } + // } + + // public class XBotMessageResponse + // { + // public bool Ok { get; set; } + // public string Description { get; set; } + // public XBotResMessage Result { get; set; } + // } + + // public class XBotResMessage + // { + // public long Date { get; set; } + // public string Text { get; set; } + // public long MessageId { get; set; } + // public XBotResUser From { get; set; } + // public XBotResChat Chat { get; set; } + // } + + public class XBotResUser + { + [JsonProperty("id")] + public long Id { get; set; } + + [JsonProperty("is_bot")] + public bool IsBot { get; set; } + + [JsonProperty("last_name")] + public string LastName { get; set; } + + [JsonProperty("username")] + public string Username { get; set; } + + [JsonProperty("first_name")] + public string FirstName { get; set; } + + [JsonProperty("language_code")] + public string LanguageCode { get; set; } + + [JsonProperty("has_main_web_app")] + public string HasMainWebApp { get; set; } + + [JsonProperty("has_topics_enabled")] + public bool HasTopicsEnabled { get; set; } + + [JsonProperty("allows_users_to_create_topics")] + public bool AllowsUsersToCreateTopics { get; set; } + } + + // public class XBotResChat + // { + // public long Id { get; set; } + // public string Type { get; set; } + // public string Title { get; set; } + // public string Username { get; set; } + // public string FirstName { get; set; } + // } + + // public class XBotUpdate + // { + // public long UpdateId { get; set; } + // public XBotResMessage Message { get; set; } + // public XBotCallbackQuery CallbackQuery { get; set; } + // } + + /// + /// Base Bot Response ... + /// + public class XBotResponse : XBotResponse + { } + + /// + /// Base Bot Response ... + /// + /// + public class XBotResponse + { + public bool Ok { get; set; } + public T Result { get; set; } + } + + /// + /// Bot Message Send Request ... + /// + public class XBotSendMessageRequest + { + [JsonProperty("chat_id")] + public long ChatId { get; set; } + + [JsonProperty("text")] + public string Text { get; set; } + + [JsonProperty("reply_markup")] + public object ReplyMarkup { get; set; } + + [JsonProperty("message_thread_id")] + public long MessageThreadId { get; set; } + + [JsonProperty("reply_to_message_id")] + public long ReplyToMessageId { get; set; } + } + + // public class XBotCallbackQuery + // { + // public string Id { get; set; } + // public string Data { get; set; } + // public XBotResUser From { get; set; } + // public XBotResMessage Message { get; set; } + // } +} \ No newline at end of file diff --git a/Documents/Codes/XBotProvider.cs b/Documents/Codes/XBotProvider.cs new file mode 100644 index 0000000..e34a7e9 --- /dev/null +++ b/Documents/Codes/XBotProvider.cs @@ -0,0 +1,973 @@ +using System; +using RestSharp; +using System.Linq; +using System.Net.Http; +using System.Threading; +using xCommons.Providers; +using xCommons.Constants; +using xBotService.Models; +using xCommons.Extensions; +using xBotService.Constants; +using xExceptions.Constants; +using xBotService.Interfaces; +using xIdentityModels.Models; +using System.Threading.Tasks; +using xHttpService.Constants; +using xIdentityService.Models; +using xHttpService.Interfaces; +using RestSharp.Authenticators; +using xIdentityModels.Constants; +using xBotService.Configuration; +using xIdentityModels.Extensions; +using xIdentityService.Constants; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Configuration; + +namespace xBotService.Providers +{ + public class XBotProvider : IXBotProvider + { + // + private readonly IXHttpProvider httpProvider; + private readonly ILogger logger; + private readonly IXTokenProvider tokenProvider; + private readonly IXIdentityProvider identityProvider; + private readonly XValidationProvider validationProvider; + private readonly XBotServiceConfiguration configuration; + private readonly XIdentityServiceConfiguration identityConfiguration; + + public XBotProvider( + IXHttpProvider httpProvider, + ILogger logger, + IXTokenProvider tokenProvider, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider, + XBotServiceConfiguration configuration, + XIdentityServiceConfiguration identityConfiguration + ) + { + // + this.logger = logger; + this.httpProvider = httpProvider; + this.tokenProvider = tokenProvider; + this.configuration = configuration; + this.identityProvider = identityProvider; + this.validationProvider = validationProvider; + this.identityConfiguration = identityConfiguration; + } + + // + #region Tools ... + /// + /// Get an Instance of Http Client + /// + /// + public HttpClient GetHttpClient() + { + // + HttpClient httpClient = null; + + // + // httpClient = new HttpClient (); + var httpClientHandler = new HttpClientHandler() + { + ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => + { + // + logger.LogInformation( + $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" + ); + + // + return true; + }, + ClientCertificateOptions = ClientCertificateOption.Manual, + }; + httpClient = new HttpClient(httpClientHandler); + + // + // Set Timeout ... + // TODO: Fix this ... + // httpClient.Timeout = TimeSpan + // .FromSeconds (identityConfiguration.DefaultClientTimeout); + + // + return httpClient; + } + + /// + /// Get an Instance of RestClient + /// + /// + public RestClient GetRestClient(XTokenResponse tokens = null) + { + // + var client = new RestClient(configuration.BaseRoute); + + // + // Set Authenticator ... + if (!tokens.IsNull() && + !tokens.AccessToken.IsNullOrEmpty()) + { + client.Authenticator = new JwtAuthenticator(tokens.AccessToken); + } + + // + // Refresh Token ... + if (!tokens.IsNull() && + !tokens.RefreshToken.IsNullOrEmpty()) + { + client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken); + } + + // + // ExpiresAt ... + if (!tokens.IsNull() && + tokens.ExpiresAt > 0) + { + client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString()); + } + + // + // Set Default Timeout ... + client.Timeout = configuration.DefaultClientTimeout; + + // + // SSL Validation Handler ... + client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => + { + // + logger.LogInformation( + $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" + ); + + // + return true; + }; + + // + return client; + } + + /// + /// Get an Instance of RestRequest + /// + public RestRequest GetRestRequest( + XBotEndpoints endpoint, + bool addXPoweredValue = true, + IDictionary @params = null, + IDictionary headers = null, + IDictionary queryStrings = null + ) + { + // + var url = endpoint.GetStringValue(); + + // + // Add Route Payloads ... + if (!@params.IsNull() && @params.Count > 0) + { + // + var enumerator = @params.GetEnumerator(); + while (enumerator.MoveNext()) + { + // + var item = enumerator.Current; + + // + url = url.Replace(item.Key, item.Value.ToUrlEncoded()); + } + } + + // + // Add Query Strings ... + if (!queryStrings.IsNull() && queryStrings.Count > 0) + { + // + url = $"{url}?"; + var enumerator = queryStrings.GetEnumerator(); + while (enumerator.MoveNext()) + { + // + var item = enumerator.Current; + + // + url += $"{item.Key}={item.Value.ToUrlEncoded()}&"; + } + + // + // remove lates & ... + if (url.EndsWith("&")) + { + url = url.Substring(0, url.Length - 1); + } + } + + // + // Create request ... + var request = new RestRequest(url, DataFormat.Json); + + // + if (addXPoweredValue) + { + request.AddHeader(XAuthorization.XPoweredBy, identityConfiguration.XPoweredValue); + } + + // + // Add Headers to request ... + if (!headers.IsNull() && headers.Count > 0) + { + // + var enumerator = headers.GetEnumerator(); + while (enumerator.MoveNext()) + { + // + var item = enumerator.Current; + request.AddHeader(item.Key, item.Value); + } + } + + // + return request; + } + + /// + /// Handle Call Specific Request and retrieve Response + /// + /// + /// + /// + /// + /// + /// + /// + public async Task RunRestRequest( + RestClient client, + RestRequest request, + XHttpMethod method, + bool supportRefreshingTokens = true, + CancellationToken cancellationToken = default + ) + { + // + var response = await Task.Run(async () => + { + // + IRestResponse resp = null; + + // + // Call Endpoint Service using Specified Method ... + switch (method) + { + // + // Get ... + case XHttpMethod.GET: + resp = client.Get(request); + break; + + // + // Put ... + case XHttpMethod.PUT: + resp = client.Put(request); + break; + + // + // Post ... + case XHttpMethod.POST: + resp = client.Post(request); + break; + + // + // Delete ... + case XHttpMethod.DELETE: + resp = client.Delete(request); + break; + } + + // + if (!resp.IsSuccessful) + { + // + // Log Exception ... + logger.LogError($"Error: {resp.ErrorMessage}"); + logger.LogError($"Exception: {resp.ErrorException.ToJSON()}"); + if (!resp.ErrorMessage.IsNullOrEmpty() && + resp.ErrorMessage.Contains("timed out")) + { + XException.Timeout.Throw(); + } + + // + // Refresh Tokens or Issue Correct Exception ... + if (supportRefreshingTokens && + resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) + { + // + var isRefreshed = request.Parameters.Any(rp => + rp.Name == XParam.XIsRefreshed.GetStringValue() && + rp.Value.ToString().ToNormalString() == true.ToJSON()); + + // + logger.LogInformation($"isRefreshed: {isRefreshed}"); + + // + // Get Access Token ... + XTokenResponse tokens = null; + var accessToken = request.Parameters.FirstOrDefault(rp => + rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString(); + if (!accessToken.IsNullOrEmpty()) + { + // + accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, ""); + + // + if (!accessToken.IsNullOrEmpty()) + { + tokens = await tokenProvider.RetrieveToken(accessToken); + } + } + + // + // Refresh Token and then re do request ... + if (!isRefreshed && + !accessToken.IsNullOrEmpty() && + !tokens.IsNull() && + tokens.IsRefreshable()) + { + // + request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON()); + + // + // Refreshe Tokens ... + var refreshedTokens = await identityProvider.RefreshTokens(tokens); + + // + // Renew Rest Client with Refreshed Tokens ... + var timeout = client.Timeout; + client = GetRestClient(refreshedTokens); + client.Timeout = Timeout.Infinite; + + // + // Do Request Again using renew Client ... + return await RunRestRequest( + client: client, + request: request, + method: method); + } + } + + // + var ex = resp.Content.ToXError(); + if (!ex.IsNull()) + { + throw ex.ToException(); + } + + // + // UnAuthorized ... + if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) + { + XException.NotAuthorized.Throw(); + } + + // + // NotFound ... + if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) + { + XException.NotFound.Throw(); + } + + // + XException.ActionFailed.Throw(); + } + + // + var result = resp.Content.FromJSON(); + return result; + }, cancellationToken); + + // + return response; + } + public async Task> RunRestRequestByResponse( + RestClient client, + RestRequest request, + XHttpMethod method, + bool supportRefreshingTokens = true, + CancellationToken cancellationToken = default + ) + { + // + var response = await Task.Run(async () => + { + // + IRestResponse resp = null; + + // + // Call Endpoint Service using Specified Method ... + switch (method) + { + // + // Get ... + case XHttpMethod.GET: + resp = client.Get(request); + break; + + // + // Put ... + case XHttpMethod.PUT: + resp = client.Put(request); + break; + + // + // Post ... + case XHttpMethod.POST: + resp = client.Post(request); + break; + + // + // Delete ... + case XHttpMethod.DELETE: + resp = client.Delete(request); + break; + } + + // + if (!resp.IsSuccessful) + { + // + // Log Exception ... + logger.LogError($"Error: {resp.ErrorMessage}"); + logger.LogError($"Exception: {resp.ErrorException.ToJSON()}"); + if (!resp.ErrorMessage.IsNullOrEmpty() && + resp.ErrorMessage.Contains("timed out")) + { + XException.Timeout.Throw(); + } + + // + // Refresh Tokens or Issue Correct Exception ... + if (supportRefreshingTokens && + resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) + { + // + var isRefreshed = request.Parameters.Any(rp => + rp.Name == XParam.XIsRefreshed.GetStringValue() && + rp.Value.ToString().ToNormalString() == true.ToJSON()); + + // + logger.LogInformation($"isRefreshed: {isRefreshed}"); + + // + // Get Access Token ... + XTokenResponse tokens = null; + var accessToken = request.Parameters.FirstOrDefault(rp => + rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString(); + if (!accessToken.IsNullOrEmpty()) + { + // + accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, ""); + + // + if (!accessToken.IsNullOrEmpty()) + { + tokens = await tokenProvider.RetrieveToken(accessToken); + } + } + + // + // Refresh Token and then re do request ... + if (!isRefreshed && + !accessToken.IsNullOrEmpty() && + !tokens.IsNull() && + tokens.IsRefreshable()) + { + // + request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON()); + + // + // Refreshe Tokens ... + var refreshedTokens = await identityProvider.RefreshTokens(tokens); + + // + // Renew Rest Client with Refreshed Tokens ... + var timeout = client.Timeout; + client = GetRestClient(refreshedTokens); + client.Timeout = Timeout.Infinite; + + // + // Do Request Again using renew Client ... + return await RunRestRequestByResponse( + client: client, + request: request, + method: method + ); + } + } + + // + var ex = resp.Content.ToXError(); + if (!ex.IsNull()) + { + throw ex.ToException(); + } + + // + // UnAuthorized ... + if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) + { + XException.NotAuthorized.Throw(); + } + + // + // NotFound ... + if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) + { + XException.NotFound.Throw(); + } + + // + XException.ActionFailed.Throw(); + } + + // + var result = new XBaseRestResponse + { + Response = resp, + Model = resp.Content.FromJSON() + }; + + // + return result; + }, cancellationToken); + + // + return response; + } + + /// + /// Get User SelectBy Param + /// + /// + /// + /// + /// + public string GetUserSelectByParam( + XActionRequest model, + bool forceNotNull = true, + ICollection excludes = null + ) + { + // + // Validate Args ... + validationProvider.NotNull(model); + + // + var id = model.UserId; + var userName = model.UserName; + var email = model.Email; + var phoneNumber = model.MobileNumber; + + // + if (excludes != null) + { + // + if (excludes.Contains(XUserSelectBy.ID)) + { + id = null; + } + if (excludes.Contains(XUserSelectBy.Email)) + { + email = null; + } + if (excludes.Contains(XUserSelectBy.MobileNumber)) + { + phoneNumber = null; + } + if (excludes.Contains(XUserSelectBy.Username)) + { + userName = null; + } + } + + var selectByParam = + id.IsNullOrEmpty() ? + userName.IsNullOrEmpty() ? + email.IsNullOrEmpty() ? + phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; + + // + // Check result ... + if (forceNotNull && + selectByParam.IsNullOrEmpty()) + { + XException.InvalidData.Throw(); + } + + // + return selectByParam; + } + #endregion + + // + #region Service ... + /// + /// Retrieve Bot Info ... + /// + /// + /// + public virtual async Task GetMe( + CancellationToken cancellationToken = default + ) + { + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.GetMe, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + } + ); + + // + var response = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.GET, + cancellationToken: cancellationToken + ); + + // + return response; + } + + /// + /// Sending Simple String Message to Bot ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task SendMessage( + long chatId, + string text, + XBotReplyMarkup replyMarkup = null, + XBotMessageParseMode parseMode = XBotMessageParseMode.Html, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (chatId <= 0 || text.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.SendMessage, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + } + ); + + // + request.AddJsonBody(new + { + text = text, + caht_id = chatId, + reply_markup = replyMarkup, + parse_mode = parseMode.GetStringValue() + }); + + // + var response = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.POST, + cancellationToken: cancellationToken + ); + + // + return response; + } + + /// + /// Sending Verification Request Menu ... + /// + /// + /// + /// + /// + public virtual async Task SendVerificationMenu( + long chatId, + string label = "🔐 دریافت کد وریفیکیشن", + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (chatId <= 0 || label.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + // Markup for Keyboards ... + var markup = new XBotReplyMarkup + { + // + InlineKeyboard = + [ + // + [ + // + new XBotInlineButton + { + Text = label, + CallbackData = "request_verification_code" + } + ] + ] + }; + + // + var response = await SendMessage( + chatId: chatId, + text: "برای دریافت کد وریفیکیشن روی دکمه زیر کلیک کنید:", + replyMarkup: markup, + cancellationToken: cancellationToken + ); + + // + return response; + } + + /// + /// Send Verification Code to Requests ... + /// + /// + /// + /// + /// + /// + public virtual async Task SendVerificationCode( + long chatId, + string code, + int ttlSeconds, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (chatId <= 0 || ttlSeconds < 60 || code.IsNullOrEmpty()) + { + XException.InvalidArgs.Throw(); + } + + // + var minutes = ttlSeconds / 60; + var response = await SendMessage( + chatId: chatId, + cancellationToken: cancellationToken, + text: $"✅ کد وریفیکیشن شما:\n\n{code}\n\n⏱ این کد تا {minutes} دقیقه معتبر است." + ); + + // + return response; + } + + /// + /// an Accept for Exit Loading on Bot ... + /// + /// + /// + /// + /// + /// + public virtual async Task AnswerCallbackQuery( + string callbackQueryId, + string text = null, + bool showAlert = false, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider.GroupValidationBuilder() + .AddNotEmpty(callbackQueryId) + .ValidateGroup(); + + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.AnswerCallbackQuery, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + } + ); + + // + request.AddJsonBody(new + { + text = text, + show_alert = showAlert, + callback_query_id = callbackQueryId, + }); + + // + var response = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.POST, + cancellationToken: cancellationToken + ); + + // + return response; + } + + /// + /// Remove Inline Keyboard After Click (Optional) ... + /// + /// + /// + /// + /// + public virtual async Task RemoveInlineKeyboard( + long chatId, + long messageId, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + if (chatId <= 0 || messageId <= 0) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.EditMessageReplyMarkup, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + } + ); + + // + request.AddJsonBody(new + { + chat_id = chatId, + message_id = messageId, + reply_markup = new { inline_keyboard = new List>() } + }); + + // + var response = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.POST, + cancellationToken: cancellationToken + ); + + // + return response; + } + + /// + /// Retrieve Messages ... + /// + /// + /// + /// + /// + public virtual async Task> GetUpdates( + long offset = 0, + int timeout = 30, + CancellationToken cancellationToken = default + ) + { + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.GetUpdates, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + }, + queryStrings: new Dictionary + { + { XBotParams.XOffest, offset.ToString() }, + { XBotParams.XTimeout, timeout.ToString() } + } + ); + + // + var iResponse = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.GET, + cancellationToken: cancellationToken + ); + var response = iResponse.Result ?? []; + + // + return response; + } + + /// + /// Set Webhook for Retrieve Messages on Recieved ... + /// + /// + /// + /// + /// + public virtual async Task SetWebhook( + string webhookUrl, + string secretToken = null, + CancellationToken cancellationToken = default + ) + { + // + var client = GetRestClient(); + var request = GetRestRequest( + endpoint: XBotEndpoints.SetWebhook, + @params: new Dictionary + { + { XBotParams.XTokenParam, configuration.Token } + } + ); + + // + request.AddJsonBody(new + { + url = webhookUrl, + secret_token = secretToken + }); + + // + var iResponse = await RunRestRequest( + client: client, + request: request, + method: XHttpMethod.POST, + cancellationToken: cancellationToken + ); + var response = iResponse?.Ok ?? false; + + // + return response; + } + #endregion + } +} \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261109_152617.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261109_152617.txt deleted file mode 100644 index 9561342..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261109_152617.txt +++ /dev/null @@ -1,39256 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Program.cs - -using System.Text; -using xLoggingService.DI; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace xAiApi -{ - public class Program - { - public static void Main(string[] args) - { - // - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - - // - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - // - var result = Host.CreateDefaultBuilder(args) - .ConfigureLogging(logging => - logging.AddXTelemetryLogger()) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .AddXTelemetry(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Startup.cs - -using System; -using System.IO; -using xAiApi.DI; -using System.Linq; -using xAiModels.DI; -using xAiService.DI; -using xTagService.DI; -using System.Net.Http; -using xAiApi.Database; -using xHttpService.DI; -using xPushService.DI; -using xFileService.DI; -using xDataService.DI; -using Newtonsoft.Json; -using System.Reflection; -using xAiApi.Extensions; -using xStringService.DI; -using xLoggingService.DI; -using xStorageService.DI; -using xIdentityService.DI; -using xDataService.Models; -using xCommons.Extensions; -using xAiModels.Constants; -using xPushService.Helpers; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using Newtonsoft.Json.Serialization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using IdentityModel.AspNetCore.OAuth2Introspection; - -namespace xAiApi -{ - public class Startup - { - // - #region Props ... - public IConfiguration Configuration { get; } - private readonly List databases; - private readonly XAiApiDatabaseDescriptor apiDatabaseDescriptor; - #endregion - - // - #region Constructor(s) ... - public Startup(IConfiguration configuration) - { - // - Configuration = configuration; - - // - // Create an Api Descriptor Class Instance ... - apiDatabaseDescriptor = new XAiApiDatabaseDescriptor(); - databases = new List - { - apiDatabaseDescriptor - }; - } - #endregion - - public void ConfigureServices(IServiceCollection services) - { - // - // Register Validation Provider and all XCommons Module Services ... - services.AddXCommons(Configuration); - - // - // Register App Configuration ... - services.AddXAppConfiguration(Configuration); - var appConfiguration = services.GetRegisteredService(); - - // - // Register Logging Service ... - services.AddXLoggingService(Configuration); - - // - // Register Allowed Origins ... - services.AddXCors(appConfiguration.AllowedOrigins); - - // - // Register Swagger ... - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - services.AddXSwagger(Configuration, xmlFilePath: xmlPath); - - // - // Register HttpService ... - services.AddXHttpService(Configuration); - - // - // Add Api V1 Versioning ... - services.AddXApiV1Versioning(); - - // - // OAuthIntrospectin Http Client Handler ... - // this is for handling SSLErrors ... - services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) - .ConfigurePrimaryHttpMessageHandler(() => - { - return new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true - }; - }); - - // - // Register Authorizations ... - services.AddXAuthorization(); - - // - services.AddControllers() - .AddNewtonsoftJson(x => - { - x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - }); - - // - var lifeTime = ServiceLifetime.Scoped; - var repositoryType = xDataService.Constants.XRepositoryType.EF; - - // - // Register XIdentity Service ... - services.AddXIdentityService( - lifeTime: lifeTime, - configuration: Configuration - ); - - // - // Storage Service ... - services.AddXStorageService(Configuration); - - // - // Push Service ... - services.AddXPushService( - lifeTime: lifeTime, - config: Configuration - ); - - // - // Preparing DataBases ... - if (databases.HasChild()) - { - // - databases - .ToList() - .ForEach(database => - { - // - // Register DataBase ... - services.AddXDatabase( - lifeTime: lifeTime, - descriptor: database, - configuration: Configuration - ); - }); - } - - // - // Register String Service ... - services.AddXStringService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Tag Service ... - services.AddXTagService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register File Service ... - services.AddXFileService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register AiApi Data Service ... - services.AddXAiDataService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register XAiApi Configuration ... - services.AddXAiApiConfiguration(Configuration); - - // - // Register MCP Server Provider ... - services.AddXAiMcpServerProvider(); - - // - // Register File Content Extractor Services ... - services.AddXAiFileContentExtractors(); - - // - // Register Text Chunker Service ... - services.AddXAiTextChunker(); - - // - // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... - services.AddXAiChatWithDocuments(); - - // - // Register XAiMcpClient ... - services.AddXAiMcpClient(); - - // - // Persistent RAG (Knowledge over XAiVector Table) ... - services.AddXRagService(); - - // - // Register Default AI Services ... - services.AddXAiServices(); - } - - public void Configure( - IApplicationBuilder app, - IWebHostEnvironment env - ) - { - // - // Configure the HTTP request pipeline. - // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors - // -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ... - var isDevelopmentEnvironment = env.IsDevelopment(); - if (isDevelopmentEnvironment) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute); - app.UseHsts(); - } - - // - // Setting Environment in App Confiuration ... - app.AddEnvironmentToXAppConfiguration(env.EnvironmentName); - - // - // Force Https Redirection ... - app.UseHttpsRedirection(); - - // - // Use Storage Service (Prepare Folders + Static Files) ... - // Must be before Routing so Static Files Short Circuit Pipeline ... - app.UseXStorageService(); - - // - // Use Swagger Middleware (Only in Development) ... - if (isDevelopmentEnvironment) - { - app.UseXSwagger(); - } - - // - // Using Cors (before Proxy so Browser Requests get CORS Headers) ... - app.UseXCors(); - - // - // Enable Model Proxy (Handles its own Authentication) ... - app.UseXAiModelProxy(); - - // - // Using Routing ... - app.UseRouting(); - - // - // Using Request Logging ... - if (!isDevelopmentEnvironment) - { - app.UseXRequestLogger(); - } - - // - // Use xIdentityService (Authentication) ... - app.UseXIdentityService(); - - // - // Use Authorization ... - app.UseAuthorization(); - - // - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - - // - // Use PushService (Legacy UseSignalR -> Registers its own Router) ... - var pushHelper = new XPushServiceHelper(); - app.UseXPushService(pushHelper); - - // - // Using DataBase ... - if (databases.HasChild()) - { - // - databases - .ToList() - .ForEach(database => - { - // - app.UseXDatabase( - descriptor: database, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - }); - } - - // - // Using String Service ... - app.UseXStringService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using XTag Service ... - app.UseXTagService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using File Service ... - app.UseXFileService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } -} - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Configurations\XAiApiConfiguration.cs - -using xAiApi.Models; -using xAiModels.Models; - -namespace xAiApi.Configurations -{ - public class XAiApiConfiguration - { - /// - /// Allowed Models to Use ... - /// - public XAiModelDescriptor[] Models { get; set; } = []; - - /// - /// Allowed Prompts to Use ... - /// - public XAiPromptDescriptor[] Prompts { get; set; } = []; - - /// - /// OCR Configuration ... - /// - public XAiOCRDescriptor OCR { get; set; } = new(); - - /// - /// Transcript Configuration ... - /// - public XAiTransciptDescriptor Transcript { get; set; } = new(); - - /// - /// PDF To Image Configuration ... - /// - public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new(); - - /// - /// Proxy Configuration ... - /// - /// - public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new(); - - /// - /// Text Chunker Configuration ... - /// - public XTextChunkerDescriptor TextChunker { get; set; } = new(); - - /// - /// RAG Configuration ... - /// - public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); - - /// - /// DateTime Configuration ... - /// - /// - public XDateTimeDescriptor DateTime { get; set; } = new(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs - -namespace xAiApi.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_API_NODE = "AiApiConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Constants\XAiApiConstants.cs - -namespace xAiApi.Constants -{ - public struct XAiApiConstants - { - // - // Database Descriptor ... - public const string XAiApiDbIdentifier = "xAiApiDb"; - public const string XAiApiMigrationsAssemblyIdentifier = "xAiApi"; - - // - public const string XDILogTag = "XAiApi"; - - // - public const string XAiApiRagPromptName = "ChatWithDocuments"; - public const string XAiApiIntroductionPromptName = "Introduction"; - public const string XAiApiContentExtractionPromptName = "ContentExtraction"; - - // - public const string XAiDefaultModelName = "Arion"; - public const string XAiEmbeddingModelName = "Embed"; - public const string XAiDefaultVisionModelName = "Qwen"; - public const string XAiDefaultThinkingModelName = "Qwen"; - public const string XAiEmbeddingPromptName = "Embedding"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityHelper.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Controllers -{ - public partial class AccountController : XAccountControllerBase - { - // - #region Constructor ... - public AccountController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\ChatWithDocumentsController.cs - -using System; -using System.Linq; -using xAiApi.Models; -using System.Threading; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Providers; -using xCommons.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xHttpService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Controllers; -using xAiApi.Interfaces.Extractors; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - /// - /// Chat With Documents (In-Memory RAG) Controller ... - /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session - /// - [Authorize] - public class ChatWithDocumentsController : XBaseIdentityApiV1Controller - { - /// - /// Default AI Service ... - /// - private readonly IXAiService aiService; - - /// - /// Text Chunker Service ... - /// - private readonly IXTextChunker textChunker; - - /// - /// In Memory Vector Store ... - /// - private readonly IXInMemoryVectorStore vectorStore; - - /// - /// XAiApi Configuration ... - /// - private readonly XAiApiConfiguration apiConfiguration; - - /// - /// Embedding Service ... - /// - private readonly IXAiEmbeddingService embeddingService; - - /// - /// File Context Extractor Service ... - /// - private readonly IXFileContentExtractor fileContentExtractor; - - public ChatWithDocumentsController( - IXAiService aiService, - IXTextChunker textChunker, - IXInMemoryVectorStore vectorStore, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XAiApiConfiguration apiConfiguration, - IXAiEmbeddingService embeddingService, - XValidationProvider validationProvider, - ILogger logger, - IXFileContentExtractor fileContentExtractor - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - // - this.aiService = aiService; - this.textChunker = textChunker; - this.vectorStore = vectorStore; - this.apiConfiguration = apiConfiguration; - this.embeddingService = embeddingService; - this.fileContentExtractor = fileContentExtractor; - } - - // - #region Ingest ... - /// - /// Ingest Files into a (new or existing) In-Memory Session: - /// Extract -> Chunk -> Embed -> Store ... - /// - /// - /// Optional: Add to an Existing Session - /// Optional: Session TTL in Minutes (only for new Session) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - public async Task> Ingest( - [FromForm] IFormFileCollection files, - [FromForm] Guid? sessionId = null, - [FromForm] int? ttlMinutes = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Resolve Target Session ... - Guid targetSessionId; - if (sessionId.HasValue && sessionId.Value != Guid.Empty) - { - // - if (!vectorStore.TryGet(sessionId.Value, out _, ownerId)) - { - XException.NotFound.Throw(); - } - targetSessionId = sessionId.Value; - } - else - { - // - var ttl = TimeSpan.FromMinutes( - ttlMinutes.HasValue && ttlMinutes.Value > 0 - ? ttlMinutes.Value - : apiConfiguration.RAGDescriptor.DefaultTtlMinutes - ); - targetSessionId = vectorStore.CreateSession(ownerId, ttl); - } - - // - var result = new XAiDocumentIngestResult - { - SessionId = targetSessionId - }; - - // - // Extract -> Chunk -> Embed ... - var vectors = new List(); - foreach (var file in files) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - if (file.IsNull() || file.Length == 0) - { - result.SkippedFiles.Add(file?.FileName ?? "(null)"); - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var text = await ExtractText(file, mimeType, cancellationToken); - if (string.IsNullOrWhiteSpace(text)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var chunks = textChunker.Chunk(text, file.FileName); - if (!chunks.HasChild()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Embed in Batches ... - var fileVectors = await EmbedChunks( - chunks: chunks, - fileName: file.FileName, - mimeType: mimeType, - cancellationToken: cancellationToken - ); - - // - vectors.AddRange(fileVectors); - result.FilesCount++; - } - - // - // Store ... - if (vectors.HasChild() && - !vectorStore.Add(targetSessionId, vectors, ownerId)) - { - XException.ActionFailed.Throw(); - } - - // - // Fill Result ... - result.ChunksCount = vectors.Count; - if (vectorStore.TryGet(targetSessionId, out var session, ownerId)) - { - lock (session.SyncRoot) - { - result.TotalVectorsCount = session.Vectors.Count; - } - result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl); - } - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Ask ... - /// - /// Ask a Question over Ingested Documents ... - /// - /// - /// - /// - [HttpPost("Ask")] - public async Task> Ask( - [FromBody] XAiDocumentAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Check Session ... - if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) - { - XException.NotFound.Throw(); - } - - // - // Retrieve ... - var context = await Retrieve(request, ownerId, cancellationToken); - - // - var result = new XAiDocumentAnswer - { - SessionId = request.SessionId, - Sources = ToSources(context) - }; - - // - if (!context.HasChild()) - { - result.NoContextFound = true; - return Ok(result); - } - - // - // Generate ... - result.Answer = await aiService.AskTextByContextAsync( - context: context, - userInfo: userInfo, - prompt: request.Prompt, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask a Question over Ingested Documents and Stream Response (SSE) ... - /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ... - /// - /// - /// - /// - [HttpPost("AskStream")] - public async Task AskStream( - [FromBody] XAiDocumentAskRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - // - Response.StatusCode = StatusCodes.Status400BadRequest; - Response.ContentType = "application/json; charset=utf-8"; - await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var ownerId = userInfo.UserId; - - // - // Check Session ... - if (!vectorStore.TryGet(request.SessionId, out _, ownerId)) - { - XException.NotFound.Throw(); - } - - // - // Retrieve ... - var context = await Retrieve(request, ownerId, cancellationToken); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - // First Event: Sources ... - var hasContext = context.HasChild(); - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = string.Empty, - IsFinal = !hasContext, - NoContextFound = !hasContext, - Sources = ToSources(context) - }, cancellationToken); - - // - if (!hasContext) - { - await Response.WriteSseDoneAsync(cancellationToken); - return; - } - - // - // Stream Deltas ... - var enumerable = aiService.AskTextByContextAsEnumerable( - context: context, - userInfo: userInfo, - prompt: request.Prompt, - cancellationToken: cancellationToken - ); - await foreach (var delta in enumerable) - { - // - if (delta.IsNullOrEmpty()) - { - continue; - } - - // - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = delta - }, cancellationToken); - } - - // - // Final Event ... - await WriteChunk(new XAiDocumentAnswerChunk - { - Text = string.Empty, - IsFinal = true - }, cancellationToken); - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "ChatWithDocuments: AskStream Failed"); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - #endregion - - // - #region Session ... - /// - /// Retrieve Session Info (without Embeddings) ... - /// - /// - /// - [HttpGet("Session/{id:guid}")] - public async Task> GetSession(Guid id) - { - // - try - { - // - var userInfo = await GetUserInfo(); - if (!vectorStore.TryGet(id, out var session, userInfo.UserId)) - { - XException.NotFound.Throw(); - } - - // - IList vectors; - lock (session.SyncRoot) - { - vectors = session.Vectors.ToList(); - } - - // - var result = new XAiDocumentSessionInfo - { - Id = session.Id, - Ttl = session.Ttl, - VectorsCount = vectors.Count, - CreatedAtUtc = session.CreatedAtUtc, - LastAccessAtUtc = session.LastAccessAtUtc, - ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl), - Files = [.. vectors - .Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)) - .Where(f => !f.IsNullOrEmpty()) - .Distinct()] - }; - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove a Session and Free Memory ... - /// - /// - /// - [HttpDelete("Session/{id:guid}")] - public async Task> DeleteSession(Guid id) - { - // - try - { - // - var userInfo = await GetUserInfo(); - if (!vectorStore.Remove(id, userInfo.UserId)) - { - XException.NotFound.Throw(); - } - - // - return Ok(true); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Private ... - /// - /// Extract Plain Text of a File (Text or Audio Transcript) ... - /// - private async Task ExtractText( - IFormFile file, - string mimeType, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var stream = file.OpenReadStream(); - var extraction = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - var result = extraction?.Text; - if (string.IsNullOrWhiteSpace(result)) - { - result = extraction?.AudioTranscript; - } - - // - return result; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors ... - /// - private async Task> EmbedChunks( - IList chunks, - string fileName, - string mimeType, - CancellationToken cancellationToken - ) - { - // - var result = new List(chunks.Count); - var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize; - - // - for (var offset = 0; offset < chunks.Count; offset += batchSize) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - var batch = chunks.Skip(offset).Take(batchSize).ToList(); - var embeddings = await embeddingService.Embeddings( - batch: batch.Select(c => c.Text).ToArray(), - cancellationToken: cancellationToken - ); - - // - if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) - { - XException.ActionFailed.Throw(); - } - - // - for (var i = 0; i < batch.Count; i++) - { - // - var chunk = batch[i]; - result.Add(new XAiVectorDto - { - Id = Guid.NewGuid(), - Text = chunk.Text, - Embedding = embeddings[i], - Identifier = chunk.Identifier, - Metadata = new Dictionary - { - [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName, - [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType, - [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString() - } - }); - } - } - - // - return result; - } - - /// - /// Embed Prompt and Search Session ... - /// - private async Task> Retrieve( - XAiDocumentAskRequest request, - string ownerId, - CancellationToken cancellationToken - ) - { - // - var topK = Math.Clamp( - request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK, - 1, - apiConfiguration.RAGDescriptor.MaxTopK - ); - var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore; - - // - var queryEmbedding = await embeddingService.Embedding( - content: request.Prompt, - cancellationToken: cancellationToken - ); - if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) - { - XException.ActionFailed.Throw(); - } - - // - var result = vectorStore.Search( - topK: topK, - ownerId: ownerId, - minScore: minScore, - sessionId: request.SessionId, - queryEmbedding: queryEmbedding - ); - - // - return result ?? []; - } - - /// - /// Map Search Results to Public Sources ... - /// - private IList ToSources( - IEnumerable context - ) - { - // - var result = (context ?? []) - .Select(c => - { - // - var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex); - var text = c.Text ?? string.Empty; - var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength); - - // - return new XAiDocumentSource - { - Score = c.Score, - Identifier = c.Identifier, - Snippet = text.Substring(0, snippetLength), - ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null, - FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName) - }; - }) - .ToList(); - - // - return result; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\KnowledgeController.cs - -using System; -using xAiApi.Models; -using System.Threading; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Controllers; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using xIdentityHelper; - -namespace xAiApi.Controllers -{ - /// - /// Knowledge (Persistent RAG over XAiVector Table) Controller ... - /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete - /// - [Authorize] - public class KnowledgeController : XBaseIdentityApiV1Controller - { - /// - /// Persistent RAG Service ... - /// - private readonly IXAiRAGService ragService; - - public KnowledgeController( - IXAiRAGService ragService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - this.ragService = ragService; - } - - // - #region Ingest ... - /// - /// Ingest Files into a Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store in XAiVector Table ... - /// - /// - /// Target Scope: User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type / Domain - /// Replace Previously Stored Vectors of Same File (default true) - /// - /// - [HttpPost("Ingest")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> Ingest( - [FromForm] IFormFileCollection files, - [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromForm] Guid? scopeId = null, - [FromForm] string knowledgeType = null, - [FromForm] bool replaceExisting = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await ragService.IngestAsync( - files: files, - userInfo: userInfo, - connectionId: connectionId, - replaceExisting: replaceExisting, - cancellationToken: cancellationToken, - scope: BuildScope(scope, scopeId, knowledgeType) - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Documents ... - /// - /// List Ingested Documents of a Knowledge Scope ... - /// - /// User (default) / Project / Conversation / Global - /// ProjectId or ConversationId (Required for Project / Conversation) - /// Optional Knowledge Type Filter - /// - /// - [HttpGet("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task>> Documents( - [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromQuery] Guid? scopeId = null, - [FromQuery] string knowledgeType = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType); - - // - var result = await ragService.LoadDocumentsAsync( - userInfo: userInfo, - scope: scopeIdentifier, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove All Vectors of a Document in a Knowledge Scope ... - /// - /// - /// User (default) / Project / Conversation / Global (Admin) - /// ProjectId or ConversationId (Required for Project / Conversation) - /// - /// Count of Removed Vectors - [HttpDelete("Documents")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task> DeleteDocument( - [FromQuery] string fileName, - [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global, - [FromQuery] Guid? scopeId = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotEmpty(fileName); - - // - var userInfo = await GetUserInfo(); - - // - var result = await ragService.RemoveDocumentAsync( - fileName: fileName, - userInfo: userInfo, - cancellationToken: cancellationToken, - scope: BuildScope(scope, scopeId, null) - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Private ... - /// - /// Build Scope Descriptor from Request Params ... - /// - private XAiKnowledgeScopeDescriptor BuildScope( - XAiKnowledgeScope? scope, - Guid? scopeId, - string knowledgeType - ) - { - // - if (!scope.HasValue) - { - scope = XAiKnowledgeScope.Global; - } - - // - var result = new XAiKnowledgeScopeDescriptor - { - Scope = scope.Value, - ScopeId = scopeId, - Type = knowledgeType, - }; - - // - return result; - } - - /// - /// Write a SSE Event ... - /// - private Task WriteChunk( - XAiDocumentAnswerChunk chunk, - CancellationToken cancellationToken - ) - { - // - return Response.WriteSseEventAsync( - data: chunk, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\McpServersController.cs - -using System; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiModels.Models.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - [Authorize] - public class McpServersController : XBaseIdentityApiV1Controller - { - private readonly IXAiMcpServerProvider mcpServerProvider; - - public McpServersController( - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.mcpServerProvider = mcpServerProvider; - } - - // - #region Provider ... - /// - /// Retrieve Specified MCP Server ... - /// - /// - /// - /// - [HttpGet("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> GetMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.GetMcpServer( - id: id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add MCP Server ... - /// - /// - /// - /// - [HttpPost] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AddMcpServer( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || item.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.AddMcpServer( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update Specified MCP Server ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> UpdateMcpServer( - [FromRoute] Guid id, - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id.IsDefaultGuid() || - !ModelState.IsValid || - !item.IsValidForAddOrUpdate()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.UpdateMcpServer( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified MCP Server ... - /// - /// - /// - /// - [HttpDelete("{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> RemoveMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.RemoveMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Enable Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Enable")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> EnableMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.EnableMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Disable Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Disable")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> DisableMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.DisableMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Toggle Specified MCP Server ... - /// - /// - /// - /// - [HttpPost("{id}/Toggle")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> ToggleMcpServer( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.ToggleMcpServer( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get all Registered MCP Servers by handling Ownership ... - /// - /// - /// - [HttpGet] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetMcpServers( - [FromQuery] bool forceOwner = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.GetAll( - userInfo: userInfo, - forceOwner: forceOwner, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Registered MCP Servers by handling Ownership ... - /// - /// - /// - /// - /// - [HttpGet("Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryMcpServers( - [FromQuery] XQuery query, - [FromQuery] bool forceOwner = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await mcpServerProvider.Query( - query: query, - userInfo: userInfo, - forceOwner: forceOwner, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - /// - /// Refresh MCP Servers ... - /// - /// - /// - [HttpPost("Refresh")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task RefreshMcpServers( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - await mcpServerProvider.RefreshAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } catch(Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\StartupController.cs - -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - /// - /// Runing when application start ... - /// - [Route("")] - [AllowAnonymous] - public class StartupController : XBaseController - { - - public StartupController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { } - - /// - /// Show Configured Welcome Message - /// - /// - [HttpGet("")] - [AllowAnonymous] - public virtual ActionResult Index() - { - // - var controllerName = GetControllerName(); - var message = $"{AppConfiguration.WelcomeMessage}"; - - // - return Ok(message); - } - - /// - /// Global Exception Handler Endpoint (Production) ... - /// Returns a Generic Error without Leaking Exception Details ... - /// - /// - [AllowAnonymous] - [Route("error")] - [ApiExplorerSettings(IgnoreApi = true)] - public virtual ActionResult Error() - { - // - var error = XException.ActionFailed.ToXError(); - return StatusCode(StatusCodes.Status500InternalServerError, error); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\TestIdentity.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using xIdentityHelper.Controllers; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Controllers { - /// - /// Test all Authentication Policies ... - /// - public class TestIdentity : XTestIdentityControllerBase { - public TestIdentity ( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base ( - logger, - appConfiguration, - identityProvider, - validationProvider - ) { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\XAiController.cs - -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - [Authorize] - public class XAiController : XAiServiceControllerBase - { - public XAiController( - ILogger logger, - IXAiService aiService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - aiService, - appConfiguration, - identityProvider, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\XAiServiceControllerBase.cs - -using System; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xAiModels.Models; -using xAiApi.Extensions; -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiModels.Models.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xAiApi.Controllers -{ - [Authorize] - public abstract class XAiServiceControllerBase : XBaseIdentityApiV1Controller - where TAiService : IXAiServiceBase - { - private readonly TAiService aiService; - - protected XAiServiceControllerBase( - ILogger logger, - TAiService aiService, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.aiService = aiService; - } - - // - #region Actions ... - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpGet("AskText")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AskText( - [FromQuery] string question, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotEmpty(question); - - // - var userInfo = await GetUserInfo(); - - // - var result = await aiService.AskTextAsync( - prompt: question, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [HttpGet("AskTextStream")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task AskTextStream( - [FromQuery] string question, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (question.IsNullOrEmpty()) - { - await WriteStreamValidationError(); - return; - } - - // - try - { - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - var userInfo = await GetUserInfo(); - - // - var enumerable = aiService.AskTextAsEnumerable( - prompt: question, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - // Format: data: {"text":"..."}\n\n - await foreach (var chunk in enumerable) - { - // - // Skip Empty Chunks ... - if (string.IsNullOrEmpty(chunk)) - { - continue; - } - - // - await Response.WriteSseEventAsync( - data: new { text = chunk }, - cancellationToken: cancellationToken - ); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "AskTextStream Failed"); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - [HttpGet("AskTextFromKnowledge")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AskTextFromKnowledge( - [FromQuery] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.AskTextFromKnowledgeAsync( - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - [HttpGet("AskTextFromKnowledgeStream")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task AskTextFromKnowledgeStream( - [FromQuery] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - await WriteStreamValidationError(); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - var enumerable = aiService.AskTextFromKnowledgeAsEnumerable( - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - cancellationToken: cancellationToken - ); - - // - // Format: data: {json}\n\n - await foreach (var resp in enumerable) - { - // - // Skip Empty Responses ... - if (resp.IsNullOrDefault()) - { - continue; - } - - // - await Response.WriteSseEventAsync( - data: resp, - cancellationToken: cancellationToken - ); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "AskStream Failed ..."); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - - /// - /// Ask Question and Get Response ... - /// - /// - /// - /// - [HttpPost("Ask")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> Ask( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.AskAsync( - files: null, - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask Question and Get Response Stream ... - /// - /// - /// - /// - [HttpPost("AskStream")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task AskStream( - [FromBody] XAiResponseRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - await WriteStreamValidationError(); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - var enumerable = aiService.AskAsEnumerable( - files: null, - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - // Format: data: {json}\n\n - await foreach (var resp in enumerable) - { - // - // Skip Empty Responses ... - if (resp.IsNullOrDefault()) - { - continue; - } - - // - await Response.WriteSseEventAsync( - data: resp, - cancellationToken: cancellationToken - ); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "AskStream Failed ..."); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - - /// - /// Ask Question with Files and Get Response ... - /// - /// - /// - /// - [HttpPost("AskWithFiles")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AskWithFiles( - [FromForm] XAiResponseRequest request, - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.AskAsync( - files: files, - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Ask Question with Files and Get Response Stream ... - /// - /// - /// - /// - [HttpPost("AskWithFilesStream")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task AskWithFilesStream( - [FromForm] XAiResponseRequest request, - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - // Validate (before Stream Starts -> Proper Http Error) ... - if (!request.IsValid()) - { - await WriteStreamValidationError(); - return; - } - - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Configure SSE Response ... - Response.PrepareSseResponse(); - - // - var enumerable = aiService.AskAsEnumerable( - files: files, - topK: request.TopK, - userInfo: userInfo, - type: request.Type, - prompt: request.Prompt, - minScore: request.MinScore, - connectionId: connectionId, - projectId: request.ProjectId, - cancellationToken: cancellationToken, - conversationId: request.ConversationId - ); - - // - // Format: data: {json}\n\n - await foreach (var resp in enumerable) - { - // - // Skip Empty Responses ... - if (resp.IsNullOrDefault()) - { - continue; - } - - // - await Response.WriteSseEventAsync( - data: resp, - cancellationToken: cancellationToken - ); - } - - // - await Response.WriteSseDoneAsync(cancellationToken); - } - catch (Exception ex) when (ex.IsClientCancellation(cancellationToken)) - { - // Client Disconnected ... - } - catch (Exception ex) - { - // - Logger.LogError(ex, "AskStream Failed ..."); - if (!Response.HasStarted) - { - // - var result = GetExceptionActionResult(ex); - await result.ExecuteResultAsync(ControllerContext); - return; - } - - // - await Response.WriteSseErrorAsync(ex.Message); - } - } - #endregion - - // - #region Loaders ... - /// - /// Retrieve AI Projects ... - /// - /// - /// - /// - [HttpGet("Projects")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> LoadProjects( - [FromQuery] bool includeDefaults = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.LoadProjects( - ownerId: userInfo.UserId, - connectionId: connectionId, - includeDefaults: includeDefaults, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Specified AI Project's Conversations ... - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Projects/{projectId}/Conversations")] - public async Task>> LoadConversations( - [FromRoute] Guid projectId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.LoadConversations( - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Specified AI Conversation's Messages ... - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Conversations/{conversationId}/Messages")] - public async Task>> LoadMessages( - [FromRoute] Guid conversationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await aiService.LoadMessages( - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - /// - [HttpGet("Projects/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryProjects( - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.QueryProjects( - query: query, - ownerId: userInfo.UserId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Projects/{projectId}/Conversations/Query")] - public async Task>> QueryConversations( - [FromRoute] Guid projectId, - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.QueryConversations( - query: query, - projectId: projectId, - ownerId: userInfo.UserId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Conversations/{conversationId}/Messages/Query")] - public async Task>> QueryMessages( - [FromRoute] Guid conversationId, - [FromQuery] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await aiService.QueryMessages( - query: query, - ownerId: userInfo.UserId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - [HttpPost("Projects")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> CreateProject( - [FromBody] XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (item.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Update Required Params ... - item.OwnerId = userInfo.UserId; - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidData.Throw(); - } - - // - var result = await aiService.CreateProject( - item: item, - ownerId: userInfo.UserId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Projects/{projectId}/Conversations")] - public async Task> CreateConversation( - [FromRoute] Guid projectId, - [FromBody] XAiConversationDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (projectId.IsDefaultGuid() || - item.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Update Required Params ... - item.OwnerId = userInfo.UserId; - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidData.Throw(); - } - - // - var result = await aiService.CreateConversation( - item: item, - projectId: projectId, - ownerId: userInfo.UserId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Content Extraction ... - /// - /// Extract Files Content ... - /// - /// - /// - /// - /// - [HttpPost("ExtractContent")] - [Consumes("multipart/form-data")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> ExtractContent( - [FromForm] IFormFileCollection files, - [FromForm] string extractors = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - string[] extractorArr = null; - if (!extractors.IsNullOrEmpty()) - { - extractorArr = [.. extractors.ParseListString()]; - } - - // - var result = await aiService.ExtractContent( - files: files, - extractors: extractorArr, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Non Actions ... - /// - /// Write Validation Error for Streaming Endpoints (before Stream Starts) ... - /// - /// - [NonAction] - protected async Task WriteStreamValidationError() - { - // - Response.StatusCode = StatusCodes.Status400BadRequest; - Response.ContentType = "application/json; charset=utf-8"; - await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON()); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDatabaseDescriptor.cs - -using xAiApi.Constants; -using xDataService.Interfaces; -using xDataService.Models; - -namespace xAiApi.Database -{ - /// - /// Ai Api Database Descriptor ... - /// - public class XAiApiDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor - { - public XAiApiDatabaseDescriptor() : base( - name: XAiApiConstants.XAiApiDbIdentifier, - repositories: [] - ) - { - OptionsBuilder = b => b.MigrationsAssembly(XAiApiConstants.XAiApiMigrationsAssemblyIdentifier); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDbContext.cs - -using xDataService.Db; -using xAiApi.Constants; -using xAiModels.Providers; -using xTagService.Providers; -using xDataService.Providers; -using xFileService.Providers; -using xStringService.Providers; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xAiApi.Database -{ - /// - /// Db Context of AiApi ... - /// - public class XAiApiDbContext : XDbContext - { - // - #region DbSets ... - #endregion - - // - #region Navigation Property Entities ... - #endregion - - // - #region Constructor ... - public XAiApiDbContext( - DbContextOptions options, - XDataServiceConfiguration config, - XEntityRegisterarHandlerService dynamicEntityHandlers - ) : base( - config: config, - options: options, - database: XAiApiConstants.XAiApiDbIdentifier, - dynamicEntityHandlers: dynamicEntityHandlers, - dynamicEntityRegisterarsNames: [ - nameof(XTagEntityRegisterar), - nameof(XFileEntityRegisterar), - nameof(XStringEntityRegisterar), - nameof(XAiVectorEntityRegisterar), - nameof(XAiMessageEntityRegisterar), - nameof(XAiProjectEntityRegisterar), - nameof(XAiMcpServerEntityRegisterar), - nameof(XAiConversationEntityRegisterar), - ] - ) - { } - #endregion - - // - #region Overrides ... - // - public override void OnXModelCreating(ModelBuilder modelBuilder) - { } - - // - public override void OnXConfiguring(DbContextOptionsBuilder optionsBuilder) - { } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\DI\XDIHelperExtension.cs - -using System; -using xAiApi.Constants; -using xAiApi.Providers; -using xAiApi.Extensions; -using xAiApi.Interfaces; -using xAiApi.Middlewares; -using xCommons.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiApi.Providers.Extractors; -using xAiApi.Interfaces.Extractors; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiApi.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Extract AI Configuration ... - /// - /// - /// - public static XAiApiConfiguration GetXAiApiConfiguration(this IConfiguration source) - { - // - XAiApiConfiguration result = null; - - // - var section = source.GetSection(ConfigurationNodeNames.AI_API_NODE); - if (!section.IsNull()) - { - result = section.Get(); - } - - // - return result; - } - - /// - /// Register AiApi Configuration ... - /// - /// - /// - public static void AddXAiApiConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var apiConfig = configuration.GetXAiApiConfiguration(); - source.AddXAiApiConfiguration(apiConfig); - } - - /// - /// Register AiApi Configuration ... - /// - /// - /// - public static void AddXAiApiConfiguration( - this IServiceCollection source, - XAiApiConfiguration configuration - ) - { - // - if (!configuration.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Register Rag Service ... - /// - /// - public static void AddXRagService( - this IServiceCollection source - ) - { - // - // Persistent RAG (Knowledge over XAiVector Table) ... - source.AddScoped(); - source.AddScoped(); - } - - /// - /// Register Ai Services ... - /// - /// - public static void AddXAiServices( - this IServiceCollection source - ) - { - // - source.AddScoped(); - source.AddScoped(); - } - - /// - /// Register AiApi File Content Extractor Services ... - /// - /// - public static void AddXAiFileContentExtractors( - this IServiceCollection source - ) - { - // - // Register File Content Extractors ... - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - source.AddSingleton(); - - // - source.AddSingleton(); - } - - /// - /// Register AiApi Text Chunker Service ... - /// - /// - public static void AddXAiTextChunker( - this IServiceCollection source - ) - { - // - // Stateless -> Singleton ... - source.AddSingleton(); - } - - /// - /// Register In-Memory Vector Store Service ... - /// - public static void AddXAiInMemoryVectorStore(this IServiceCollection source) - { - source.AddSingleton(); - source.AddHostedService(); - } - - /// - /// Register all Services Required for Chat With Documents (In-Memory RAG): - /// Text Chunker + In-Memory Vector Store (+ Cleanup) ... - /// - /// - public static void AddXAiChatWithDocuments(this IServiceCollection source) - { - source.AddXAiInMemoryVectorStore(); - } - - /// - /// Use Model Proxy Provider ... - /// - /// - /// - public static IApplicationBuilder UseXAiModelProxy( - this IApplicationBuilder source - ) - { - return source.UseMiddleware(); - } - - // - #region Private ... - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XAiApiConstants.XDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XModelsExtensions.cs - -using System; -using OpenAI; -using System.Linq; -using OllamaSharp; -using xAiApi.Models; -using System.Net.Http; -using xAiApi.Constants; -using xAiModels.Models; -using System.Threading; -using System.ClientModel; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using Microsoft.Extensions.AI; -using System.Collections.Generic; -using System.ClientModel.Primitives; - -namespace xAiApi.Extensions -{ - public static class XModelsExtensions - { - /// - /// Validate Configurations ... - /// - /// - /// - public static bool IsValid(this XAiApiConfiguration source) - { - // - var result = - !source.IsNullOrDefault() && - source.Models.HasChild() && - source.Models.All(m => m.IsValid()) && - source.Prompts.All(m => m.IsValid()) && - source.Prompts.Any(p => p.Name - .Equals( - XAiApiConstants.XAiApiIntroductionPromptName, - StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Check TextChunker Descriptor is Valid or not ... - /// - /// - /// - public static bool IsValid(this XTextChunkerDescriptor source) - { - // - var result = - source.ChunkSize > 0 && - source.ChunkOverlap >= 0 && - source.ChunkOverlap < source.ChunkSize && - source.MinChunkSize >= 0 && - source.MinChunkSize <= source.ChunkSize; - - // - return result; - } - - /// - /// Check Document Ask Request is Valid or not ... - /// - /// - /// - public static bool IsValid(this XAiDocumentAskRequest source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Prompt.IsNullOrEmpty() && - !source.SessionId.IsDefaultGuid(); - - // - return result; - } - - /// - /// Extract Default Model Descriptor ... - /// - /// - /// - public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source) - { - // - XAiModelDescriptor result = null; - - // - if (source.IsValid()) - { - result = source.Models[0]; - } - - // - return result; - } - - /// - /// Retrieve Specified Model from Config ... - /// - /// - /// - /// - public static XAiModelDescriptor GetModel( - this XAiApiConfiguration source, - string name - ) - { - // - XAiModelDescriptor result = null; - - // - if (source.IsValid()) - { - // - if (name.IsNullOrEmpty()) - { - result = source.GetDefaultModel(); - } - else - { - result = source.Models - .FirstOrDefault(m => m.Name - .Equals(name, System.StringComparison.InvariantCultureIgnoreCase)); - } - } - - // - return result; - } - - /// - /// Retrieve Introduction Prompt ... - /// - /// - /// - public static XAiPromptDescriptor GetIntroductionPrompt(this XAiApiConfiguration source) - { - // - XAiPromptDescriptor result = null; - - // - if (source.IsValid()) - { - // - result = source.Prompts - .FirstOrDefault(p => p.Name - .Equals( - XAiApiConstants.XAiApiIntroductionPromptName, - System.StringComparison.InvariantCultureIgnoreCase)); - } - - // - return result; - } - - /// - /// Select Specified Prompts and Parse it's Template - /// and Generate Message ... - /// - /// - /// - /// - /// - public static string GetPrompt( - this XAiApiConfiguration source, - string name = null, - IDictionary @params = null - ) - { - // - var result = string.Empty; - - // - // Normalize ... - if (name.IsNullOrEmpty()) - { - name = XAiApiConstants.XAiApiIntroductionPromptName; - } - - // - if (source.IsValid()) - { - // - var prompt = source.Prompts - .FirstOrDefault(p => p.Name - .Equals( - name, - System.StringComparison.InvariantCultureIgnoreCase - ) - ); - if (!prompt.IsNullOrDefault()) - { - // - result = prompt.Template; - - // - // Handle Params ... - if (!@params.IsNullOrDefault() && @params.HasChild()) - { - // - // Select Params ... - var existsParams = prompt.Params - .Where(p => @params.Any(pr => pr.Key == p.Name)) - .Distinct() - .ToList(); - - // - // Replace Selected Params ... - existsParams - .ForEach(pk => - { - result = result.Replace(pk.Param, @params[pk.Name]); - }); - } - } - } - - // - return result; - } - - /// - /// Provide HttpClient for Common Usages ... - /// - /// - /// - public static HttpClient GetHttpClient(this string source) - { - // - var result = new HttpClient - { - // - // Disable timeout completely (not recommended for production) - Timeout = Timeout.InfiniteTimeSpan, - - // - BaseAddress = source.IsNullOrEmpty() - ? null - : new Uri(source), - - // - // OR set a very long timeout (e.g., 30 minutes for large file uploads) - // Timeout = TimeSpan.FromMinutes(30) - }; - - // - return result; - } - - /// - /// Instance and Retrieve Chat Client ... - /// - /// - /// - public static IChatClient GetClient(this XAiModelDescriptor source) - { - // - // Try to Initialize LLm ... - var model = source.LLM; - var apiKey = source.ApiKey; - var url = new Uri(source.Url); - var httpClient = source.Url.GetHttpClient(); - - // - IChatClient result = null; - switch (source.Provider) - { - // - case XAiModelProviderType.Ollama: - // - // Instance Ollama Client using Custom HttpCLient ... - var ollamaClient = new OllamaApiClient(httpClient, model); - result = - new ChatClientBuilder(ollamaClient) - .UseFunctionInvocation() - .Build(); - break; - - // - case XAiModelProviderType.OpenAI: - // - // Instance Ollama Client using Custom HttpCLient ... - var openAiClient = new OpenAIClient( - new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey), - new OpenAIClientOptions - { - Endpoint = url, - Transport = new HttpClientPipelineTransport(httpClient) - } - ); - result = - new ChatClientBuilder( - openAiClient - .GetChatClient(model) - .AsIChatClient()) - .UseFunctionInvocation() - .Build(); - break; - - // - case XAiModelProviderType.DeepSeek: - break; - - // - case XAiModelProviderType.HuggingFace: - break; - - // - default: - break; - } - - // - if (result.IsNullOrDefault()) - { - XException.InvalidData.Throw(); - } - - // - return result; - } - - // public static IList ToAITools(this IList source) - // { - // // - // var result = new List(); - - // // - // foreach (var tool in source) - // { - // // - // var declaration = AIFunctionFactory.CreateDeclaration( - // name: tool.Name, - // jsonSchema: tool.InputSchema, - // description: tool.Description - // ); - - // // - // result.Add(declaration); - // } - - // // - // return result; - // } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs - -using System.Linq; -using xIdentityHelper; -using xAiApi.Providers; -using xAiApi.Interfaces; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiApi.Extensions -{ - public static class XProgramExtensions - { - /// - /// Register MCP Server Provider ... - /// - /// - public static void AddXAiMcpServerProvider( - this IServiceCollection source - ) - { - source.AddScoped(); - } - - /// - /// Register Authorization Policies - /// - /// - /// - public static void AddXAuthorization( - this IServiceCollection services, - IDictionary policies = null - ) - { - // - var policyHandler = services.GetRegisteredService(); - services.AddAuthorization(options => - { - // - if (!policies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = policies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - var policyDescriptor = policiesEnumerator.Current; - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - - // - var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); - if (!xPolicies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = xPolicies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - // - var policyDescriptor = policiesEnumerator.Current; - - // - // Add Policy to Authorization ... - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - }); - - // - services.AddSingleton(); - } - - /// - /// Use Forward Headers Options for resolving behind a proxy issues ... - /// - /// - /// - public static void UseXForwardOptions(this IApplicationBuilder source) - { - // - var forwardOptions = new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, - RequireHeaderSymmetry = false - }; - - // - forwardOptions.KnownNetworks.Clear(); - forwardOptions.KnownProxies.Clear(); - - // - // ref: https://github.com/aspnet/Docs/issues/2384 - source.UseForwardedHeaders(forwardOptions); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingService.cs - -namespace xAiApi.Interfaces -{ - public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceBase.cs - -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// Base Embedding Provider Service ... - /// - public interface IXAiEmbeddingServiceBase // : IXAiServiceBase - { - /// - /// Embedding Specified String ... - /// - /// - /// - /// - Task Embedding( - string content, - CancellationToken cancellationToken = default - ); - - /// - /// Embedding Specified Batch ... - /// - /// - /// - /// - Task> Embeddings( - string[] batch, - CancellationToken cancellationToken = default - ); - - /// - /// Embedding Generator ... - /// - /// - IEmbeddingGenerator> GetEmbeddingGenerator(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiMcpServerProvider.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xAiModels.Models.Dtos; -using xIdentityModels.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using ModelContextProtocol.Client; -using Microsoft.Extensions.AI; - -namespace xAiApi.Interfaces -{ - /// - /// MCP Manager / Provider ... - /// - public interface IXAiMcpServerProvider - { - // - #region Manager ... - /// - /// Get a List Of Available Tools which Provided using registered Mcp Servers ... - /// - /// - /// - /// - /// - Task> GetAvailableToolsAsync( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Test Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task TestServerAsync( - XAiMcpServerDto server, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Force Refresh Mcp Servers ... - /// - /// - /// - /// - Task RefreshAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Actions ... - /// - /// Add an Mcp Server ... - /// - /// - /// - /// - /// - /// - Task AddMcpServer( - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get an Mcp Server ... - /// - /// - /// - /// - /// - Task GetMcpServer( - Guid id, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateMcpServer( - Guid id, - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task RemoveMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Disable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task DisableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Enable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task EnableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Toggle Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task ToggleMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Mcp Server ... - /// - /// - /// - /// - /// - Task> GetAll( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - Task FindOne( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a Collection of Specified Mcp Servers ... - /// - /// - /// - /// - /// - /// - Task> FindMany( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Query Registered Mcp Servers ... - /// - /// - /// - /// - /// - /// - Task> Query( - XQuery query, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiRAGService.cs - -using xAiApi.Models; -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// Persistent RAG Service over XAiVector Table: - /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ... - /// Isolation is Scope Based (Conversation / Project / User / Global) ... - /// - public interface IXAiRAGService - { - /// - /// Ingest Files into Specified Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store (XAiVector) ... - /// - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - /// - /// - Task IngestAsync( - IFormFileCollection files, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - bool replaceExisting = true, - CancellationToken cancellationToken = default - ); - - /// - /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... - /// - /// - /// - /// - /// - Task> RetrieveAsync( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// List Ingested Documents of Specified Scope ... - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - Task> LoadDocumentsAsync( - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove All Vectors of a Document in Specified Scope ... - /// - /// - /// Target Scope (Null = User Scope) - /// - /// - /// - /// Count of Removed Vectors - Task RemoveDocumentAsync( - string fileName, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ... - /// Idempotent: Returns 0 when Nothing Left to Migrate ... - /// - /// - /// - /// Count of Migrated Vectors - Task MigrateLegacyVectorsAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Map Search Results to Public Sources ... - /// - /// - /// - IList ToSources( - IEnumerable context - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiService.cs - -namespace xAiApi.Interfaces -{ - public interface IXAiService : IXAiServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiServiceBase.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xAiModels.Models; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// Describe a Base Service Actions of any Ai Based Services ... - /// - public interface IXAiServiceBase : IDisposable - { - /// - /// Chat Options ... - /// - ChatOptions Options { get; } - - /// - /// Descriptor of Models which used in Service ... - /// - XAiModelDescriptor Descriptor { get; } - - // - #region Actions ... - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - Task AskTextAsync( - string prompt, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - IAsyncEnumerable AskTextAsEnumerable( - string prompt, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Providing Vector Search Result ... - /// - /// - /// - /// - /// - /// - Task AskTextByContextAsync( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By By Providing Vector Search Result and Stream Response ... - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskTextByContextAsEnumerable( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - /// - /// - /// - /// - Task AskTextFromKnowledgeAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question as Prompt and Retrieve Response ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task AskAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable AskAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Loaders ... - /// - /// Load AI Projects ... - /// - /// - /// - /// - /// - /// - Task> LoadProjects( - string ownerId, - string connectionId = null, - bool includeDefaults = false, - CancellationToken cancellationToken = default - ); - - /// - /// Load Conversations of Specified AI Project ... - /// - /// - /// - /// - /// - Task> LoadConversations( - Guid projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - /// - /// - Task CreateProject( - string ownerId, - XAiProjectDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - /// - /// - Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Content Extraction ... - /// - /// Try to Extract Files Content ... - /// - /// - /// - /// - /// - Task ExtractContent( - IFormFileCollection files, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultThinkingAiService.cs - -namespace xAiApi.Interfaces -{ - public interface IXDefaultThinkingAiService: IXAiServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXInMemoryVectorStore.cs - -using System; -using xAiApi.Models; -using xAiModels.Models.Dtos; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - public interface IXInMemoryVectorStore - { - int Count { get; } - int RemoveExpired(); - Guid CreateSession( - string ownerId = null, - TimeSpan? ttl = null - ); - Guid CreateSession( - IEnumerable vectors, - string ownerId = null, - TimeSpan? ttl = null - ); - bool Replace( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ); - bool Add( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ); - IList Search( - Guid sessionId, - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, - string ownerId = null - ); - bool TryGet( - Guid sessionId, - out XAiDocumentSession session, - string ownerId = null - ); - bool Remove( - Guid sessionId, - string ownerId = null - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXTextChunker.cs - -using xAiApi.Models; -using System.Collections.Generic; - -namespace xAiApi.Interfaces -{ - /// - /// a Service for Splitting Long Texts into Overlapping Chunks - /// which Suitable for Embedding ... - /// - public interface IXTextChunker - { - /// - /// Split Text into Chunks ... - /// - /// Source Text - /// Source Name (e.g. File Name) used for Identifier - /// - IList Chunk( - string text, - string source = null - ); - - /// - /// Split Text into Chunks and Return only Texts ... - /// - /// - /// - IList ChunkTexts( - string text - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXAudioFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXAudioFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXCodeFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for source code files ... - /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) - /// - public interface IXCodeFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXDocxFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXDocxFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXEpubFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for EPUB electronic publication format - /// (application/epub+zip) - /// - public interface IXEpubFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXExcelFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXExcelFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXFileContentExtractor.cs - -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using xAiModels.Models; - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// a Base Service for Extracting File Content ... - /// - public interface IXFileContentExtractorBase - { - /// - /// Check if this extractor supports the specified MIME type ... - /// - bool CanExtract(string mimeType); - - /// - /// Extract text content from file stream ... - /// - Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ); - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ); - } - - /// - /// a Service for Extracting File Content ... - /// - public interface IXFileContentExtractor - { - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - /// - bool CanExtract( - string mimeType, - string[] extractors = null - ); - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - /// - Task ExtractAsync( - Stream fileStream, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - /// - Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ); - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXHtmlFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for HTML documents (text/html, application/xhtml+xml) - /// - public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXImageFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXImageFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXOpenDocumentFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for OpenDocument Format (ODF) documents - /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) - /// - public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPdfFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXPdfFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPlainTextFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXPlainTextFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPowerPointFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for all PowerPoint Presentation formats - /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot) - /// - public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXRtfFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - /// - /// Extractor for Rich Text Format (RTF) documents - /// (application/rtf, text/rtf) - /// - public interface IXRtfFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXVisionFileContentExtractor.cs - -namespace xAiApi.Interfaces.Extractors -{ - public interface IXVisionFileContentExtractor : IXFileContentExtractorBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Middlewares\XAiModelProxyMiddleware.cs - -using System; -using System.IO; -using System.Net; -using System.Linq; -using System.Text; -using System.Net.Http; -using System.Threading; -using xAiApi.Extensions; -using xCommons.Constants; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiApi.Configurations; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.Net.Http.Headers; -using xIdentityService.Constants; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using Microsoft.Extensions.Logging; -using xExceptions.Constants; -using xIdentityModels.Models; -using xIdentityModels.Constants; - -namespace xAiApi.Middlewares -{ - public class XAiModelProxyMiddleware - { - private readonly RequestDelegate next; - private readonly XAiApiConfiguration configuration; - private readonly IHttpClientFactory httpClientFactory; - private readonly ILogger logger; - - public XAiModelProxyMiddleware( - RequestDelegate next, - XAiApiConfiguration configuration, - IHttpClientFactory httpClientFactory, - ILogger logger - ) - { - // - this.next = next; - this.logger = logger; - this.configuration = configuration; - this.httpClientFactory = httpClientFactory; - } - - /// - /// Handle Routing ... - /// - /// - /// - public async Task InvokeAsync( - HttpContext context, - IXIdentityProvider identityProvider - ) - { - // - // Validate ... - var isValid = - !configuration.IsNull() && - !configuration.ProxyConfiguration.IsNull() && - configuration.ProxyConfiguration.Enabled && - !configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() && - context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining); - if (!isValid) - { - // - await next(context); - return; - } - - // - // Validating Segment ... - var rawSegments = remaining.Value? - .Trim('/') - .Split('/', StringSplitOptions.RemoveEmptyEntries); - if (!rawSegments.HasChild()) - { - // - await next(context); - return; - } - - // - // Extract Model Name and Retrieve Model Descriptor and do Validation ... - var modelName = Uri.UnescapeDataString(rawSegments[0]); - var descriptor = configuration.GetModel(modelName); - if (!descriptor.IsValid()) - { - // - // Handle Error ... - await context.Response.WriteJsonAsync( - status: HttpStatusCode.NotFound, - data: new - { - error = $"Model '{modelName}' is not configured." - } - ); - return; - } - - // - var errorMessages = new string[] { }; - var apiKey = context.ExtractApiKey(); - var clientIP = context.Request.ExtractClientIP(); - var tokenModel = await context.RetrieveTokensAsXTokenResponse(); - var isAuthenticated = - // - (!apiKey.IsNullOrEmpty()) || - // - (!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty()) - ; - if (isAuthenticated) - { - // - // Handle Authentication ... - if (!apiKey.IsNullOrEmpty()) - { - // - // Try to Validate Api Key ... - var validationResult = await identityProvider.ValidateApiKey( - request: new XApiKeyValidationRequest - { - ApiKey = apiKey, - ClientIP = clientIP, - RequiredScope = XApiKeyScope.Read.GetStringValue() - } - ); - isAuthenticated = !validationResult.Errors.HasChild(); - if (!isAuthenticated) - { - errorMessages = [.. errorMessages, .. validationResult.Errors]; - } - } - else if (!tokenModel.IsNullOrDefault()) - { - // - // Try To Validate Token ... - var validationResult = await identityProvider.Validate(tokenModel); - isAuthenticated = !validationResult.IsError; - if (!isAuthenticated) - { - errorMessages = [..errorMessages, validationResult.Error]; - } - } - else - { - isAuthenticated = false; - } - } - if (!isAuthenticated) - { - // - var error = XException.NotAuthorized.ToXError(); - error.Message = $"{error.Message}: {errorMessages.ToListString(',')}"; - await context.Response.WriteJsonAsync( - status: HttpStatusCode.Unauthorized, - data: error - ); - return; - } - - // - var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1))); - var targetUri = BuildTargetUri( - descriptor.Url, - suffixPath, - context.Request.QueryString - ); - - // - // Collect Headers which need to Except ... - var exceptionHeaders = new string[] - { - XAuthorization.Header, - XAuthorization.ExpiresAt, - XAuthorization.XPoweredBy, - XAuthorization.AccessToken, - XAuthorization.RefreshToken, - XHeader.ApiKey.GetStringValue(), - XAuthorization.AccessTokenExpired, - XHeader.ConnectionId.GetStringValue(), - XHeader.ChecksumDigest.GetStringValue(), - }; - - // - using var upstreamRequest = new HttpRequestMessage( - new HttpMethod(context.Request.Method), - targetUri - ); - - // - context.CopyRequestHeaders( - dest: upstreamRequest, - exceptions: exceptionHeaders - ); - - // - if ( - context.Request.ContentLength > 0 || - context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding) - ) - { - // - context.Request.EnableBuffering(); - using var reader = new StreamReader( - context.Request.Body, - Encoding.UTF8, - detectEncodingFromByteOrderMarks: true, - bufferSize: 1024, - leaveOpen: true - ); - var bodyText = await reader.ReadToEndAsync(); - var actualLength = Encoding.UTF8.GetByteCount(bodyText); - var declaredLength = context.Request.ContentLength; - var contentType = context.Request.ContentType ?? "application/octet-stream"; - var mediaType = contentType.Split(';')[0].Trim(); - upstreamRequest.Content = new StringContent( - bodyText, - Encoding.UTF8, - mediaType - ); - context.Request.Body.Position = 0; - context.CopyRequestHeaders( - dest: upstreamRequest.Content, - exceptions: exceptionHeaders - ); - } - - // - // Handle Api Key of LLM ... - descriptor.AddModelDescriptorApiKey( - request: upstreamRequest - ); - - // - try - { - // - var client = httpClientFactory.CreateClient("XAiModelProxy"); - client.Timeout = Timeout.InfiniteTimeSpan; - - // - using var upstreamResponse = await client.SendAsync( - upstreamRequest, - HttpCompletionOption.ResponseHeadersRead, - context.RequestAborted - ); - - // - context.Response.StatusCode = (int)upstreamResponse.StatusCode; - - // - upstreamResponse.CopyHeaders( - response: context.Response, - exceptions: exceptionHeaders - ); - - // - await using var responseStream = await upstreamResponse.Content - .ReadAsStreamAsync(); - await responseStream.CopyToAsync( - context.Response.Body, - context.RequestAborted - ); - } - catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) - { } - catch (Exception ex) - { - // - logger.LogError(ex, "Proxy failed for model {ModelName}", modelName); - if (!context.Response.HasStarted) - { - // - // Handle Error ... - var error = XException.ActionFailed.ToXError(); - error.Message = $"{error.Message}: {ex.Message}"; - await context.Response.WriteJsonAsync( - status: HttpStatusCode.BadGateway, - data: error - ); - } - } - } - - // - #region Private ... - private static Uri BuildTargetUri( - string baseUrl, - string suffixPath, - QueryString query - ) - { - // - var baseUri = new Uri(baseUrl, UriKind.Absolute); - var builder = new UriBuilder(baseUri); - var basePath = builder.Path.TrimEnd('/'); - - // - builder.Path = suffixPath.IsNullOrEmpty() - ? basePath - : $"{basePath}/{suffixPath.TrimStart('/')}"; - - // - builder.Query = query.HasValue - ? query.Value.TrimStart('?') - : string.Empty; - - // - return builder.Uri; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xAiApi.Migrations -{ - public partial class InitialMigrationAiApi : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "AiConversations", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ProjectId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiConversations", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMcpServers", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Scope = table.Column(nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Enabled = table.Column(nullable: false), - EnvironmentVariables = table.Column(nullable: true), - Endpoint = table.Column(maxLength: 1000, nullable: true), - Headers = table.Column(nullable: true), - TimeoutSeconds = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMcpServers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiMessages", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Content = table.Column(nullable: false), - Role = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false), - ConversationId = table.Column(maxLength: 255, nullable: false), - MetaDatas = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiMessages", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiProjects", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Prompt = table.Column(nullable: true), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AiProjects", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AiVectors", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Text = table.Column(nullable: true), - Identifier = table.Column(nullable: true), - Type = table.Column(maxLength: 100, nullable: true), - Embedding = table.Column(nullable: true), - Metadata = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AiVectors", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Files", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Type = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Path = table.Column(nullable: false), - Thumb = table.Column(nullable: true), - ThumbPath = table.Column(nullable: true), - UploadedOn = table.Column(nullable: false), - FileName = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Files", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Strings", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Language = table.Column(maxLength: 10, nullable: false), - ResourceTitle = table.Column(maxLength: 255, nullable: false), - TranslatedValue = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Strings", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tags", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Tag = table.Column(maxLength: 255, nullable: false), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Tags", x => x.Id); - }); - - migrationBuilder.CreateIndex( - name: "IX_AiVectors_Identifier", - table: "AiVectors", - column: "Identifier"); - - migrationBuilder.CreateIndex( - name: "IX_AiVectors_Type", - table: "AiVectors", - column: "Type"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "AiConversations"); - - migrationBuilder.DropTable( - name: "AiMcpServers"); - - migrationBuilder.DropTable( - name: "AiMessages"); - - migrationBuilder.DropTable( - name: "AiProjects"); - - migrationBuilder.DropTable( - name: "AiVectors"); - - migrationBuilder.DropTable( - name: "Files"); - - migrationBuilder.DropTable( - name: "Strings"); - - migrationBuilder.DropTable( - name: "Tags"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.Designer.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xAiApi.Database; - -namespace xAiApi.Migrations -{ - [DbContext(typeof(XAiApiDbContext))] - [Migration("20261104052650_InitialMigrationAiApi")] - partial class InitialMigrationAiApi - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("TEXT") - .HasMaxLength(100); - - b.HasKey("Id"); - - b.HasIndex("Identifier"); - - b.HasIndex("Type"); - - b.ToTable("AiVectors"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\XAiApiDbContextModelSnapshot.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xAiApi.Database; - -namespace xAiApi.Migrations -{ - [DbContext(typeof(XAiApiDbContext))] - partial class XAiApiDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiConversations"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("EnvironmentVariables") - .HasColumnType("TEXT"); - - b.Property("Headers") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Scope") - .HasColumnType("INTEGER"); - - b.Property("TimeoutSeconds") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMcpServers"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Content") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ConversationId") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("MetaDatas") - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Role") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiMessages"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(1000); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Prompt") - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("AiProjects"); - }); - - modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Embedding") - .HasColumnType("TEXT"); - - b.Property("Identifier") - .HasColumnType("TEXT"); - - b.Property("Metadata") - .HasColumnType("TEXT"); - - b.Property("Text") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("TEXT") - .HasMaxLength(100); - - b.HasKey("Id"); - - b.HasIndex("Identifier"); - - b.HasIndex("Type"); - - b.ToTable("AiVectors"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentModels.cs - -using System; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Result of Ingesting Documents into an In-Memory Session ... - /// - public class XAiDocumentIngestResult - { - /// - /// Session Identifier which must be used in Ask Requests ... - /// - public Guid SessionId { get; set; } - - /// - /// Count of Successfully Processed Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Chunks (Vectors) Added to Session ... - /// - public int ChunksCount { get; set; } - - /// - /// Total Vectors Count in Session after Ingest ... - /// - public int TotalVectorsCount { get; set; } - - /// - /// Files which Skipped (Unsupported / Empty / Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Session Expiration Time (UTC) based on Last Access ... - /// - public DateTime ExpiresAtUtc { get; set; } - } - - /// - /// Request for Asking a Question over Ingested Documents ... - /// - public class XAiDocumentAskRequest - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// User Question ... - /// - public string Prompt { get; set; } - - /// - /// Count of Top Chunks used as Context (Optional) ... - /// - public int? TopK { get; set; } - - /// - /// Minimum Similarity Score of Chunks (Optional) ... - /// - public float? MinScore { get; set; } - } - - /// - /// a Source Chunk which used for Generating Answer ... - /// - public class XAiDocumentSource - { - /// - /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... - /// - public string Identifier { get; set; } - - /// - /// Source File Name ... - /// - public string FileName { get; set; } - - /// - /// Chunk Index in Source File ... - /// - public int? ChunkIndex { get; set; } - - /// - /// Similarity Score ... - /// - public float Score { get; set; } - - /// - /// Short Snippet of Chunk Text ... - /// - public string Snippet { get; set; } - - /// - /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ... - /// - public string Scope { get; set; } - - /// - /// Knowledge Type of the Chunk ... - /// - public string Type { get; set; } - } - - /// - /// Answer of a Chat With Documents Request ... - /// - public class XAiDocumentAnswer - { - /// - /// Session Identifier ... - /// - public Guid SessionId { get; set; } - - /// - /// Generated Answer ... - /// - public string Answer { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources used for Generating Answer ... - /// - public IList Sources { get; set; } = new List(); - } - - /// - /// Streaming Chunk of a Chat With Documents Answer ... - /// - public class XAiDocumentAnswerChunk - { - /// - /// Text Delta ... - /// - public string Text { get; set; } - - /// - /// True for Last Chunk ... - /// - public bool IsFinal { get; set; } - - /// - /// True when no Relevant Chunk Found in Session ... - /// - public bool NoContextFound { get; set; } - - /// - /// Sources (Only Filled in First Chunk) ... - /// - public IList Sources { get; set; } - } - - /// - /// Public Info of a Document Session (without Embeddings) ... - /// - public class XAiDocumentSessionInfo - { - public Guid Id { get; set; } - public TimeSpan Ttl { get; set; } - public int VectorsCount { get; set; } - public DateTime CreatedAtUtc { get; set; } - public DateTime LastAccessAtUtc { get; set; } - public DateTime ExpiresAtUtc { get; set; } - public IList Files { get; set; } = new List(); - } - - /// - /// Document RAG Configuration ... - /// - public class XAiDocumentRAGDescriptor - { - public int MaxTopK { get; set; } = 20; - public int DefaultTopK { get; set; } = 5; - public int DefaultTtlMinutes { get; set; } = 30; - public int EmbeddingBatchSize { get; set; } = 32; - public int SourceSnippetLength { get; set; } = 200; - public float DefaultMinScore { get; set; } = 0.35f; - public string MetadataFileName { get; set; } = "fileName"; - public string MetadataMimeType { get; set; } = "mimeType"; - public string PromptName { get; set; } = "ChatWithDocuments"; - public string MetadataChunkIndex { get; set; } = "chunkIndex"; - - // - // Knowledge (Persistent RAG) Limits ... - /// - /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ... - /// - public int MaxFilesPerIngest { get; set; } = 20; - - /// - /// Max Size of a Single File in Bytes (0 = Unlimited) ... - /// - public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024; - - /// - /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ... - /// - public int MaxDocumentsPerScope { get; set; } = 50; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentSession.cs - -using System; -using xAiModels.Models.Dtos; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - public class XAiDocumentSession - { - public Guid Id { get; set; } - public TimeSpan Ttl { get; set; } - public string OwnerId { get; set; } - public DateTime CreatedAtUtc { get; set; } - public DateTime LastAccessAtUtc { get; set; } - internal object SyncRoot { get; } = new object(); - public IList Vectors { get; set; } = new List(); - public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiKnowledgeModels.cs - -using System; -using xAiModels.Constants; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// Describes Target Knowledge Base Scope of an Operation ... - /// - public class XAiKnowledgeScopeDescriptor - { - /// - /// Scope Kind ... - /// - public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User; - - /// - /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Optional Knowledge Type / Domain Filter ... - /// - public string Type { get; set; } - - /// - /// Create User Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor User( - string type = null - ) => new() - { - // - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.User, - }; - - /// - /// Create Global Scope Knowledge Descriptor ... - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Global( - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = null, - Scope = XAiKnowledgeScope.Global, - }; - - /// - /// Create Project Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Project( - Guid projectId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = projectId, - Scope = XAiKnowledgeScope.Project, - }; - - /// - /// Create Conversational Scope Knowledge Descriptor ... - /// - /// - /// - /// - public static XAiKnowledgeScopeDescriptor Conversation( - Guid conversationId, - string type = null - ) => new() - { - Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType, - ScopeId = conversationId, - Scope = XAiKnowledgeScope.Conversation, - }; - } - - /// - /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ... - /// - public class XAiKnowledgeIngestResult - { - /// - /// Target Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Target Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type of Ingested Vectors ... - /// - public string Type { get; set; } - - /// - /// Count of Successfully Ingested Files ... - /// - public int FilesCount { get; set; } - - /// - /// Count of Stored Chunks (Vectors) in this Request ... - /// - public int ChunksCount { get; set; } - - /// - /// Count of Removed Stale Vectors (Re-Ingest) ... - /// - public int ReplacedCount { get; set; } - - /// - /// Skipped Files (Empty, Unsupported or Extraction Failed) ... - /// - public IList SkippedFiles { get; set; } = new List(); - - /// - /// Ingested Documents Info ... - /// - public IList Documents { get; set; } = new List(); - } - - /// - /// Ask Request over Persistent Knowledge Base ... - /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ... - /// - public class XAiKnowledgeAskRequest - { - /// - /// Question ... - /// - public string Prompt { get; set; } - - /// - /// Optional: Conversation Scope (Caller must be Conversation Owner) ... - /// When Provided, Conversation's Project is used for Second Tier Automatically ... - /// - public Guid? ConversationId { get; set; } - - /// - /// Optional: Project Scope (Caller must be Project Owner) ... - /// - public Guid? ProjectId { get; set; } - - /// - /// Include Personal (User) Knowledge Tier (default true) ... - /// - public bool IncludeUser { get; set; } = true; - - /// - /// Include Global Knowledge Tier (default true) ... - /// - public bool IncludeGlobal { get; set; } = true; - - /// - /// Optional: Restrict Retrieval to a Knowledge Type / Domain ... - /// - public string Type { get; set; } - - /// - /// Optional: Restrict Retrieval to a Specific File Name ... - /// - public string FileName { get; set; } - - /// - /// Optional: Max Retrieved Chunks ... - /// - public int? TopK { get; set; } - - /// - /// Optional: Minimum Cosine Similarity Score ... - /// - public float? MinScore { get; set; } - } - - /// - /// Ingested Document Info ... - /// - public class XAiKnowledgeDocumentInfo - { - /// - /// Scope ... - /// - public XAiKnowledgeScope Scope { get; set; } - - /// - /// Scope Identifier (Null for Global) ... - /// - public Guid? ScopeId { get; set; } - - /// - /// Knowledge Type ... - /// - public string Type { get; set; } - - /// - /// File Name ... - /// - public string FileName { get; set; } - - /// - /// Mime Type ... - /// - public string MimeType { get; set; } - - /// - /// Ingesting User Identifier ... - /// - public string OwnerId { get; set; } - - /// - /// Count of Stored Chunks ... - /// - public int ChunksCount { get; set; } - - /// - /// Ingestion Time (UTC) ... - /// - public DateTime? IngestedAtUtc { get; set; } - } - - /// - /// Public Vector Info (Export) ... - /// - public class XAiKnowledgeVectorInfo - { - public Guid Id { get; set; } - public string Text { get; set; } - public string Type { get; set; } - public Guid? ScopeId { get; set; } - public string FileName { get; set; } - public int? ChunkIndex { get; set; } - public string Identifier { get; set; } - public XAiKnowledgeScope Scope { get; set; } - public Dictionary Metadata { get; set; } - - /// - /// Embedding (Only Filled when Requested) ... - /// - public float[] Embedding { get; set; } - } -} - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs - -namespace xAiApi.Models -{ - /// - /// Describe an Mcp Server for Seeding ... - /// - public class XAiMcpServerDescriptor - { - public string Name { get; set; } - public string OwnerId { get; set; } - public string Headers { get; set; } - public string Endpoint { get; set; } - public string Description { get; set; } - public bool Enabled { get; set; } = true; - public int TimeoutSeconds { get; set; } = 30; - public string EnvironmentVariables { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs - -namespace xAiApi.Models -{ - public class XAiModelProxyConfiguration - { - /// - /// Enable Proxy or not ... - /// - /// - public bool Enabled { get; set; } = false; - - /// - /// Proxy Prefix ... - /// - /// - public string RoutePrefix { get; set; } = "ai-model"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs - -using Tesseract; - -namespace xAiApi.Models -{ - public class XAiOCRDescriptor - { - /// - /// Provides Trained Data Path ... - /// - public string DataPath { get; set; } - - /// - /// The Engine for Doing OCR ... - /// - public EngineMode EngineMode { get; set; } - - /// - /// Enable OCR Fallback using Model ... - /// - public bool EnableOcrFallback { get; set; } - - /// - /// Default OCR Language ... - /// - public string DefaultLanguage { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs - -namespace xAiApi.Models -{ - public class XAiTransciptDescriptor - { - public string Language { get; set; } - public string ModelsPath { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XDateTimeDescriptor.cs - -namespace xAiApi.Models -{ - public class XDateTimeDescriptor - { - /// - /// Adding Current DateTime to Prompt ... - /// - public bool InjectIntoSystemPrompt { get; set; } = true; - - /// - /// Time Zone ... - /// - public string DefaultTimezone { get; set; } = "Asia/Tehran"; - - /// - /// Georgian Date Format ... - /// - public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; - - /// - /// Include Persian Calendar ... - /// - public bool IncludePersianCalendar { get; set; } = true; - - /// - /// Include Day of Week ... - /// - public bool IncludeDayOfWeek { get; set; } = true; - - /// - /// Include Unix Timestamp ... - /// - public bool IncludeUnixTimestamp { get; set; } = false; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs - -namespace xAiApi.Models -{ - public class XPDFToImageDescriptor - { - public int Dpi { get; set; } = 300; - public int Width { get; set; } = 0; - public int Height { get; set; } = 0; - public bool UseTiling { get; set; } = false; - public bool WithFormFill { get; set; } = false; - public bool WithAspectRatio { get; set; } = false; - public bool WithAnnotations { get; set; } = false; - public bool DpiRelativeToBounds { get; set; } = false; - - public int MaxImageWidth { get; set; } = 2000; - public int MinTextLengthThreshold { get; set; } = 50; - public int MaxPagesForImageFallback { get; set; } = 0; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XPreparedChatContext.cs - -using xAiModels.Models.Dtos; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiApi.Models -{ - /// - /// a Shared Context Between Actions for Generation ... - /// - public class XPreparedChatContext - { - /// - /// Specified Related Project, if Exists ... - /// - public XAiProjectDto Project { get; set; } = null; - - /// - /// Specified Related Conversation, if Exists ... - /// - public XAiConversationDto Conversation { get; set; } = null; - - /// - /// Specified Message History, if Exists ... - /// - public IList History { get; set; } = []; - - /// - /// Specified Vector Search Conext, if Exists ... - /// - public IList Context { get; set; } = []; - - /// - /// Specified Persisted Prompt, if Exists ... - /// - public XAiMessageDto PersistedPromptMessage { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunk.cs - -namespace xAiApi.Models -{ - /// - /// Represents a Chunk of a Text which Produced by Text Chunker ... - /// - public class XTextChunk - { - /// - /// Zero Based Index of Chunk in Source Text ... - /// - public int Index { get; set; } - - /// - /// Chunk Text Content ... - /// - public string Text { get; set; } = string.Empty; - - /// - /// Source Name (e.g. File Name) which Chunk Extracted From ... - /// - public string Source { get; set; } - - /// - /// Doc and Chunk Identifier (e.g. "file.pdf#3") ... - /// - public string Identifier { get; set; } - - /// - /// Start Offset of Chunk in Normalized Source Text ... - /// - public int StartOffset { get; set; } - - /// - /// Length of Chunk Text ... - /// - public int Length => Text?.Length ?? 0; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunkerDescriptor.cs - -namespace xAiApi.Models -{ - /// - /// Text Chunker Descriptor ... - /// - public class XTextChunkerDescriptor - { - /// - /// Maximum Characters Count of each Chunk ... - /// - public int ChunkSize { get; set; } = 800; - - /// - /// Characters Count which Shared between two Consecutive Chunks ... - /// - public int ChunkOverlap { get; set; } = 150; - - /// - /// Chunks Smaller than this Size will be Merged into Previous Chunk ... - /// - public int MinChunkSize { get; set; } = 50; - - /// - /// Chunck Identifier Separator ... - /// - public string ChunkIdentifierSeparator { get; set; } = "#"; - - /// - /// Normalize Line Endings and Repeated Whitespaces before Chunking ... - /// - public bool NormalizeWhitespace { get; set; } = true; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingService.cs - -using xAiApi.Constants; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers -{ - public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService - { - public XAiEmbeddingService( - IXAiDataProvider dataProvider, - XAiApiConfiguration configuration, - ILogger logger, - XValidationProvider validationProvider, - IXFileContentExtractor fileContentExtractor - ) : base( - dataProvider, - configuration, - validationProvider, - logger, - fileContentExtractor, - XAiApiConstants.XAiEmbeddingModelName - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingServiceBase.cs - -using System; -using OpenAI; -using System.Linq; -using OllamaSharp; -using System.Threading; -using xAiApi.Constants; -using xAiModels.Models; -using xAiApi.Extensions; -using xAiApi.Interfaces; -using xAiModels.Helpers; -using System.ClientModel; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Extensions; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; -using System.ClientModel.Primitives; - -namespace xAiApi.Providers -{ - /// - /// Base Embedding Provider Service ... - /// - public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase - { - private readonly string embeddingModelName; - private readonly XAiModelDescriptor descriptor; - private readonly IXAiDataProvider dataProvider; - private readonly XAiApiConfiguration configuration; - private readonly XValidationProvider validationProvider; - private readonly ILogger logger; - private readonly IXFileContentExtractor fileContentExtractor; - - protected XAiEmbeddingServiceBase( - IXAiDataProvider dataProvider, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - ILogger logger, - IXFileContentExtractor fileContentExtractor, - string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName - ) - { - // - // Prepare Embedding Model Descriptor ... - descriptor = configuration.GetModel(embeddingModelName); - if (!descriptor.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - this.dataProvider = dataProvider; - this.configuration = configuration; - this.validationProvider = validationProvider; - - // - this.logger = logger; - this.fileContentExtractor = fileContentExtractor; - this.embeddingModelName = embeddingModelName; - } - - /// - /// Embedding Specified String ... - /// - /// - /// - /// - public virtual async Task Embedding( - string content, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (content.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var generator = GetEmbeddingGenerator(); - - // - GeneratedEmbeddings> response = null; - response = await generator.GenerateAsync( - values: [content], - cancellationToken: cancellationToken - ); - - // - if (response.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - // Generae Result ... - var result = response - .First()? - .Vector - .ToArray() - ?? []; - if (result.Length == 0) - { - XException.ActionFailed.Throw(); - } - - // - // Normalize ... - VectorHelper.Normalize(result); - - // - return result; - } - - /// - /// Embedding Specified Batch ... - /// - /// - /// - /// - public virtual async Task> Embeddings( - string[] batch, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!batch.HasChild() || - !batch.All(x => !x.IsNullOrEmpty()) - ) - { - XException.InvalidArgs.Throw(); - } - - // - using var generator = GetEmbeddingGenerator(); - - // - GeneratedEmbeddings> response = null; - response = await generator.GenerateAsync( - values: [.. batch], - cancellationToken: cancellationToken - ); - - // - if (response.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - var result = response - .Select(e => e.Vector.ToArray()) - .ToList(); - - // - // Normalize ... - foreach (var vector in result) - { - VectorHelper.Normalize(vector); - } - - // - return result; - } - - /// - /// Embedding Generator ... - /// - /// - public IEmbeddingGenerator> GetEmbeddingGenerator() - { - // - IEmbeddingGenerator> result = null; - - // - if (!descriptor.IsValid()) - { - XException.InvalidData.Throw("Invalid Embedding Model ..."); - } - - // - switch (descriptor.Provider) - { - // - case XAiModelProviderType.OpenAI: - // - var openAiClient = new OpenAIClient( - new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey), - new OpenAIClientOptions - { - Endpoint = new Uri(descriptor.Url), - Transport = new HttpClientPipelineTransport(descriptor.Url.GetHttpClient()) - } - ); - result = openAiClient - .GetEmbeddingClient(descriptor.LLM) - .AsIEmbeddingGenerator(); - break; - - // - case XAiModelProviderType.Ollama: - // - var ollamaClient = new OllamaApiClient(new Uri(descriptor.Url)); - result = ollamaClient; - break; - } - - // - if (result.IsNull()) - { - XException.InvalidData.Throw("Invalid Embedding Model ..."); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiMcpServerProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using System.Text.Json; -using xAiApi.Interfaces; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiService.Services; -using xAiModels.Extensions; -using xAiService.Extensions; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xIdentityModels.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xCommons.Configurations; -using Microsoft.Extensions.AI; -using xAiModels.Providers.Hubs; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Dtos; -using xIdentityHelper.Extensions; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; -using System.Collections.Concurrent; -using xAiModels.Interfaces.Enrichers; - -namespace xAiApi.Providers -{ - /// - /// MCP Manager / Provider ... - /// - public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable - { - // - private readonly XAiMcpSessionStore sessionStore; - private readonly XAiMcpHttpTransport mcpTransport; - - // - private readonly XAppConfiguration configuration; - private readonly IHubContext hub; - private readonly IXIdentityProvider identityProvider; - private readonly ILogger logger; - private readonly XValidationProvider validationProvider; - private readonly IXAiMcpServerEnricher mcpServerEnricher; - private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; - private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; - - // - private readonly ConcurrentDictionary mcpServers = []; - private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new(); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new(); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList> tools = new(); - - // - private bool isInitialized = false; - private readonly SemaphoreSlim initLock = new(1, 1); - - public XAiMcpServerProvider( - XAiMcpSessionStore sessionStore, - XAppConfiguration configuration, - XAiMcpHttpTransport mcpTransport, - IHubContext hub, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider, - IXAiMcpServerEnricher mcpServerEnricher, - IXAiMcpServerServiceProvider mcpServerServiceProvider, - IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider - ) - { - this.configuration = configuration; - // - this.hub = hub; - this.logger = logger; - this.sessionStore = sessionStore; - this.mcpTransport = mcpTransport; - this.identityProvider = identityProvider; - this.mcpServerEnricher = mcpServerEnricher; - this.validationProvider = validationProvider; - this.mcpServerServiceProvider = mcpServerServiceProvider; - this.mcpServerRepositoryProvider = mcpServerRepositoryProvider; - } - - public async ValueTask DisposeAsync() - { - // - foreach (var client in clients.Values) - { - try - { - await client.DisposeAsync(); - } - catch { } - } - initLock.Dispose(); - } - - // - #region Manager ... - /// - /// Get a List Of Available Tools which Provided using registered Mcp Servers ... - /// - /// - /// - /// - /// - public async Task> GetAvailableToolsAsync( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - if (userInfo.IsNullOrDefault()) - { - // - logger.LogInformation("there isn't any McpServer for non authenticated user ..."); - return []; - } - - // - if (!userInfo.IsAdmin()) - { - forceOwner = true; - } - - // - // Load Servers Metadata ... - await EnsureServersLoadedAsync(cancellationToken); - - // - // Extract Accessible Mcp Servers ... - var accessibleServers = mcpServers.Values - .Where(s => s.OwnerId == userInfo.UserId || - s.Scope == XAiMcpServerUsageScope.All) - .ToList(); - - // - // Create User Speciic Client Connection ... - foreach (var server in accessibleServers) - { - // - // Create User Specific Client Key ... - var key = (server.Id, userInfo.UserId); - - // - // Check Expiration ... - if (clients.ContainsKey(key) && - clientExpirations.TryGetValue(key, out var exp) && - exp < DateTime.UtcNow) - { - // - // Remove Expired Client and Tools ... - if (clients.TryRemove(key, out var old)) - { - // - try - { - await old.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - clientExpirations.TryRemove(key, out _); - } - - // - if (clients.ContainsKey(key)) - { - continue; - } - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (!clients.ContainsKey(key)) - { - // - await ConnectAndValidateAsync( - descriptor: server, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - } - } - finally - { - initLock.Release(); - } - } - - // - // Extract User Specified Mcp Client Tools ... - var result = tools - .Where(kv => kv.Key.UserId == userInfo.UserId) - .SelectMany(kv => kv.Value) - .ToList(); - - // - return result; - } - - /// - /// Test Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task TestServerAsync( - XAiMcpServerDto server, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); - - // - var client = CreateClientAsync(server, connectionId, userInfo); - // await client.PingAsync(cancellationToken: cts.Token); - var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); - - // - var names = string.Join(", ", serverTools.Select(t => t.Name)); - return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}"; - } - catch (Exception ex) - { - // - return $"✗ Error: {ex.Message} ..."; - } - } - - /// - /// Force Refresh Mcp Servers ... - /// - /// - /// - /// - public async Task RefreshAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - if (!userInfo.IsAdmin()) - { - XException.NotAllowed.Throw(); - } - - // - logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); - foreach (var client in clients.Values) - { - try - { - await client.DisposeAsync(); - } - catch { } - } - tools.Clear(); - clients.Clear(); - mcpServers.Clear(); - - // - isInitialized = false; - await GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Actions ... - /// - /// Add an Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task AddMcpServer( - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(userInfo) - .AddUrl(item.Endpoint) - .AddNotEmpty(item.Endpoint) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Normalize Scope ... - if (!userInfo.IsAdmin()) - { - item.Scope = XAiMcpServerUsageScope.Owner; - } - item.OwnerId = userInfo.UserId; - item.CreatedOn = DateTime.UtcNow; - - // - // Normalizing Timeout ... - if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) - { - item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; - } - - // - // Validate for Add ... - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await mcpServerServiceProvider - .AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerCreated.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - mcpServers[result.Id] = result; - await ConnectAndValidateAsync(result, connectionId, userInfo); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Get an Mcp Server ... - /// - /// - /// - /// - /// - public async Task GetMcpServer( - Guid id, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var result = await mcpServerServiceProvider - .GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId) - { - XException.NotAllowed.Throw(); - } - - // - if (!result.IsNullOrDefault()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Update Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - /// - public async Task UpdateMcpServer( - Guid id, - XAiMcpServerDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(item) - .AddIsGuid(item.Id) - .AddNotNull(userInfo) - .AddUrl(item.Endpoint) - .AddNotNull(item.CreatedOn) - .AddNotEmpty(item.Endpoint) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Normalize Scope ... - if (!userInfo.IsAdmin()) - { - item.Scope = XAiMcpServerUsageScope.Owner; - } - item.UpdatedAt = DateTime.UtcNow; - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && - userInfo.UserId != item.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - // Normalizing Timeout ... - if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) - { - item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; - } - - // - // Validate for Add ... - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await mcpServerServiceProvider - .UpdateAsync( - id: id, - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - mcpServers[result.Id] = result; - - // - // Remove Exists ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == result.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var old)) - { - try - { - await old.DisposeAsync(); - } - catch { } - } - tools.TryRemove(key, out _); - } - - // - // Reconnect ... - await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Remove Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task RemoveMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Check McpServer Exists ... - var exists = await mcpServerServiceProvider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && - userInfo.UserId != exists.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - var result = await mcpServerServiceProvider.RemoveAsync( - id: id, - softDelete: true, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - // Remove Server Descriptor ... - mcpServers.TryRemove(result.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == result.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Disable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task DisableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Check McpServer Exists ... - var exists = await mcpServerServiceProvider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && - userInfo.UserId != exists.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - if (!exists.Enabled) - { - return false; - } - exists.Enabled = false; - - // - exists = await mcpServerServiceProvider.UpdateAsync( - id: id, - item: exists, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var result = !exists.IsNullOrDefault() && !exists.Enabled; - - // - if (result) - { - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: exists.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - // Remove Server Descriptor ... - mcpServers.TryRemove(exists.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == exists.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Enable Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task EnableMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Check McpServer Exists ... - var exists = await mcpServerServiceProvider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && - userInfo.UserId != exists.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - if (exists.Enabled) - { - return false; - } - exists.Enabled = true; - - // - exists = await mcpServerServiceProvider.UpdateAsync( - id: id, - item: exists, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var result = !exists.IsNullOrDefault() && exists.Enabled; - - // - if (result) - { - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: exists.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - mcpServers[exists.Id] = exists; - await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken); - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Toggle Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task ToggleMcpServer( - Guid id, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Check McpServer Exists ... - var exists = await mcpServerServiceProvider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Ownership ... - if (!userInfo.IsAdmin() && - userInfo.UserId != exists.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - exists.Enabled = !exists.Enabled; - - // - exists = await mcpServerServiceProvider.UpdateAsync( - id: id, - item: exists, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var result = !exists.IsNullOrDefault(); - - // - if (result) - { - // - // Sending Push ... - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: exists.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() - ); - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (exists.Enabled) - { - // - mcpServers[exists.Id] = exists; - await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken); - } - else - { - // - // Remove Server Descriptor ... - mcpServers.TryRemove(exists.Id, out _); - - // - // Disconnect all Connections ... - var keysToRemove = clients.Keys - .Where(k => k.ServerId == exists.Id) - .ToList(); - foreach (var key in keysToRemove) - { - // - if (clients.TryRemove(key, out var c)) - { - // - try - { - await c.DisposeAsync(); - } - catch { } - } - - // - tools.TryRemove(key, out _); - } - } - } - finally - { - initLock.Release(); - } - } - - // - return result; - } - - /// - /// Retrieve all Mcp Server ... - /// - /// - /// - /// - /// - public async Task> GetAll( - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - if (!userInfo.IsAdmin()) - { - forceOwner = true; - } - - // - var result = Enumerable.Empty(); - Func, IOrderedQueryable> orderBuilder = x => x.OrderByDescending(y => y.CreatedOn); - if (forceOwner) - { - // - result = await mcpServerServiceProvider - .FindManyAsync( - predicate: x => - x.OwnerId - .Equals( - userInfo.UserId, - StringComparison.InvariantCultureIgnoreCase - ), - includeBuilder: null, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - else - { - // - result = await mcpServerServiceProvider - .GetAllAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - - // - if (result.HasChild()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Find Specified Mcp Server ... - /// - /// - /// - /// - /// - /// - public async Task FindOne( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - if (!userInfo.IsAdmin()) - { - forceOwner = true; - } - - // - Expression> predicator = null; - if (forceOwner) - { - // - predicator = x => - predicate.Compile()(x) && - x.OwnerId - .Equals( - userInfo.UserId, - StringComparison.InvariantCultureIgnoreCase - ); - } - else - { - // - predicator = x => predicate.Compile()(x); - } - - // - var result = await mcpServerServiceProvider.FindOneAsync( - includeBuilder: null, - predicate: predicator, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Find a Collection of Specified Mcp Servers ... - /// - /// - /// - /// - /// - /// - public async Task> FindMany( - Expression> predicate, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - if (!userInfo.IsAdmin()) - { - forceOwner = true; - } - - // - Expression> predicator = null; - if (forceOwner) - { - // - predicator = x => - predicate.Compile()(x) && - x.OwnerId - .Equals( - userInfo.UserId, - StringComparison.InvariantCultureIgnoreCase - ); - } - else - { - // - predicator = x => predicate.Compile()(x); - } - - // - var result = await mcpServerServiceProvider.FindManyAsync( - includeBuilder: null, - predicate: predicator, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) - ); - - // - if (result.HasChild()) - { - // - // Handle Enrichment ... - result = await mcpServerEnricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Query Registered Mcp Servers ... - /// - /// - /// - /// - /// - /// - public async Task> Query( - XQuery query, - bool forceOwner = false, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - if (!userInfo.IsAdmin()) - { - forceOwner = true; - } - - // - Expression> predicator = null; - if (forceOwner) - { - // - predicator = x => - x.OwnerId - .Equals( - userInfo.UserId, - StringComparison.InvariantCultureIgnoreCase - ); - } - - // - var result = await mcpServerServiceProvider.QueryAsync( - query: query, - includeBuilder: null, - predicate: predicator, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) - ); - - // - if (!result.IsNullOrDefault() && result.Items.HasChild()) - { - // - // Handle Enrichment ... - result.Items = await mcpServerEnricher.EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - #endregion - - // - #region Private ... - private static Dictionary ParseJsonDict(string json) - => json.IsNullOrEmpty() ? null - : JsonSerializer.Deserialize>(json); - - private static List ParseJsonList(string json) - => json.IsNullOrEmpty() ? null - : JsonSerializer.Deserialize>(json); - - private XAiMcpClient CreateClientAsync( - XAiMcpServerDto descriptor, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ) - { - // - var result = new XAiMcpClient( - logger: logger, - userInfo: userInfo, - transport: mcpTransport, - serverId: descriptor.Id, - sessionStore: sessionStore, - connectionId: connectionId, - appConfiguration: configuration, - endpoint: new Uri(descriptor.Endpoint) - ); - - // - return result; - } - - private async Task ConnectAndValidateAsync( - XAiMcpServerDto descriptor, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Create Specified Cancellation Token ... - using var cts = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); - - // - var client = CreateClientAsync( - userInfo: userInfo, - descriptor: descriptor, - connectionId: connectionId - ); - - // - await client.InitializeAsync(cts.Token); - - // - var clientTools = await client.ListToolsAsync(cts.Token); - var aiTools = clientTools.ToAITools(client); - - // - // Key for Cache ... - var key = (descriptor.Id, userInfo.UserId); - - // - tools[key] = aiTools; - clients[key] = client; - mcpServers[descriptor.Id] = descriptor; - clientExpirations[key] = DateTime.UtcNow.AddMinutes(15); - - // - logger.LogInformation( - "MCP '{Name}': {Count} Tools Detected for {UserId} ...", - descriptor.Name, - aiTools.Count, - userInfo.UserId - ); - } catch(Exception ex) - { - // - logger.LogWarning(ex, - "MCP '{Name}': Connection Established Failed, Ignored ...", - descriptor.Name - ); - } - } - - private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken) - { - // - if (isInitialized) - { - return; - } - - // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (isInitialized) - { - return; - } - - // - var servers = await mcpServerServiceProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: x => x.Enabled, - cancellationToken: cancellationToken - ); - - // - if (servers.HasChild()) - { - // - foreach (var s in servers) - { - // - mcpServers[s.Id] = s; - } - } - - // - isInitialized = true; - } - finally - { - initLock.Release(); - } - } - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - public async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Collect Allowed Actions ... - var actions = new List - { - XAiDataProviderHubActions.McpServerCreated.GetStringValue(), - XAiDataProviderHubActions.McpServerUpdated.GetStringValue(), - XAiDataProviderHubActions.McpServerRemoved.GetStringValue(), - }; - - // - // Validate Args ... - var isValid = - !action.IsNullOrEmpty() && - actions.Contains(action); - if (!isValid) - { - return; - } - - // - // Retrieve Connection Id ... - var clients = hub.Clients.All; - if (!connectionId.IsNullOrEmpty()) - { - clients = hub.Clients.AllExcept(connectionId); - } - - // - await clients.SendAsync( - action, - payLoad, - connectionId, - cancellationToken - ); - } - catch { } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiRAGService.cs - -using System; -using System.IO; -using System.Linq; -using xAiApi.Models; -using xIdentityHelper; -using System.Threading; -using xAiApi.Interfaces; -using xAiModels.Constants; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xFileService.Interfaces; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; -using xFileService.Models.Dtos; - -namespace xAiApi.Providers -{ - /// - /// Persistent RAG Service over XAiVector Table ... - /// Isolation (Identifier Layout): - /// Conversation: "conversation/{conversationId}/{fileName}#{i}" - /// Project : "project/{projectId}/{fileName}#{i}" - /// User : "user/{ownerId}/{fileName}#{i}" - /// Global : "global/{fileName}#{i}" - /// Retrieval is Tiered: Conversation -> Project -> User -> Global ... - /// - public class XAiRAGService : IXAiRAGService - { - private readonly IXTextChunker textChunker; - private readonly IXFileProvider fileProvider; - private readonly IXAiDataProvider dataProvider; - private readonly ILogger logger; - private readonly XAiApiConfiguration configuration; - private readonly IXAiEmbeddingService embeddingService; - private readonly IXFileContentExtractor fileContentExtractor; - - /// - /// Characters which are not Allowed in File Name Part of Identifier ... - /// - private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#']; - - public XAiRAGService( - IXTextChunker textChunker, - IXFileProvider fileProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - IXAiEmbeddingService embeddingService, - IXFileContentExtractor fileContentExtractor - ) - { - // - this.logger = logger; - this.textChunker = textChunker; - this.fileProvider = fileProvider; - this.dataProvider = dataProvider; - this.configuration = configuration; - this.embeddingService = embeddingService; - this.fileContentExtractor = fileContentExtractor; - } - - // - #region Ingest ... - /// - /// Ingest Files into Specified Knowledge Scope: - /// Extract -> Chunk -> Embed -> Store (XAiVector) ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task IngestAsync( - IFormFileCollection files, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - bool replaceExisting = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!files.HasChild() || !IsValidUser(userInfo)) - { - XException.InvalidArgs.Throw(); - } - - // - var rag = configuration.RAGDescriptor; - if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest) - { - XException.InvalidArgs.Throw(); - } - - // - // Resolve & Authorize Scope (Write) ... - scope = NormalizeScope(scope); - await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken); - - // - var knowledgeType = scope.Type.IsNullOrEmpty() - ? XAiModelsConstants.XAiDefaultKnowledgeType - : scope.Type; - var scopePrefix = GetScopePrefix(scope, userInfo); - - // - var result = new XAiKnowledgeIngestResult - { - Type = knowledgeType, - Scope = scope.Scope, - ScopeId = scope.ScopeId, - }; - var ingestedAt = DateTime.UtcNow; - var ingestedAtUtc = ingestedAt.ToString("O"); - - // - // Existing Documents (for MaxDocumentsPerScope Limit) ... - var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken); - - // - // Loop through Files ... - foreach (var file in files) - { - // - XFileDto uploadedFile = null; - - // - try - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - if (file.IsNull() || file.Length == 0) - { - result.SkippedFiles.Add(file?.FileName ?? "(null)"); - continue; - } - - // - // Size Limit ... - if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var fileName = NormalizeFileName(file.FileName); - if (fileName.IsNullOrEmpty()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ... - var isNewDocument = !existingDocuments.Contains(fileName); - if ( - isNewDocument && - scope.Scope != XAiKnowledgeScope.Global && - rag.MaxDocumentsPerScope > 0 && - existingDocuments.Count >= rag.MaxDocumentsPerScope - ) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType)) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - var text = await ExtractText(file, mimeType, cancellationToken); - if (text.IsNullOrEmpty()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ... - var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}"); - if (!chunks.HasChild()) - { - result.SkippedFiles.Add(file.FileName); - continue; - } - - // - // Handle File Save ... - uploadedFile = await fileProvider.Upload( - file: file, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Add Reference File to Prompt Message ... - if ( - !uploadedFile.IsNullOrDefault() && - scope.ScopeId.HasValue && - !uploadedFile.Id.IsDefaultGuid() - ) - { - // - await fileProvider.AddReference( - userInfo: userInfo, - id: uploadedFile.Id, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedFor: scope.Scope.GetStringValue(), - forProvidedId: scope.ScopeId.Value.ToString() - ); - } - - // - // Embed in Batches ... - var vectors = await EmbedChunks( - scope: scope, - chunks: chunks, - fileName: fileName, - mimeType: mimeType, - type: knowledgeType, - ownerId: userInfo.UserId, - ingestedAtUtc: ingestedAtUtc, - cancellationToken: cancellationToken - ); - - // - // Remove Stale Vectors of Same Document ... - if (replaceExisting) - { - // - result.ReplacedCount += await dataProvider.RemoveVectorsAsync( - cancellationToken: cancellationToken, - identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName) - ); - } - - // - // Store ... - var storedCount = await dataProvider.UpsertVectorsAsync( - items: vectors, - cancellationToken: cancellationToken - ); - - // - existingDocuments.Add(fileName); - result.FilesCount++; - result.ChunksCount += storedCount; - result.Documents.Add(new XAiKnowledgeDocumentInfo - { - FileName = fileName, - MimeType = mimeType, - Type = knowledgeType, - Scope = scope.Scope, - ScopeId = scope.ScopeId, - ChunksCount = storedCount, - OwnerId = userInfo.UserId, - IngestedAtUtc = ingestedAt, - }); - - // - logger.LogInformation( - "Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks", - fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount - ); - } - catch (Exception ex) - { - // - logger.LogError(ex, "Ingesting Failed ..."); - - // - // Removing Uploaded File if Chuncking Failed ... - if (!uploadedFile.IsNullOrDefault() && - !uploadedFile.Id.IsDefaultGuid() - ) - { - // - await fileProvider.Remove( - id: uploadedFile.Id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - } - - // - return result; - } - #endregion - - // - #region Ask ... - /// - /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ... - /// Each Tier Fills Remaining TopK; Duplicates are Removed ... - /// - /// - /// - /// - /// - public async Task> RetrieveAsync( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - request.IsNullOrDefault() || - request.Prompt.IsNullOrEmpty() || - !IsValidUser(userInfo) - ) - { - XException.InvalidArgs.Throw(); - } - - // - var rag = configuration.RAGDescriptor; - var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK); - var effectiveMinScore = request.MinScore ?? rag.DefaultMinScore; - - // - // Resolve Tiers (with Ownership Checks) before Embedding ... - var tiers = await ResolveTiers(request, userInfo, cancellationToken); - if (!tiers.HasChild()) - { - return []; - } - - // - // Embed Question (Once) ... - var queryEmbedding = await embeddingService.Embedding( - content: request.Prompt, - cancellationToken: cancellationToken - ); - if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0) - { - XException.ActionFailed.Throw(); - } - - // - var fileName = NormalizeFileName(request.FileName); - var result = new List(); - var seen = new HashSet(StringComparer.Ordinal); - foreach (var tier in tiers) - { - // - var remaining = effectiveTopK - result.Count; - if (remaining <= 0) - { - break; - } - - // - var scopePrefix = GetScopePrefix(tier, userInfo); - var prefix = fileName.IsNullOrEmpty() - ? scopePrefix - : GetDocumentChunkPrefix(scopePrefix, fileName); - - // - var searchResult = await dataProvider.SearchVectorsAsync( - topK: remaining, - type: request.Type, - identifierPrefix: prefix, - minScore: effectiveMinScore, - queryEmbedding: queryEmbedding, - cancellationToken: cancellationToken - ); - - // - foreach (var item in searchResult ?? []) - { - if (seen.Add(item.Identifier ?? item.Id.ToString())) - { - result.Add(item); - } - } - } - - // - return result; - } - #endregion - - // - #region Documents ... - /// - /// List Ingested Documents of Specified Scope ... - /// - /// - /// - /// - /// - public async Task> LoadDocumentsAsync( - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!IsValidUser(userInfo)) - { - XException.InvalidArgs.Throw(); - } - - // - // Resolve & Authorize Scope (Read) ... - scope = NormalizeScope(scope); - await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken); - - // - var vectors = await dataProvider.LoadVectorsAsync( - type: scope.Type, - includeEmbedding: false, - cancellationToken: cancellationToken, - identifierPrefix: GetScopePrefix(scope, userInfo) - ); - - // - var rag = configuration.RAGDescriptor; - var result = (vectors ?? []) - .GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName).IsNullOrEmpty() - ? v.Identifier - : v.Metadata.GetMetadata(rag.MetadataFileName)) - .Select(g => - { - // - var first = g.First(); - var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc); - - // - return new XAiKnowledgeDocumentInfo - { - FileName = g.Key, - Type = first.Type, - Scope = scope.Scope, - ChunksCount = g.Count(), - ScopeId = scope.ScopeId, - MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType), - OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId), - IngestedAtUtc = DateTime.TryParse( - ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt - ) ? dt : null - }; - }) - .OrderBy(d => d.FileName) - .ToList(); - - // - return result; - } - - /// - /// Remove All Vectors of a Document in Specified Scope ... - /// - /// - /// - /// - /// - /// - /// Count of Removed Vectors - public async Task RemoveDocumentAsync( - string fileName, - XAiKnowledgeScopeDescriptor scope = null, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var normalizedFileName = NormalizeFileName(fileName); - if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo)) - { - XException.InvalidArgs.Throw(); - } - - // - // Resolve & Authorize Scope (Write) ... - scope = NormalizeScope(scope); - await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken); - - // - var result = await dataProvider.RemoveVectorsAsync( - cancellationToken: cancellationToken, - identifierPrefix: GetDocumentChunkPrefix(GetScopePrefix(scope, userInfo), normalizedFileName) - ); - if (result > 0) - { - // - // Remove Files using ... - var file = await fileProvider.FindOne( - x => x.FileName - .Equals( - fileName, - StringComparison.InvariantCultureIgnoreCase) && - x.OwnerId - .Equals( - userInfo.UserId, - StringComparison.InvariantCultureIgnoreCase), - cancellationToken: cancellationToken - ); - - // - if (!file.IsNullOrDefault()) - { - // - await fileProvider.Remove( - id: file.Id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - // - return result; - } - - /// - /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ... - /// Store First then Remove Legacy (no Data Loss on Failure); Idempotent ... - /// - /// - /// - /// Count of Migrated Vectors - public async Task MigrateLegacyVectorsAsync( - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!IsValidUser(userInfo)) - { - XException.InvalidArgs.Throw(); - } - - // - var legacyPrefix = $"{userInfo.UserId}{XAiModelsConstants.XAiKnowledgeOwnerSeparator}"; - var legacyVectors = await dataProvider.LoadVectorsAsync( - includeEmbedding: true, - identifierPrefix: legacyPrefix, - cancellationToken: cancellationToken - ); - if (!legacyVectors.HasChild()) - { - return 0; - } - - // - var scope = XAiKnowledgeScopeDescriptor.User(); - var scopePrefix = GetScopePrefix(scope, userInfo); - var migrated = legacyVectors - .Select(v => - { - // - var type = v.Type.IsNullOrEmpty() ? XAiModelsConstants.XAiDefaultKnowledgeType : v.Type; - var metadata = v.Metadata ?? new Dictionary(); - metadata[XAiModelsConstants.XAiKnowledgeMetadataType] = type; - metadata[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = string.Empty; - metadata[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(); - metadata[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = userInfo.UserId; - - // - return new XAiVectorDto - { - Type = type, - Text = v.Text, - Metadata = metadata, - Embedding = v.Embedding, - Identifier = $"{scopePrefix}{v.Identifier.Substring(legacyPrefix.Length)}", - }; - }) - .ToList(); - - // - var result = await dataProvider.UpsertVectorsAsync( - items: migrated, - cancellationToken: cancellationToken - ); - await dataProvider.RemoveVectorsAsync( - identifierPrefix: legacyPrefix, - cancellationToken: cancellationToken - ); - - // - logger.LogInformation( - "Knowledge: Migrated {Count} Legacy Vectors of {OwnerId} into User Scope", - result, userInfo.UserId - ); - - // - return result; - } - - /// - /// Map Search Results to Public Sources ... - /// - /// - /// - public IList ToSources( - IEnumerable context - ) - { - // - var rag = configuration.RAGDescriptor; - var result = (context ?? []) - .Select(c => - { - // - var text = c.Text ?? string.Empty; - var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength); - var chunkIndexText = c.Metadata.GetMetadata(rag.MetadataChunkIndex); - - // - return new XAiDocumentSource - { - Type = c.Type, - Score = c.Score, - Identifier = c.Identifier, - Snippet = text.Substring(0, snippetLength), - FileName = c.Metadata.GetMetadata(rag.MetadataFileName), - Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope), - ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null - }; - }) - .ToList(); - - // - return result; - } - #endregion - - // - #region Private ... - /// - /// Extract Plain Text of a File (Text or Audio Transcript) ... - /// - private async Task ExtractText( - IFormFile file, - string mimeType, - CancellationToken cancellationToken - ) - { - // - try - { - // - using var stream = file.OpenReadStream(); - var extraction = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - var result = extraction?.Text; - if (string.IsNullOrWhiteSpace(result)) - { - result = extraction?.AudioTranscript; - } - - // - return result; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName); - return null; - } - } - - /// - /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ... - /// - private async Task> EmbedChunks( - XAiKnowledgeScopeDescriptor scope, - IList chunks, - string type, - string ownerId, - string fileName, - string mimeType, - string ingestedAtUtc, - CancellationToken cancellationToken - ) - { - // - var rag = configuration.RAGDescriptor; - var batchSize = Math.Max(1, rag.EmbeddingBatchSize); - var result = new List(chunks.Count); - - // - for (var offset = 0; offset < chunks.Count; offset += batchSize) - { - // - cancellationToken.ThrowIfCancellationRequested(); - - // - var batch = chunks.Skip(offset).Take(batchSize).ToList(); - var embeddings = await embeddingService.Embeddings( - batch: batch.Select(c => c.Text).ToArray(), - cancellationToken: cancellationToken - ); - - // - if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count) - { - XException.ActionFailed.Throw(); - } - - // - for (var i = 0; i < batch.Count; i++) - { - // - var chunk = batch[i]; - result.Add(new XAiVectorDto - { - // - Type = type, - Text = chunk.Text, - Embedding = embeddings[i], - Identifier = chunk.Identifier, - Metadata = new Dictionary - { - [rag.MetadataFileName] = fileName, - [rag.MetadataMimeType] = mimeType, - [rag.MetadataChunkIndex] = chunk.Index.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataType] = type, - [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId, - [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(), - [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty, - [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc - } - }); - } - } - - // - return result; - } - - // - #region Scope ... - /// - /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ... - /// - private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope) - { - // - var result = scope ?? XAiKnowledgeScopeDescriptor.User(); - switch (result.Scope) - { - case XAiKnowledgeScope.User: - case XAiKnowledgeScope.Global: - result.ScopeId = null; - break; - - case XAiKnowledgeScope.Project: - case XAiKnowledgeScope.Conversation: - if (!result.ScopeId.HasValue || result.ScopeId.Value == Guid.Empty) - { - XException.InvalidArgs.Throw(); - } - break; - - default: - XException.InvalidArgs.Throw(); - break; - } - - // - return result; - } - - /// - /// Ensure Caller has Access to Scope: - /// User: Own Data | Global: Read = Everyone, Write = Admin - /// Project / Conversation: Caller must be Owner ... - /// - private async Task EnsureAccess( - XAiKnowledgeScopeDescriptor scope, - XUserClaimsInfoDto userInfo, - bool isWrite, - CancellationToken cancellationToken - ) - { - // - switch (scope.Scope) - { - case XAiKnowledgeScope.Global: - if (isWrite && !IsAdmin(userInfo)) - { - XException.NotAuthorized.Throw(); - } - break; - - case XAiKnowledgeScope.Project: - await EnsureProjectOwner(scope.ScopeId.Value, userInfo, cancellationToken); - break; - - case XAiKnowledgeScope.Conversation: - await EnsureConversationOwner(scope.ScopeId.Value, userInfo, cancellationToken); - break; - } - } - - /// - /// Ensure Caller Owns Project ... - /// - private async Task EnsureProjectOwner( - Guid projectId, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken - ) - { - // - var result = await dataProvider.GetProject( - id: projectId, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal)) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - - /// - /// Ensure Caller Owns Conversation ... - /// - private async Task EnsureConversationOwner( - Guid conversationId, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken - ) - { - // - var result = await dataProvider.GetConversation( - id: conversationId, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal)) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - - /// - /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ... - /// - private async Task> ResolveTiers( - XAiKnowledgeAskRequest request, - XUserClaimsInfoDto userInfo, - CancellationToken cancellationToken - ) - { - // - var result = new List(); - Guid? projectId = request.ProjectId.HasValue && request.ProjectId.Value != Guid.Empty - ? request.ProjectId - : null; - - // - // Conversation Tier (+ Implicit Project) ... - if (request.ConversationId.HasValue && request.ConversationId.Value != Guid.Empty) - { - // - var conversation = await EnsureConversationOwner( - request.ConversationId.Value, userInfo, cancellationToken - ); - result.Add(XAiKnowledgeScopeDescriptor.Conversation(request.ConversationId.Value)); - - // - // Conversation must Belong to Requested Project ... - if ( - projectId.HasValue && - conversation.ProjectId != Guid.Empty && - projectId.Value != conversation.ProjectId - ) - { - XException.InvalidArgs.Throw(); - } - if (conversation.ProjectId != Guid.Empty) - { - projectId = conversation.ProjectId; - } - } - - // - // Project Tier ... - if (projectId.HasValue) - { - await EnsureProjectOwner(projectId.Value, userInfo, cancellationToken); - result.Add(XAiKnowledgeScopeDescriptor.Project(projectId.Value)); - } - - // - // User / Global Tiers ... - if (request.IncludeUser) - { - result.Add(XAiKnowledgeScopeDescriptor.User()); - } - if (request.IncludeGlobal) - { - result.Add(XAiKnowledgeScopeDescriptor.Global()); - } - - // - return result; - } - - /// - /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"): - /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ... - /// - private static string GetScopePrefix( - XAiKnowledgeScopeDescriptor scope, - XUserClaimsInfoDto userInfo - ) - { - // - var separator = XAiModelsConstants.XAiKnowledgeSeparator; - var result = scope.Scope switch - { - XAiKnowledgeScope.Global => $"{XAiModelsConstants.XAiKnowledgeGlobalPrefix}{separator}", - XAiKnowledgeScope.User => $"{XAiModelsConstants.XAiKnowledgeUserPrefix}{separator}{userInfo.UserId}{separator}", - XAiKnowledgeScope.Project => $"{XAiModelsConstants.XAiKnowledgeProjectPrefix}{separator}{scope.ScopeId:D}{separator}", - XAiKnowledgeScope.Conversation => $"{XAiModelsConstants.XAiKnowledgeConversationPrefix}{separator}{scope.ScopeId:D}{separator}", - _ => null - }; - if (result.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - return result; - } - - /// - /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ... - /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ... - /// - private string GetDocumentChunkPrefix( - string scopePrefix, - string fileName - ) - { - return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}"; - } - - /// - /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ... - /// - private string NormalizeFileName(string fileName) - { - // - if (string.IsNullOrWhiteSpace(fileName)) - { - return null; - } - - // - // Strip Client Side Path (Both Separators) ... - var name = Path.GetFileName(fileName.Replace('\\', '/'))?.Trim(); - if (name.IsNullOrEmpty()) - { - return null; - } - - // - foreach (var c in UnsafeFileNameChars) - { - name = name.Replace(c, '_'); - } - var chunkSeparator = configuration.TextChunker.ChunkIdentifierSeparator; - if (!chunkSeparator.IsNullOrEmpty()) - { - name = name.Replace(chunkSeparator, "_"); - } - - // - return name; - } - - /// - /// Load Distinct Document Names of a Scope ... - /// - private async Task> LoadDocumentNames( - string scopePrefix, - CancellationToken cancellationToken - ) - { - // - var vectors = await dataProvider.LoadVectorsAsync( - includeEmbedding: false, - identifierPrefix: scopePrefix, - cancellationToken: cancellationToken - ); - - // - var rag = configuration.RAGDescriptor; - var result = new HashSet( - (vectors ?? []) - .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName)) - .Where(n => !n.IsNullOrEmpty()), - StringComparer.Ordinal - ); - - // - return result; - } - - /// - /// Is Valid User ... - /// - private static bool IsValidUser(XUserClaimsInfoDto userInfo) - { - return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty(); - } - - /// - /// Is Caller Admin ... - /// - private static bool IsAdmin(XUserClaimsInfoDto userInfo) - { - // - var result = - !userInfo.IsNullOrDefault() && - !userInfo.Roles.IsNullOrDefault() && - userInfo.Roles.Any(r => string.Equals(r, XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase)); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiService.cs - -using xAiApi.Constants; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers -{ - public class XAiService : XAIServiceBase, IXAiService - { - public XAiService( - IXAiRAGService ragProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider, - IXFileContentExtractor fileContentExtractor - ) : base( - ragProvider, - dataProvider, - logger, - configuration, - validationProvider, - mcpServerProvider, - fileContentExtractor, - XAiApiConstants.XAiDefaultModelName - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs - -using System; -using System.Linq; -using System.Text; -using xModels.Dtos; -using xAiApi.Models; -using System.Threading; -using xAiApi.Constants; -using xAiModels.Models; -using TimeZoneConverter; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Providers; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Interfaces; -using xAiModels.Extensions; -using System.Globalization; -using xAiApi.Configurations; -using xExceptions.Constants; -using xAiModels.Models.Dtos; -using xAiService.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; -using System.Runtime.CompilerServices; - -namespace xAiApi.Providers -{ - /// - /// Base Ai Service ... - /// - public abstract class XAIServiceBase : IXAiServiceBase - { - /// - /// Chat Options ... - /// - public ChatOptions Options { get; } - - /// - /// Descriptor of Models which used in Service ... - /// - public XAiModelDescriptor Descriptor { get; } - - private readonly IXAiRAGService ragProvider; - private readonly IXAiDataProvider dataProvider; - private readonly ILogger logger; - private readonly XAiApiConfiguration configuration; - private readonly XValidationProvider validationProvider; - private readonly IXAiMcpServerProvider mcpServerProvider; - private readonly IXFileContentExtractor fileContentExtractor; - - // - private readonly bool useProvidedMcpServers; - - protected XAIServiceBase( - IXAiRAGService ragProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider, - IXFileContentExtractor fileContentExtractor, - string model = null, - bool useProvidedMcpServers = true - ) - { - // - this.logger = logger; - this.ragProvider = ragProvider; - this.dataProvider = dataProvider; - this.configuration = configuration; - this.mcpServerProvider = mcpServerProvider; - this.validationProvider = validationProvider; - this.fileContentExtractor = fileContentExtractor; - this.useProvidedMcpServers = useProvidedMcpServers; - - // - // Prepare Embedding Model Descriptor ... - Descriptor = configuration.GetModel(model); - if (!Descriptor.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Prepare Chat Options based On Tools ... - Options = new ChatOptions(); - } - - // - #region Actions ... - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - public virtual async Task AskTextAsync( - string prompt, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools]; - } - - // - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... - if (!response.IsValid()) - { - // - // Dispose Client ... - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - // Retrieve Response Text ... - var result = response.Text; - - // - return result; - } - - /// - /// Base Method for Communicate with LLM ... - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextAsEnumerable( - string prompt, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Check Prompt Exists ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history - ); - - // - await foreach (var res in enumerable) - { - // - // Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question By Providing Vector Search Result ... - /// - /// - /// - /// - /// - /// - public virtual async Task AskTextByContextAsync( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var response = await client.GetResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... - if (!response.IsValid()) - { - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - var result = response.Text; - - // - return result; - } - - /// - /// Ask a Question By By Providing Vector Search Result and Stream Response ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextByContextAsEnumerable( - string prompt, - IList context = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - using var client = Descriptor.GetClient(); - var history = GetHistory(prompt, context); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var enumerable = client.GetStreamingResponseAsync( - options: Options, - messages: history, - cancellationToken: cancellationToken - ); - - // - await foreach (var res in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question By Rag Retrive From Knowledge ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AskTextFromKnowledgeAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Prepare Requirements ... - var prep = await PrepareChatRequirementsAsync( - topK: topK, - type: type, - files: null, - prompt: prompt, - projectId: null, - minScore: minScore, - userInfo: userInfo, - connectionId: null, - conversationId: null, - persistPrompt: false, - additionalContents: null, - addFilesToKnowledge: false, - resolveConversation: false, - extractFileContents: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var response = await client - .GetResponseAsync( - options: Options, - messages: prep.History, - cancellationToken: cancellationToken - ); - if (!response.IsValid()) - { - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - return response.Text; - } - - /// - /// Ask a Question By Rag Retrive From Knowledge and Stream Response ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskTextFromKnowledgeAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validation ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Prepare Requirements ... - var prep = await PrepareChatRequirementsAsync( - topK: topK, - type: type, - files: null, - prompt: prompt, - projectId: null, - minScore: minScore, - userInfo: userInfo, - connectionId: null, - conversationId: null, - persistPrompt: false, - additionalContents: null, - resolveConversation: false, - addFilesToKnowledge: false, - extractFileContents: false, - cancellationToken: cancellationToken - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var stream = client - .GetStreamingResponseAsync( - options: Options, - messages: prep.History, - cancellationToken: cancellationToken - ); - await foreach (var res in stream) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - - /// - /// Ask a Question as Prompt and Retrieve Response ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AskAsync( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - additionalContents: null, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken, - extractFileContents: extractFileContents, - addFilesToKnowledge: addFilesToKnowledge - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var response = await client.GetResponseAsync( - options: Options, - messages: prep.History, - cancellationToken: cancellationToken - ); - if (!response.IsValid()) - { - // - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - var result = await dataProvider.AddMessage( - item: new XAiMessageDto - { - Content = response.Text, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - Role = XAiChatRole.Assistant, - ConversationId = prep.Conversation.Id, - ConversationTitle = prep.Conversation.Title, - }, - connectionId: connectionId, - conversationId: prep.Conversation.Id, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable AskAsEnumerable( - string prompt, - string type = null, - int? topK = null, - float? minScore = null, - Guid? projectId = null, - Guid? conversationId = null, - string connectionId = null, - bool extractFileContents = false, - bool addFilesToKnowledge = true, - IFormFileCollection files = null, - XUserClaimsInfoDto userInfo = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - var prep = await PrepareChatRequirementsAsync( - type: type, - topK: topK, - files: files, - prompt: prompt, - minScore: minScore, - userInfo: userInfo, - persistPrompt: true, - projectId: projectId, - additionalContents: null, - resolveConversation: true, - connectionId: connectionId, - conversationId: conversationId, - cancellationToken: cancellationToken, - extractFileContents: extractFileContents, - addFilesToKnowledge: addFilesToKnowledge - ); - - // - using var client = Descriptor.GetClient(); - - // - // Handle Provided MCP Servers ... - if (useProvidedMcpServers) - { - // - var availableTools = await mcpServerProvider - .GetAvailableToolsAsync( - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - Options.Tools = [.. availableTools.Cast()]; - } - - // - var stream = client - .GetStreamingResponseAsync( - options: Options, - messages: prep.History, - cancellationToken: cancellationToken - ); - - // - var answer = new System.Text.StringBuilder(); - long sequence = 1; - await foreach (var res in stream) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - answer.Append(res.Text); - yield return new XAiResonseMessage - { - Content = res.Text, - Sequence = sequence++, - OwnerId = userInfo.UserId, - Role = XAiChatRole.Assistant, - RespondedOn = DateTime.UtcNow, - RespondTo = prep.PersistedPromptMessage.Id, - }; - } - - // - // Adding Full Message ... - await dataProvider.AddMessage( - item: new XAiMessageDto - { - OwnerId = userInfo.UserId, - Content = answer.ToString(), - CreatedOn = DateTime.UtcNow, - Role = XAiChatRole.Assistant, - ConversationId = prep.Conversation.Id, - }, - connectionId: connectionId, - conversationId: prep.Conversation.Id, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Loaders ... - /// - /// Load AI Projects ... - /// - /// - /// - /// - /// - /// - public virtual async Task> LoadProjects( - string ownerId, - string connectionId = null, - bool includeDefaults = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadProjects( - ownerId: ownerId, - fillConversations: false, - connectionId: connectionId, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - - // - // Handle Defaults Including ... - if (includeDefaults) - { - // - // Here we have to fill Conversations of Default Project ... - var defaultProjectId = result.GetDafaultProject(ownerId); - var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId); - result = result.Where(x => x.Id != defaultProjectId); - - // - // Reading Conversations of Specified Default Project ... - var defaultProjectConversations = await dataProvider.LoadConversations( - fillMessages: false, - connectionId: connectionId, - projectId: defaultProjectId, - cancellationToken: cancellationToken - ); - var defaultConversationId = defaultProjectConversations.GetDefaultConversation( - ownerId: ownerId, - projectId: defaultProjectId - ); - var defaultConversation = defaultProjectConversations.First(x => x.Id == defaultConversationId); - defaultProjectConversations = defaultProjectConversations.Where(x => x.Id != defaultConversationId); - - // - // Reading Default Conversations Messages ... - var defaultConversationMessages = await dataProvider.LoadMessages( - cancellationToken: cancellationToken, - conversationId: defaultConversationId - ); - - // - defaultConversation.Messages = [.. defaultConversationMessages.OrderByDescending(m => m.CreatedOn)]; - defaultProjectConversations = [defaultConversation, .. defaultProjectConversations]; - defaultProject.Conversations = [.. defaultProjectConversations]; - result = [defaultProject, .. result]; - } - - // - return result; - } - - /// - /// Load Conversations of Specified AI Project ... - /// - /// - /// - /// - /// - public virtual async Task> LoadConversations( - Guid projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadConversations( - fillMessages: false, - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - public virtual async Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.LoadMessages( - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Queries ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - public virtual async Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await dataProvider.QueryProjects( - query: query, - ownerId: ownerId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty() || - projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Project ... - var project = await dataProvider.GetProject( - id: projectId, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (ownerId != project.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - var result = await dataProvider.QueryConversations( - query: query, - ownerId: ownerId, - projectId: projectId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (ownerId.IsNullOrEmpty() || - conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Conversation ... - var conversation = await dataProvider.GetConversation( - id: conversationId, - fillMessages: false, - cancellationToken: cancellationToken - ); - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (ownerId != conversation.OwnerId) - { - XException.NotAllowed.Throw(); - } - - // - var result = await dataProvider.QueryMessages( - query: query, - ownerId: ownerId, - conversationId: conversationId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Creators ... - /// - /// Create an AI Project ... - /// - /// - /// - /// - /// - /// - public virtual async Task CreateProject( - string ownerId, - XAiProjectDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await dataProvider.CreateProject( - item: item, - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await dataProvider.CreateConversation( - item: item, - ownerId: ownerId, - projectId: projectId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Content Extraction ... - /// - /// Try to Extract Files Content ... - /// - /// - /// - /// - /// - public async Task ExtractContent( - IFormFileCollection files, - string[] extractors = null, - CancellationToken cancellationToken = default - ) - { - // - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - var extractionResults = new List(); - foreach (var file in files) - { - // - if (file.IsNull() || file.Length == 0) - { - continue; - } - - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (!fileContentExtractor.CanExtract(mimeType, extractors)) - { - continue; - } - - // - try - { - // - using var stream = file.OpenReadStream(); - - // - var fr = await fileContentExtractor.ExtractRichAsync( - fileStream: stream, - mimeType: mimeType, - extractors: extractors, - fileName: file.FileName, - cancellationToken: cancellationToken - ); - - // - if (fr.IsValid()) - { - extractionResults.Add(fr); - } - } - catch (OperationCanceledException) - { - throw; - } - catch - { - continue; - } - } - - // - var result = string.Empty; - if (extractionResults.HasChild()) - { - // - extractionResults.ForEach(er => - { - result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----"; - }); - } - - // - return result; - } - #endregion - - /// - /// Base Dispose Action ... - /// - /// - public virtual void Dispose() - { } - - // - #region Private ... - /// - /// Prepare a Message History List for LLM Communication based on Prompt ... - /// - /// - /// - /// - private IList GetHistory( - string prompt = null, - bool forcePrompt = true - ) - { - // - // Validate Args ... - if (prompt.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // User Prompt ... - var promptMessage = new ChatMessage( - ChatRole.User, - prompt - ); - - // - // Preparing Introduction Prompt ... - var introductionPrompt = new ChatMessage( - ChatRole.System, - configuration.GetPrompt() - ); - - // - List result = - [ - introductionPrompt, - ]; - - // - // Prepare Datetime ... - var datetimeContext = BuildDateTimeContext(); - if (!datetimeContext.IsNullOrEmpty()) - { - // - result.Add(new ChatMessage( - ChatRole.Assistant, - datetimeContext - )); - } - - // - if (forcePrompt && - prompt is not null && - !prompt.IsNullOrEmpty()) - { - result.Add(promptMessage); - } - - // - return result; - } - - /// - /// Build Chat History for RAG: - /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ... - /// - /// - /// - /// - private IList GetHistory( - string prompt, - IEnumerable context - ) - { - // - var introductionPrompt = configuration.GetPrompt(); - var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); - if (ragPrompt.IsNullOrEmpty()) - { - XException.InvalidConfiguration.Throw(); - } - - // - var datetimeContext = BuildDateTimeContext(); - var contextBlock = BuildContextBlock(context); - var systemText = introductionPrompt; - if (context.HasChild() && - !contextBlock.IsNullOrEmpty() - ) - { - // - systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}"; - - // - if (!datetimeContext.IsNullOrEmpty()) - { - // - systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; - } - - // - systemText += - $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"Context:{Environment.NewLine}{contextBlock}"; - } - - // - List result = - [ - new ChatMessage(ChatRole.System, systemText), - new ChatMessage(ChatRole.User, prompt), - ]; - - // - return result; - } - - /// - /// Implementing Memory Strategy here ... - /// - /// - /// - /// - /// - /// - private async Task> PrepareMemory( - XAiProjectDto project, - IEnumerable messages, - IEnumerable context = null, - CancellationToken cancellationToken = default - ) - { - // - var result = new List(); - - // - await Task.FromResult(true); - - // - // Retrieve Introduction Prompt ... - var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); - var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName); - if (ragPrompt.IsNullOrEmpty() || - introductionPrompt.IsNullOrEmpty() - ) - { - XException.InvalidData.Throw(); - } - - // - var contextBlock = BuildContextBlock(context); - var systemText = introductionPrompt; - if (context.HasChild() && - !contextBlock.IsNullOrEmpty()) - { - // - systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + - $"Context:{Environment.NewLine}{contextBlock}"; - } - - // - // Prepare Datetime ... - var datetimeContext = BuildDateTimeContext(); - if (!datetimeContext.IsNullOrEmpty()) - { - // - systemText += - $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; - } - - // - // Apply Project Prompt as System Text ... - if (!project.IsNullOrDefault() && - !project.Prompt.IsNullOrEmpty()) - { - systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}"; - } - - // - // Add System Message ... - result.Add(new ChatMessage(ChatRole.System, systemText)); - - // - // Attach Message ... - if (messages.HasChild()) - { - // - // TODO: Here we can Implement Memory Management based on - // Last nth of Messages, or Summarization of Messages, etc ... - result = [..result, ..messages - .OrderBy(m => m.CreatedOn) - .Select(m => m.ToChatMessages())]; - } - - // - return result; - } - - /// - /// Convert Context Chunks to a Numbered Text Block ... - /// - /// - /// - private string BuildContextBlock( - IEnumerable context - ) - { - // - var result = "(no context)"; - - // - var items = context? - .Where(c => - !c.IsNullOrDefault() && - !c.Text.IsNullOrEmpty() - ) - .ToList() ?? []; - if (!items.HasChild()) - { - return result; - } - - // - var index = 1; - var builder = new System.Text.StringBuilder(); - foreach (var item in items) - { - // - var identifier = item.Identifier.IsNullOrEmpty() - ? item.Id.ToString() - : item.Identifier; - - // - builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})"); - builder.AppendLine(item.Text.Trim()); - builder.AppendLine("----"); - - // - index++; - } - - // - result = builder.ToString(); - - // - return result; - } - - /// - /// Normalizing Rag Params ... - /// - /// - /// - /// - private void NormalizeRagParams( - ref int? topK, - ref float? minScore, - ref string type - ) - { - // - var rag = configuration.RAGDescriptor; - - // - // TopK ... - if (!topK.HasValue || topK.Value < 1) - { - topK = rag.DefaultTopK; - } - else if (topK.Value > rag.MaxTopK) - { - topK = rag.MaxTopK; - } - - // - // Min Score ... - if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1) - { - minScore = rag.DefaultMinScore; - } - - // - // Type ... - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - } - - /// - /// Retrieve Prepared Chat Context ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private async Task PrepareChatRequirementsAsync( - int? topK, - string type, - string prompt, - float? minScore, - Guid? projectId, - bool persistPrompt, - string connectionId, - Guid? conversationId, - bool resolveConversation, - IFormFileCollection files, - XUserClaimsInfoDto userInfo, - bool extractFileContents = true, - bool addFilesToKnowledge = false, - IList additionalContents = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotEmpty(prompt) - .AddNotNull(userInfo) - .AddNotEmpty(userInfo.UserId) - .ValidateGroup(); - - // - // Normalize ... - NormalizeRagParams( - topK: ref topK, - type: ref type, - minScore: ref minScore - ); - - // - // Resolve Project and Conversation ... - XAiProjectDto project = null; - XAiConversationDto conversation = null; - if (resolveConversation) - { - // - // Check Project ... - if (!projectId.HasValue || projectId.Value.IsDefaultGuid()) - { - // - project = await dataProvider.GetDefaultProject( - ownerId: userInfo.UserId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - projectId = project.Id; - } - else - { - // - project = await dataProvider.GetProject( - id: projectId.Value, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - } - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check Conversation ... - if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid()) - { - // - conversation = await dataProvider.GetDefaultConversation( - ownerId: userInfo.UserId, - projectId: projectId.Value, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - conversationId = conversation.Id; - } - else - { - // - conversation = await dataProvider.GetConversation( - fillMessages: false, - id: conversationId.Value, - cancellationToken: cancellationToken - ); - } - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - } - - // - // Ingest Files if Provided and also Resolve Conversation Flagged ... - if ( - files.HasChild() && - resolveConversation && - addFilesToKnowledge - ) - { - // - try - { - // - var ingestResult = await ragProvider - .IngestAsync( - files: files, - userInfo: userInfo, - replaceExisting: true, - connectionId: connectionId, - scope: XAiKnowledgeScopeDescriptor - .Conversation( - type: type, - conversationId: conversationId.Value - ), - cancellationToken: cancellationToken - ); - if (ingestResult.SkippedFiles.HasChild()) - { - // - logger.LogWarning( - "Ingest skipped {Count} file(s): {Files}", - ingestResult.SkippedFiles.Count, - string.Join(", ", ingestResult.SkippedFiles)); - } - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - // - logger.LogError(ex, - "Ingest failed for prompt '{Prompt}'. Continuing without attachments.", - prompt - ); - } - } - - // - // If there isn't Files need to add Files to Knowledge ... - if (files.HasChild() && - !addFilesToKnowledge - ) - { - // - // Extract File Content and add them to Additional Contents ... - foreach (var file in files) - { - // - var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty; - if (mimeType.IsNullOrEmpty() || - !fileContentExtractor.CanExtract(mimeType)) - { - continue; - } - - // - using var stream = file.OpenReadStream(); - - // - // Extract File Content if necessary ... - if (extractFileContents) - { - // - var content = await fileContentExtractor.ExtractAsync( - fileStream: stream, - mimeType: mimeType, - cancellationToken: cancellationToken - ); - if (!content.IsNullOrEmpty()) - { - // - var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}"); - additionalContents = [.. additionalContents, fileContent]; - } - } - else - { - // - var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken); - additionalContents = [.. additionalContents, fileContent]; - } - } - } - - // - // Request Knowledge ... - var knowledgeRequest = new XAiKnowledgeAskRequest - { - TopK = topK, - Type = type, - Prompt = prompt, - IncludeUser = true, - MinScore = minScore, - IncludeGlobal = true, - ProjectId = resolveConversation ? projectId : null, - ConversationId = resolveConversation ? conversationId : null, - }; - var context = await ragProvider - .RetrieveAsync( - userInfo: userInfo, - request: knowledgeRequest, - cancellationToken: cancellationToken - ); - - // - // Prepare History and Persisted Prompt Message ... - IList history; - XAiMessageDto persistedPromptMessage = null; - if (persistPrompt) - { - // - // Retrieve Conversation Message ... - var messages = await dataProvider - .LoadMessages( - conversationId: conversationId.Value, - cancellationToken: cancellationToken - ); - - // - // Prepare History based on Memory Strategies ... - history = await PrepareMemory( - context: context, - project: project, - messages: messages, - cancellationToken: cancellationToken - ); - - // - // Persist Prompt Message ... - persistedPromptMessage = await dataProvider.AddMessage( - item: new XAiMessageDto - { - Content = prompt, - Role = XAiChatRole.User, - OwnerId = userInfo.UserId, - CreatedOn = DateTime.UtcNow, - ConversationId = conversationId.Value, - ConversationTitle = conversation.Title, - }, - connectionId: connectionId, - conversationId: conversationId.Value, - cancellationToken: cancellationToken - ); - - // - history - .Add(persistedPromptMessage - .ToChatMessages(additionalContents: additionalContents)); - } - else - { - // - history = GetHistory(prompt, context); - } - - // - // Prepare Result ... - var result = new XPreparedChatContext - { - Project = project, - Context = context, - History = history, - Conversation = conversation, - PersistedPromptMessage = persistedPromptMessage, - }; - - // - return result; - } - - private string BuildDateTimeContext() - { - // - var cfg = configuration.DateTime; - if (cfg == null || !cfg.InjectIntoSystemPrompt) - { - return string.Empty; - } - - // - try - { - // - var tz = ResolveTimezone(cfg.DefaultTimezone); - var nowUtc = DateTime.UtcNow; - var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); - - // - var sb = new StringBuilder(); - sb.AppendLine("[CURRENT DATETIME — for your reference]"); - sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}"); - - // - if (cfg.IncludeDayOfWeek) - { - sb.AppendLine($"Day of week: {nowLocal:dddd}"); - } - - // - if (cfg.IncludePersianCalendar) - { - // - var pc = new PersianCalendar(); - sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); - } - - // - if (cfg.IncludeUnixTimestamp) - { - sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); - } - - // - sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations."); - return sb.ToString().TrimEnd(); - } - catch - { - return string.Empty; - } - } - - private static TimeZoneInfo ResolveTimezone(string id) - { - // - if (id.IsNullOrEmpty()) - { - return TimeZoneInfo.Utc; - } - - // - try - { - return TZConvert.GetTimeZoneInfo(id); - } - catch - { - return TimeZoneInfo.Utc; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XDefaultThinkingAiService.cs - -using xAiApi.Constants; -using xAiApi.Interfaces; -using xCommons.Providers; -using xAiModels.Interfaces; -using xAiApi.Configurations; -using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers -{ - public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService - { - public XDefaultThinkingAiService( - IXAiRAGService ragProvider, - IXAiDataProvider dataProvider, - ILogger logger, - XAiApiConfiguration configuration, - XValidationProvider validationProvider, - IXAiMcpServerProvider mcpServerProvider, - IXFileContentExtractor fileContentExtractor, - ReasoningEffort effort = ReasoningEffort.Medium, - ReasoningOutput output = ReasoningOutput.Full - ) : base( - ragProvider, - dataProvider, - logger, - configuration, - validationProvider, - mcpServerProvider, - fileContentExtractor, - XAiApiConstants.XAiDefaultThinkingModelName - ) - { - // - // Preparing Reasoning ... - Options.Reasoning = new ReasoningOptions - { - Output = output, - Effort = effort, - }; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStore.cs - -using System; -using System.Linq; -using xAiApi.Models; -using xAiApi.Interfaces; -using xAiModels.Helpers; -using xAiModels.Models.Dtos; -using System.Collections.Generic; -using System.Collections.Concurrent; - -namespace xAiApi.Providers -{ - public class XInMemoryVectorStore : IXInMemoryVectorStore - { - private const int DefaultTtlMinutes = 30; - private readonly ConcurrentDictionary sessions = new ConcurrentDictionary(); - public int Count { get { RemoveExpired(); return sessions.Count; } } - - public Guid CreateSession( - string ownerId = null, - TimeSpan? ttl = null - ) - { - // - var result = CreateSession(null, ownerId, ttl); - return result; - } - - public Guid CreateSession( - IEnumerable vectors, - string ownerId = null, - TimeSpan? ttl = null - ) - { - // - var now = DateTime.UtcNow; - var session = new XAiDocumentSession - { - Id = Guid.NewGuid(), - OwnerId = ownerId, - CreatedAtUtc = now, - LastAccessAtUtc = now, - Ttl = NormalizeTtl(ttl), - Vectors = Copy(vectors) - }; - sessions[session.Id] = session; - var result = session.Id; - return result; - } - - public bool Replace( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ) - { - // - XAiDocumentSession session; - if (!TryGet(sessionId, out session, ownerId)) - { - return false; - } - - // - lock (session.SyncRoot) - { - session.Vectors = Copy(vectors); - session.LastAccessAtUtc = DateTime.UtcNow; - } - - // - return true; - } - - public bool Add( - Guid sessionId, - IEnumerable vectors, - string ownerId = null - ) - { - // - XAiDocumentSession session; - if (!TryGet(sessionId, out session, ownerId)) - { - return false; - } - var additions = Copy(vectors); - lock (session.SyncRoot) - { - // - foreach (var vector in additions) - { - session.Vectors.Add(vector); - } - - // - session.LastAccessAtUtc = DateTime.UtcNow; - } - return true; - } - - public IList Search( - Guid sessionId, - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, - string ownerId = null - ) - { - // - var result = new List(); - if (topK <= 0 || queryEmbedding.Length == 0) - { - return result; - } - - // - XAiDocumentSession session; - if (!TryGet(sessionId, out session, ownerId)) - { - return result; - } - - // - var query = queryEmbedding.ToArray(); - lock (session.SyncRoot) - { - // - session.LastAccessAtUtc = DateTime.UtcNow; - foreach (var vector in session.Vectors) - { - // - if (vector == null || vector.Embedding.Length == 0) - { - continue; - } - - // - var score = VectorHelper.CosineSimilarity( - query, - vector.Embedding.ToArray() - ); - - // - if (score >= minScore) - { - // - result.Add(new XAiVectorSearchResult - { - Score = score, - Id = vector.Id, - Text = vector.Text, - Metadata = vector.Metadata, - Identifier = vector.Identifier, - }); - } - } - } - - // - result = [.. result - .OrderByDescending(x => x.Score) - .Take(topK)]; - - // - return result; - } - - public bool TryGet( - Guid sessionId, - out XAiDocumentSession session, - string ownerId = null - ) - { - // - session = null; - XAiDocumentSession found; - if (!sessions.TryGetValue(sessionId, out found)) - { - return false; - } - - // - lock (found.SyncRoot) - { - // - XAiDocumentSession current; - if (!sessions.TryGetValue(sessionId, out current) || - !ReferenceEquals(current, found)) - return false; - - // - if (!OwnerMatches(found, ownerId)) - return false; - - // - if (found.IsExpired(DateTime.UtcNow)) - { - // - sessions.TryRemove(sessionId, out found); - return false; - } - - // - found.LastAccessAtUtc = DateTime.UtcNow; - session = found; - return true; - } - } - - public bool Remove( - Guid sessionId, - string ownerId = null - ) - { - // - XAiDocumentSession session; - if (!TryGet(sessionId, out session, ownerId)) return false; - return sessions.TryRemove(sessionId, out session); - } - - public int RemoveExpired() - { - // - var now = DateTime.UtcNow; var removed = 0; - foreach (var pair in sessions) { if (pair.Value.IsExpired(now) && sessions.TryRemove(pair.Key, out _)) removed++; } - return removed; - } - - // - #region Private ... - private static bool OwnerMatches( - XAiDocumentSession session, - string ownerId - ) - { - return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal); - } - - private static TimeSpan NormalizeTtl( - TimeSpan? ttl - ) - { - return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value; - } - - private static IList Copy( - IEnumerable vectors - ) - { - return vectors == null ? new List() : vectors.Where(x => x != null).ToList(); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStoreCleanupService.cs - -using System; -using System.Threading; -using xAiApi.Interfaces; -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace xAiApi.Providers -{ - /// - /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ... - /// - public class XInMemoryVectorStoreCleanupService : BackgroundService - { - /// - /// Default Cleanup Interval ... - /// - public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5); - - private readonly TimeSpan interval; - private readonly IXInMemoryVectorStore vectorStore; - private readonly ILogger logger; - - public XInMemoryVectorStoreCleanupService( - IXInMemoryVectorStore vectorStore, - ILogger logger - ) - { - this.logger = logger; - this.vectorStore = vectorStore; - this.interval = DefaultInterval; - } - - /// - /// Cleanup Loop ... - /// - /// - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - // - try - { - // - while (!stoppingToken.IsCancellationRequested) - { - // - await Task.Delay(interval, stoppingToken); - - // - try - { - // - var removed = vectorStore.RemoveExpired(); - if (removed > 0) - { - // - logger.LogInformation( - "InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining", - removed, - vectorStore.Count - ); - } - } - catch (Exception ex) - { - logger.LogError(ex, "InMemoryVectorStore Cleanup Failed"); - } - } - } - catch (OperationCanceledException) - { - // Shutdown ... - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XTextChunker.cs - -using System.Linq; -using System.Text; -using xAiApi.Models; -using xAiApi.Interfaces; -using xAiApi.Extensions; -using xCommons.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace xAiApi.Providers -{ - /// - /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy: - /// Paragraphs -> Sentences -> Words -> Hard Cut ... - /// - public class XTextChunker : IXTextChunker - { - /// - /// Default Options which used when no Options Provided ... - /// - private readonly XAiApiConfiguration configuration; - - /// - /// Matches Paragraph Boundaries (two or more Line Breaks) ... - /// - private static readonly Regex ParagraphSplitter = new( - @"\n\s*\n+", - RegexOptions.Compiled - ); - - /// - /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ... - /// - private static readonly Regex SentenceSplitter = new( - @"(?<=[\.\!\?؟。!?])\s+|(?<=\n)", - RegexOptions.Compiled - ); - - /// - /// Matches Repeated Horizontal Whitespaces ... - /// - private static readonly Regex HorizontalWhitespace = new( - @"[ \t\f\v\u00A0]{2,}", - RegexOptions.Compiled - ); - - /// - /// Matches Three or more Line Breaks ... - /// - private static readonly Regex ExcessiveLineBreaks = new( - @"\n{3,}", - RegexOptions.Compiled - ); - - public XTextChunker( - XAiApiConfiguration configuration - ) - { - // - // Validate Configuration ... - if ( - !configuration.IsValid() || - !configuration.TextChunker.IsValid() - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - this.configuration = configuration; - } - - /// - /// Split Text into Chunks ... - /// - /// - /// - /// - public IList Chunk( - string text, - string source = null - ) - { - // - var result = new List(); - if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text)) - { - return result; - } - - // - // Normalize ... - var normalized = configuration.TextChunker.NormalizeWhitespace - ? Normalize(text) - : text; - - // - // Short Circuit for Small Texts ... - if (normalized.Length <= configuration.TextChunker.ChunkSize) - { - // - result.Add(CreateChunk(normalized, 0, 0, source)); - return result; - } - - // - // Build Atomic Units (never larger than ChunkSize) ... - var units = BuildUnits(normalized); - - // - // Accumulate Units into Chunks with Overlap ... - var chunks = Accumulate(units); - - // - // Merge too Small Tail Chunks ... - chunks = MergeSmallChunks(chunks); - - // - for (var i = 0; i < chunks.Count; i++) - { - result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source)); - } - - // - return result; - } - - /// - /// Split Text into Chunks and Return only Texts ... - /// - /// - /// - public IList ChunkTexts(string text) - { - // - var result = Chunk(text, null) - .Select(c => c.Text) - .ToList(); - - // - return result; - } - - // - #region Private ... - /// - /// Internal Text Unit with its Offset in Normalized Source ... - /// - private readonly struct Unit - { - public Unit(string text, int offset) - { - Text = text; - Offset = offset; - } - - public string Text { get; } - public int Offset { get; } - } - - /// - /// Normalize Line Endings and Whitespaces ... - /// - /// - /// - private string Normalize(string text) - { - // - var result = text - .Replace("\r\n", "\n") - .Replace('\r', '\n'); - - // - result = HorizontalWhitespace.Replace(result, " "); - result = ExcessiveLineBreaks.Replace(result, "\n\n"); - - // - result = result.Trim(); - - // - return result; - } - - /// - /// Create Chunk Model ... - /// - /// - /// - /// - /// - /// - private XTextChunk CreateChunk( - string text, - int offset, - int index, - string source - ) - { - // - var identifier = source.IsNullOrEmpty() - ? index.ToString() - : $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}"; - - // - var result = new XTextChunk - { - Text = text, - Index = index, - Source = source, - StartOffset = offset, - Identifier = identifier - }; - - // - return result; - } - - /// - /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ... - /// - /// - /// - private List BuildUnits(string text) - { - // - var result = new List(); - - // - foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0)) - { - // - if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize) - { - // - result.Add(paragraph); - continue; - } - - // - // Paragraph too Long -> Sentences ... - foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset)) - { - // - if (sentence.Text.Length <= configuration.TextChunker.ChunkSize) - { - // - result.Add(sentence); - continue; - } - - // - // Sentence too Long -> Word Boundary Hard Cut ... - result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize)); - } - } - - // - return result; - } - - /// - /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ... - /// - /// - /// - /// - /// - private IEnumerable SplitWithOffsets( - string text, - Regex splitter, - int baseOffset - ) - { - // - var position = 0; - foreach (Match match in splitter.Matches(text)) - { - // - var part = text.Substring(position, match.Index - position); - var unit = TrimUnit(part, baseOffset + position); - if (!unit.Text.IsNullOrEmpty()) - { - yield return unit; - } - - // - position = match.Index + match.Length; - } - - // - if (position < text.Length) - { - // - var tail = TrimUnit(text.Substring(position), baseOffset + position); - if (!tail.Text.IsNullOrEmpty()) - { - yield return tail; - } - } - } - - /// - /// Trim Unit Text while Adjusting its Offset ... - /// - /// - /// - /// - private Unit TrimUnit( - string text, - int offset - ) - { - // - var start = 0; - while (start < text.Length && char.IsWhiteSpace(text[start])) - { - start++; - } - - // - var end = text.Length; - while (end > start && char.IsWhiteSpace(text[end - 1])) - { - end--; - } - - // - var result = new Unit(text.Substring(start, end - start), offset + start); - - // - return result; - } - - /// - /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ... - /// - /// - /// - /// - private IEnumerable HardSplit( - Unit unit, - int maxSize - ) - { - // - var text = unit.Text; - var position = 0; - - // - while (position < text.Length) - { - // - var remaining = text.Length - position; - if (remaining <= maxSize) - { - // - yield return TrimUnit(text.Substring(position), unit.Offset + position); - yield break; - } - - // - // Find Last Whitespace within Window ... - var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize); - if (cut <= position) - { - // - // No Whitespace -> Hard Cut ... - cut = position + maxSize; - } - - // - var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position); - if (!piece.Text.IsNullOrEmpty()) - { - yield return piece; - } - - // - position = cut; - while (position < text.Length && char.IsWhiteSpace(text[position])) - { - position++; - } - } - } - - /// - /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ... - /// - /// - /// - private List Accumulate(List units) - { - // - var result = new List(); - if (!units.HasChild()) - { - return result; - } - - // - var buffer = new StringBuilder(); - var buffered = new List(); - var bufferOffset = -1; - - // - foreach (var unit in units) - { - // - var separator = buffer.Length > 0 ? " " : string.Empty; - var projected = buffer.Length + separator.Length + unit.Text.Length; - - // - if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0) - { - // - // Close Current Chunk ... - var closed = buffer.ToString(); - result.Add(new Unit(closed, bufferOffset)); - - // - // Seed Next Chunk with Overlap Tail (only if Unit still Fits) ... - var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap); - var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize; - - // - buffer.Clear(); - if (!overlap.IsNullOrEmpty() && fits) - { - // - bufferOffset = ComputeOverlapOffset(buffered, overlap.Length); - buffer.Append(overlap); - separator = " "; - } - else - { - // - bufferOffset = -1; - separator = string.Empty; - } - - // - buffered.Clear(); - } - - // - if (bufferOffset < 0) - { - bufferOffset = unit.Offset; - } - - // - buffer.Append(separator).Append(unit.Text); - buffered.Add(unit); - } - - // - if (buffer.Length > 0) - { - result.Add(new Unit(buffer.ToString(), bufferOffset)); - } - - // - return result; - } - - /// - /// Map Trailing Overlap Length of Buffered Units back to Source Offset ... - /// Units Joined by Single Space Separator in Buffer ... - /// - /// - /// - /// - private int ComputeOverlapOffset( - List buffered, - int overlapLength - ) - { - // - var result = 0; - var remaining = overlapLength; - for (var i = buffered.Count - 1; i >= 0; i--) - { - // - var unit = buffered[i]; - if (remaining <= unit.Text.Length) - { - // - result = unit.Offset + unit.Text.Length - remaining; - return result; - } - - // - // Consume Unit and its Leading Separator ... - remaining -= unit.Text.Length + 1; - if (remaining <= 0) - { - // - result = unit.Offset; - return result; - } - } - - // - result = buffered.Count > 0 ? buffered[0].Offset : 0; - - // - return result; - } - - /// - /// Take Trailing Overlap from Text, Aligned to Word Boundary ... - /// - /// - /// - /// - private string TakeOverlap( - string text, - int overlap - ) - { - // - if (overlap <= 0 || text.Length <= overlap) - { - return string.Empty; - } - - // - var start = text.Length - overlap; - var boundary = text.IndexOfAny(WordBoundaries, start); - if (boundary < 0 || boundary >= text.Length - 1) - { - // - // No Boundary inside Window -> Skip Overlap ... - return string.Empty; - } - - // - return text.Substring(boundary + 1).Trim(); - } - - /// - /// Merge Chunks Smaller than MinChunkSize into their Predecessor ... - /// - /// - /// - private List MergeSmallChunks(List chunks) - { - // - if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2) - { - return chunks; - } - - // - var result = new List(); - foreach (var chunk in chunks) - { - // - if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0) - { - // - var previous = result[result.Count - 1]; - var merged = $"{previous.Text} {chunk.Text}"; - if (merged.Length <= configuration.TextChunker.ChunkSize) - { - result[result.Count - 1] = new Unit(merged, previous.Offset); - continue; - } - } - - // - result.Add(chunk); - } - - // - return result; - } - - /// - /// Characters Considered as Word Boundaries ... - /// - private readonly char[] WordBoundaries = [' ', '\n', '\t']; - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XAudioFileContentExtractor.cs - -using System; -using System.IO; -using FFMpegCore; -using System.Linq; -using Whisper.net; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts text content from Audio files ... - /// - public class XAudioFileContentExtractor : IXAudioFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "audio/mpeg", - "audio/mp3", - "audio/wav", - "audio/wave", - "audio/x-wav", - "audio/ogg", - "audio/m4a", - "audio/mp4", - "audio/aac", - "audio/x-m4a", - "audio/webm" - ]; - - private readonly XAiApiConfiguration configuration; - - public XAudioFileContentExtractor( - XAiApiConfiguration configuration - ) - { - // - if (configuration.Transcript.IsNullOrDefault() || - configuration.Transcript.ModelsPath.IsNullOrEmpty()) - { - XException.InvalidConfiguration.Throw(); - } - - // - this.configuration = configuration; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "audio", - mimeType, - cancellationToken - ); - - // - return result.AudioTranscript; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - memoryStream.Position = 0; - - // - using var wavStream = await ConvertToWavAsync( - mimeType: mimeType, - inputStream: memoryStream, - cancellationToken: cancellationToken - ); - - // - using var factory = WhisperFactory.FromPath(configuration.Transcript.ModelsPath); - using var processor = factory.CreateBuilder() - .WithLanguage(configuration.Transcript.Language) - .Build(); - - // - var segments = new System.Text.StringBuilder(); - await foreach (var segment in processor.ProcessAsync(wavStream, cancellationToken)) - { - segments.Append(segment.Text); - } - - // - result.AudioTranscript = segments.ToString().Trim(); - result.Text = result.AudioTranscript; - } - catch (Exception ex) - { - result.ErrorMessage = $"Audio extraction failed: {ex.Message}"; - } - - // - return result; - } - - // - #region Private ... - /// - /// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ... - /// - private async Task ConvertToWavAsync( - Stream inputStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var tempInput = Path.Combine( - Path.GetTempPath(), - $"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}" - ); - var tempOutput = Path.Combine( - Path.GetTempPath(), - $"audio_out_{Guid.NewGuid()}.wav" - ); - - // - MemoryStream result = null; - try - { - // - using var fs = File.Create(tempInput); - await inputStream.CopyToAsync(fs, cancellationToken); - await FFMpegArguments - .FromFileInput(tempInput) - .OutputToFile(tempOutput, overwrite: true, options => options - .WithAudioCodec("pcm_s16le") - .WithCustomArgument("-ar 16000") - .WithCustomArgument("-ac 1") - .ForceFormat("wav")) - .ProcessAsynchronously(); - - // - result = new(); - using var fsTmp = File.OpenRead(tempOutput); - await fsTmp.CopyToAsync(result, cancellationToken); - result.Position = 0; - } - catch - { - result = null; - } - finally - { - // - // Remove Temparory Files ... - if (File.Exists(tempInput)) File.Delete(tempInput); - if (File.Exists(tempOutput)) File.Delete(tempOutput); - } - - // - if (result.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - - /// - /// Retrieve File Extension based on mime type ... - /// - /// - /// - private string GetExtensionFromMime(string mimeType) - { - // - return mimeType?.ToLowerInvariant() switch - { - "audio/mpeg" or "audio/mp3" => ".mp3", - "audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a", - "audio/ogg" => ".ogg", - "audio/webm" => ".webm", - "audio/wav" or "audio/wave" or "audio/x-wav" => ".wav", - _ => ".tmp" - }; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XCodeFileContentExtractor.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Collections.Generic; -using xAiApi.Interfaces.Extractors; -using System.IO; -using System.Threading; -using xAiModels.Models; -using System.Text; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extractor for source code files ... - /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) - /// - public class XCodeFileContentExtractor : IXCodeFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/x-c", - "text/x-go", - "text/yaml", - "text/x-php", - "text/x-c++", - "text/x-sql", - "text/x-java", - "text/x-rust", - "text/x-ruby", - "text/x-csharp", - "text/x-python", - "text/javascript", - "text/typescript", - "text/x-java-source", - "application/x-yaml", - "application/x-csharp", - "application/x-python", - "application/javascript", - "application/typescript", - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - string.Empty, - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - // Read entire source code as UTF-8 (with BOM detection) ... - using var reader = new StreamReader( - fileStream, - Encoding.UTF8, - leaveOpen: false, - detectEncodingFromByteOrderMarks: true - ); - - // - var content = await reader.ReadToEndAsync(); - - // - // Normalize line endings for consistent downstream processing ... - content = content? - .Replace("\r\n", "\n") - .Replace("\r", "\n"); - - // - result.Text = content; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XDocxFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using xAiModels.Models; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; -using DocumentFormat.OpenXml.Drawing; -using DocumentFormat.OpenXml.Packaging; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts text content from DOCX files using DocumentFormat.OpenXml ... - /// - public class XDocxFileContentExtractor : IXDocxFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - memoryStream.Position = 0; - - // - var stringBuilder = new StringBuilder(); - - // - using (var wordDocument = WordprocessingDocument.Open(memoryStream, false)) - { - // - var body = wordDocument.MainDocumentPart?.Document?.Body; - if (body != null) - { - // - var paragraphs = body.Elements(); - foreach (var paragraph in paragraphs) - { - // - var text = paragraph.InnerText?.Trim(); - if (!string.IsNullOrEmpty(text)) - { - stringBuilder.AppendLine(text); - } - } - } - } - - // - return stringBuilder.ToString(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var content = await ExtractAsync( - mimeType: mimeType, - fileStream: fileStream, - cancellationToken: cancellationToken - ); - - // - var result = new XFileExtractionResult - { - Text = content, - FileName = fileName, - MimeType = mimeType - }; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XEpubFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Text; -using VersOne.Epub; -using HtmlAgilityPack; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extractor for EPUB electronic publication format - /// (application/epub+zip) - /// - public class XEpubFileContentExtractor : IXEpubFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/epub+zip" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "book.epub", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - result.Text = await ExtractEpubAsync( - fileStream, - cancellationToken - ); - } - catch (Exception ex) - { - // - result.ErrorMessage = - $"EPUB extraction failed: {ex.Message}"; - } - - // - return result; - } - - /// - /// Extract Epub Content ... - /// - /// - /// - /// - private async Task ExtractEpubAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - // Copy to MemoryStream (VersOne.Epub requires seekable stream) ... - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - // Load EPUB book ... - EpubBook book = await EpubReader.ReadBookAsync(ms); - var sb = new StringBuilder(); - - // - // Extract metadata ... - - // - if (!book.Title.IsNullOrEmpty()) - { - sb.AppendLine($"Title: {book.Title}"); - } - - // - if (!book.Author.IsNullOrEmpty()) - { - sb.AppendLine($"Author: {book.Author}"); - } - - // - sb.AppendLine(); - - // - // Extract chapters in reading order ... - var chapterIndex = 0; - foreach (var textContentFile in book.ReadingOrder) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - chapterIndex++; - sb.AppendLine($"[Chapter {chapterIndex}]"); - var plainText = ExtractTextFromHtml( - textContentFile.Content - ); - if (!plainText.IsNullOrEmpty()) - { - sb.AppendLine(plainText); - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - - /// - /// Extract Text Content from HTML ... - /// - /// - /// - private string ExtractTextFromHtml(string html) - { - // - var result = string.Empty; - - // - if (html.IsNullOrEmpty()) - { - return result; - } - - // - var htmlDocument = new HtmlDocument(); - htmlDocument.LoadHtml(html); - - // - var sb = new StringBuilder(); - var textNodes = htmlDocument.DocumentNode - .SelectNodes("//text()"); - - // - if (textNodes == null) - { - return result; - } - - // - foreach (var node in textNodes) - { - // - var text = node.InnerText?.Trim(); - if (!text.IsNullOrEmpty()) - { - sb.AppendLine(text); - } - } - - // - result = sb.ToString().TrimEnd(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XExcelFileContentExtractor.cs - -using System; -using System.IO; -using System.Data; -using System.Linq; -using System.Text; -using ExcelDataReader; -using System.Threading; -using xAiModels.Models; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - public class XExcelFileContentExtractor : IXExcelFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx - "application/vnd.ms-excel" // .xls - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - memoryStream.Position = 0; - - // - var stringBuilder = new StringBuilder(); - - // - using (var reader = ExcelReaderFactory.CreateReader(memoryStream)) - { - // - var result = reader.AsDataSet(); - foreach (DataTable table in result.Tables) - { - // - stringBuilder.AppendLine($"--- Sheet: {table.TableName} ---"); - - // - var headers = new string[table.Columns.Count]; - for (int i = 0; i < table.Columns.Count; i++) - { - headers[i] = table.Columns[i].ColumnName; - } - stringBuilder.AppendLine(string.Join(" | ", headers)); - stringBuilder.AppendLine(new string('-', 50)); - - // - foreach (DataRow row in table.Rows) - { - // - var rowValues = new string[row.ItemArray.Length]; - for (int i = 0; i < row.ItemArray.Length; i++) - { - rowValues[i] = row.ItemArray[i]?.ToString()?.Trim() ?? string.Empty; - } - stringBuilder.AppendLine(string.Join(" | ", rowValues)); - } - stringBuilder.AppendLine(); - } - } - - // - return stringBuilder.ToString(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var content = await ExtractAsync( - mimeType: mimeType, - fileStream: fileStream, - cancellationToken: cancellationToken - ); - - // - var result = new XFileExtractionResult - { - Text = content, - FileName = fileName, - MimeType = mimeType - }; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XFileContentExtractor.cs - -using System.IO; -using System.Linq; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Collections.Generic; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Composite extractor that delegates to appropriate extractor - /// based on MIME type ... - /// - public class XFileContentExtractor : IXFileContentExtractor - { - // - private readonly IList _extractors = []; - - public XFileContentExtractor( - IEnumerable availableExtractors - ) - { - // - _extractors = [.. availableExtractors - .Where(e => e.GetType() != typeof(XFileContentExtractor))]; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - /// - public bool CanExtract( - string mimeType, - string[] extractors = null - ) - { - // - return GetExtractors(extractors) - .Any(e => e.CanExtract(mimeType)); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ) - { - // - var extractor = GetExtractors(extractors) - .FirstOrDefault(e => e.CanExtract(mimeType)); - if (extractor.IsNull()) - { - // - XException.NotAllowed.Throw( - $"Unsupported file type: {mimeType}" - ); - } - - // - var result = await extractor - .ExtractAsync( - mimeType: mimeType, - fileStream: fileStream, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - string[] extractors = null, - CancellationToken cancellationToken = default - ) - { - // - var extractor = GetExtractors(extractors) - .FirstOrDefault(e => e.CanExtract(mimeType)); - if (extractor.IsNull()) - { - // - XException.NotAllowed.Throw( - $"Unsupported file type: {mimeType}" - ); - } - - // - var result = await extractor - .ExtractRichAsync( - mimeType: mimeType, - fileName: fileName, - fileStream: fileStream, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Extract Provided Extractors ... - /// - /// - /// - private IList GetExtractors(string[] extractors = null) - { - // - var result = new List(); - - // - if (extractors.IsNull() || !extractors.HasChild()) - { - // - result = [.. _extractors]; - } - else - { - // - result = [.. _extractors - .Where(e => extractors - .Any(ex => e.GetType().FullName.Contains(ex)))]; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XHtmlFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Text; -using HtmlAgilityPack; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extractor for HTML documents (text/html, application/xhtml+xml) - /// - public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/html", - "application/xhtml+xml" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.html", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - result.Text = await ExtractHtmlAsync( - fileStream, - cancellationToken - ); - } - catch (Exception ex) - { - result.ErrorMessage = - $"HTML extraction failed: {ex.Message}"; - } - - // - return result; - } - - /// - /// Extract Html Content as Text ... - /// - /// - /// - /// - private async Task ExtractHtmlAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // Load HTML into HtmlDocument - var html = new HtmlDocument(); - html.Load(fileStream); - - // Remove noise nodes (script, style, etc.) - RemoveNoiseNodes(html); - - // Extract title - var title = ExtractTitle(html); - - // Extract body text - var body = html.DocumentNode - .SelectSingleNode("//body"); - var bodyText = body?.InnerText ?? string.Empty; - - // Clean and normalize text - var cleanedText = CleanText(bodyText); - - // Build structured output - var sb = new StringBuilder(); - if (!string.IsNullOrWhiteSpace(title)) - { - sb.AppendLine($"Title: {title}"); - sb.AppendLine(); - } - sb.AppendLine(cleanedText); - - return sb.ToString().TrimEnd(); - } - - /// - /// Remove Noisy Nodes ... - /// - /// - private void RemoveNoiseNodes(HtmlDocument html) - { - // - // Remove script and style tags ... - var noiseTags = new[] { "script", "style", "noscript", "iframe" }; - foreach (var tag in noiseTags) - { - // - var nodes = html.DocumentNode - .Descendants(tag) - .ToList(); - foreach (var node in nodes) - { - node.Remove(); - } - } - } - - /// - /// Extract Title ... - /// - /// - /// - private string ExtractTitle(HtmlDocument html) - { - // - var titleNode = html.DocumentNode - .SelectSingleNode("//title"); - - // - var result = titleNode?.InnerText?.Trim() ?? string.Empty; - - // - return result; - } - - /// - /// Clean Text ... - /// - /// - /// - private string CleanText(string text) - { - // - var result = string.Empty; - - // - if (text.IsNullOrEmpty()) - { - result = string.Empty; - } - - // - // Decode HTML entities ... - text = System.Net.WebUtility.HtmlDecode(text); - - // - // Normalize whitespace ... - text = System.Text.RegularExpressions.Regex - .Replace(text, @"\s+", " ") - .Trim(); - - // - result = text; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XImageFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Threading; -using xAiModels.Models; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; -using xAiApi.Configurations; -using xCommons.Extensions; -using xExceptions.Constants; -using Tesseract; - -namespace xAiApi.Providers.Extractors -{ - public class XImageFileContentExtractor : IXImageFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "image/png", - "image/jpeg", - "image/jpg", - "image/gif", - "image/webp", - "image/bmp" - ]; - - /// - /// AI Api Configuration ... - /// - private readonly XAiApiConfiguration configuration; - - public XImageFileContentExtractor( - XAiApiConfiguration configuration - ) - { - // - if (configuration.IsNullOrDefault() || - configuration.OCR.IsNullOrDefault() || - configuration.OCR.DataPath.IsNullOrEmpty() || - configuration.OCR.DefaultLanguage.IsNullOrEmpty()) - { - XException.InvalidConfiguration.Throw(); - } - - // - this.configuration = configuration; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "image", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - var imageBytes = memoryStream.ToArray(); - - // - result.Images.Add(new XExtractedImage - { - Bytes = imageBytes, - MimeType = mimeType, - Description = $"Attached image: {fileName}" - }); - - // - // OCR Fallback ... - if (configuration.OCR.EnableOcrFallback) - { - // - try - { - // - var ocrText = await PerformOcrAsync(imageBytes, cancellationToken); - if (!string.IsNullOrWhiteSpace(ocrText)) - { - result.Text = ocrText; - } - } - catch - { - // OCR failed, but image is still available for Vision - } - } - - // - return result; - } - - /// - /// Do OCR on Image for Text Extraction ... - /// - private async Task PerformOcrAsync( - byte[] imageBytes, - CancellationToken cancellationToken - ) - { - // - return await Task.Run(() => - { - // - // Validate Path ... - if (!Directory.Exists(configuration.OCR.DataPath)) - { - // - throw new DirectoryNotFoundException( - $"TessData directory not found at: {configuration.OCR.DataPath}. " + - "Please download traineddata files from https://github.com/tesseract-ocr/tessdata" - ); - } - - // - using var engine = new TesseractEngine( - datapath: configuration.OCR.DataPath, - language: configuration.OCR.DefaultLanguage, - engineMode: configuration.OCR.EngineMode - ); - - // - using var pix = Pix.LoadFromMemory(imageBytes); - - // - cancellationToken.ThrowIfCancellationRequested(); - - // - using var page = engine.Process(pix); - - // - var text = page.GetText(); - - // - text = text?.Trim(); - - // - return text ?? string.Empty; - }, cancellationToken); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XOpenDocumentFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using System.Threading.Tasks; -using OfficeIMO.OpenDocument; -using System.Collections.Generic; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extractor for OpenDocument Format (ODF) documents - /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation) - /// - public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/vnd.oasis.opendocument.text", // .odt - "application/vnd.oasis.opendocument.spreadsheet", // .ods - "application/vnd.oasis.opendocument.presentation" // .odp - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.rtf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - if (IsOdt(mimeType)) - { - result.Text = await ExtractOdtAsync(fileStream, cancellationToken); - } - else if (IsOds(mimeType)) - { - result.Text = await ExtractOdsAsync(fileStream, cancellationToken); - } - else if (IsOdp(mimeType)) - { - result.Text = await ExtractOdpAsync(fileStream, cancellationToken); - } - else - { - result.ErrorMessage = - $"Unsupported OpenDocument MIME type: {mimeType}"; - } - } - catch (Exception ex) - { - // - result.ErrorMessage = - $"RTF extraction failed: {ex.Message}"; - } - - // - return result; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOdt(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.text"; - - // - return result; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOds(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet"; - - // - return result; - } - - /// - /// Check Mime Type ... - /// - /// - /// - private bool IsOdp(string mimeType) - { - // - var result = mimeType? - .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation"; - - // - return result; - } - - /// - /// Extract ODT File Content ... - /// - /// - /// - /// - private async Task ExtractOdtAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - var document = OdtDocument.Load(ms); - - // - var sb = new StringBuilder(); - foreach (var paragraph in document.Paragraphs) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - if (!paragraph.Text.IsNullOrEmpty()) - { - sb.AppendLine(paragraph.Text.Trim()); - } - } - - // - // 4. استخراج جداول - var tableIndex = 0; - foreach (var table in document.Tables) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - tableIndex++; - sb.AppendLine(); - sb.AppendLine($"[Table {tableIndex}]"); - - // - foreach (var row in table.Rows) - { - // - var cellTexts = new List(); - foreach (var cell in row.Cells) - { - // - var cellText = string.Join( - " ", - cell.Paragraphs - .Select(p => p.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)) - ); - cellTexts.Add(cellText); - } - - // - sb.AppendLine($" | {string.Join(" | ", cellTexts)} |"); - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - - /// - /// Extract ODS File Content ... - /// - /// - /// - /// - private async Task ExtractOdsAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - var document = OdsDocument.Load(ms); - var sb = new StringBuilder(); - var sheetIndex = 0; - foreach (var sheet in document.Sheets) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - sheetIndex++; - sb.AppendLine($"--- Sheet: {sheet.Name} ---"); - - // - for (long row = 0; row < sheet.RowCount; row++) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - var cellValues = new List(); - var columnCount = sheet.ColumnRuns.Sum(r => r.RepeatCount); - for (long col = 0; col < columnCount; col++) - { - // - var value = sheet.GetValue(row, col); - if (!value.IsNull()) - { - var text = value.LexicalValue?.Trim() ?? string.Empty; - cellValues.Add(text); - } - } - - // - if (cellValues.Any(v => !string.IsNullOrWhiteSpace(v))) - { - sb.AppendLine(string.Join(" | ", cellValues)); - } - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - - /// - /// Extract ODS File Content ... - /// - /// - /// - /// - private async Task ExtractOdpAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - var presentation = OdpPresentation.Load(ms); - var sb = new StringBuilder(); - var slideIndex = 0; - foreach (var slide in presentation.Slides) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - slideIndex++; - sb.AppendLine($"[Slide {slideIndex}]"); - var textParts = new List(); - - // - foreach (var shape in slide.Shapes) - { - // - if (shape is OdpTextBox textBox) - { - // - foreach (var paragraph in textBox.Paragraphs) - { - // - if (!paragraph.Text.IsNullOrEmpty()) - { - textParts.Add(paragraph.Text.Trim()); - } - } - } - else if (shape is OdpShape odpShape) - { - // - foreach (var paragraph in odpShape.TextParagraphs) - { - // - if (!paragraph.Text.IsNullOrEmpty()) - { - textParts.Add(paragraph.Text.Trim()); - } - } - } - } - - // - if (textParts.Count > 0) - { - // - sb.AppendLine("Content:"); - foreach (var text in textParts) - { - sb.AppendLine($" - {text}"); - } - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPdfFileContentExtractor.cs - -using System; -using System.IO; -using SkiaSharp; -using PDFtoImage; -using System.Linq; -using System.Text; -using System.Threading; -using xAiModels.Models; -using xAiApi.Configurations; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts content from PDF files using PdfPig ... - /// - public class XPdfFileContentExtractor : IXPdfFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "application/pdf" - ]; - - /// - /// Api Configuration ... - /// - private readonly XAiApiConfiguration configuration; - - public XPdfFileContentExtractor(XAiApiConfiguration configuration) - { - this.configuration = configuration; - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.pdf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - memoryStream.Position = 0; - - // - var extractedText = await ExtractTextAsync( - memoryStream, - cancellationToken - ); - if (IsTextSufficient(extractedText)) - { - // PDF متنی است - result.Text = extractedText; - } - else - { - // PDF اسکن‌شده است - Fallback به تصویر - memoryStream.Position = 0; - result = await FallbackToImageExtractionAsync( - memoryStream, - fileName, - mimeType, - cancellationToken - ); - result.UsedImageFallback = true; - } - - // - return result; - } - - /// - /// Extract Text From PDF Files using Common way ... - /// - /// - /// - /// - private async Task ExtractTextAsync( - Stream pdfStream, - CancellationToken cancellationToken - ) - { - // - var result = await Task.Run(() => - { - // - var sb = new StringBuilder(); - using var document = UglyToad.PdfPig.PdfDocument.Open(pdfStream); - foreach (var page in document.GetPages()) - { - // - var text = page.Text?.Trim(); - if (!string.IsNullOrEmpty(text)) - { - // - sb.AppendLine(text); - sb.AppendLine(); - } - } - - // - return sb.ToString(); - }, cancellationToken); - - // - return result; - } - - /// - /// Check Extracted Content is Sufficient or not ... - /// if not try to Falling Back using Images ... - /// - /// - /// - private bool IsTextSufficient(string text) - { - // - if (string.IsNullOrWhiteSpace(text)) - { - return false; - } - - // - // حذف فاصله‌ها و بررسی طول - var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray()); - - // - var result = cleanText.Length >= configuration.PDFToImageDescriptor.MinTextLengthThreshold; - - // - return result; - } - - /// - /// Fallback Converts PDF Pages to Images ... - /// - /// - /// - /// - /// - /// - private async Task FallbackToImageExtractionAsync( - Stream pdfStream, - string fileName, - string mimeType, - CancellationToken cancellationToken - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType, - UsedImageFallback = true - }; - - // - await Task.Run(() => - { - // - try - { - // - // Calculating With ... - var width = configuration.PDFToImageDescriptor.Width; - if (width >= 0 && configuration.PDFToImageDescriptor.MaxImageWidth > 0) - { - // - width = Math.Min( - width, - configuration.PDFToImageDescriptor.MaxImageWidth - ); - } - - // - // Preparing Render Options ... - var renderOptions = new RenderOptions - { - Width = width, - Dpi = configuration.PDFToImageDescriptor.Dpi, - Height = configuration.PDFToImageDescriptor.Height, - UseTiling = configuration.PDFToImageDescriptor.UseTiling, - WithFormFill = configuration.PDFToImageDescriptor.WithFormFill, - WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio, - WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations, - DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds, - }; - - // - // Preparing Images to Fallback ... - var pagesCount = Conversion.GetPageCount(pdfStream); - pdfStream.Position = 0; - - // - if (configuration.PDFToImageDescriptor.MaxPagesForImageFallback > 0) - { - // - pagesCount = Math.Min( - pagesCount, - configuration.PDFToImageDescriptor.MaxPagesForImageFallback - ); - } - - // - for (int pageIndex = 0; pageIndex < pagesCount; pageIndex++) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - try - { - // - var skBitmap = Conversion.ToImage( - page: pageIndex, - pdfStream: pdfStream, - options: renderOptions - ); - pdfStream.Position = 0; - - // - using (skBitmap) - using (var image = SKImage.FromBitmap(skBitmap)) - using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) - using (var ms = new MemoryStream()) - { - // - data.SaveTo(ms); - result.Images.Add(new XExtractedImage - { - Bytes = ms.ToArray(), - MimeType = "image/png", - Description = $"Page {pageIndex + 1}, rendered from {fileName}" - }); - } - } - catch { } - } - } - catch (Exception ex) - { - result.ErrorMessage = $"PDF image extraction failed: {ex.Message}"; - } - }, cancellationToken); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPlainTextFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Threading; -using xAiModels.Models; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts content from plain text files (txt, md, csv, json, xml) ... - /// - public class XPlainTextFileContentExtractor : IXPlainTextFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/plain", - "text/markdown", - "text/csv", - "text/xml", - "application/json", - "application/xml" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - using var reader = new StreamReader(fileStream); - return await reader.ReadToEndAsync(); - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var content = await ExtractAsync( - mimeType: mimeType, - fileStream: fileStream, - cancellationToken: cancellationToken - ); - - // - var result = new XFileExtractionResult - { - Text = content, - FileName = fileName, - MimeType = mimeType - }; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPowerPointFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using OfficeIMO.PowerPoint; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Collections.Generic; -using xAiApi.Interfaces.Extractors; -using DocumentFormat.OpenXml.Packaging; -using DrawingText = DocumentFormat.OpenXml.Drawing.Text; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts content from all PowerPoint formats - /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot) - /// - public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - // OpenXML Formats - "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx - "application/vnd.openxmlformats-officedocument.presentationml.slideshow", // .ppsx - "application/vnd.openxmlformats-officedocument.presentationml.template", // .potx - "application/vnd.ms-powerpoint.presentation.macroEnabled.12", // .pptm - "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", // .ppsm - "application/vnd.ms-powerpoint.template.macroEnabled.12", // .potm - // Legacy Binary Formats (.ppt / .pps / .pot share same MIME) - "application/vnd.ms-powerpoint" - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream: fileStream, - fileName: "presentation", - mimeType: mimeType, - cancellationToken: cancellationToken - ); - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - if (IsOpenXmlFormat(mimeType)) - { - // - result.Text = await ExtractOpenXmlAsync( - fileStream, - cancellationToken - ); - } - else if (IsLegacyFormat(mimeType)) - { - // - result.Text = await ExtractLegacyAsync( - fileStream, - cancellationToken - ); - } - else - { - // - result.ErrorMessage = - $"Unsupported PowerPoint MIME type: {mimeType}"; - } - } - catch (Exception ex) - { - result.ErrorMessage = - $"PowerPoint extraction failed: {ex.Message}"; - } - - // - return result; - } - - /// - /// Check Open XML Format ... - /// - /// - /// - private bool IsOpenXmlFormat(string mimeType) - { - // - var result = mimeType?.ToLowerInvariant() switch - { - "application/vnd.openxmlformats-officedocument.presentationml.presentation" => true, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true, - "application/vnd.openxmlformats-officedocument.presentationml.template" => true, - "application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true, - "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true, - "application/vnd.ms-powerpoint.template.macroEnabled.12" => true, - _ => false - }; - - // - return result; - } - - /// - /// Check Legacy Format ... - /// - /// - /// - private bool IsLegacyFormat(string mimeType) - { - // - var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint"; - return result; - } - - /// - /// Extract an Slide Title ... - /// - /// - /// - private string GetSlideTitle(SlidePart slidePart) - { - // - var result = string.Empty; - - // - // Title placeholder has specific type - var titleShape = slidePart.Slide - .Descendants() - .FirstOrDefault(s => s.NonVisualShapeProperties? - .NonVisualDrawingProperties? - .Name?.Value? - .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true - ); - if (titleShape != null) - { - // - var titleText = titleShape - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)); - result = string.Join(" ", titleText); - } - - // - return result; - } - - /// - /// Extract Speaker Notes ... - /// - /// - /// - private string GetSpeakerNotes(SlidePart slidePart) - { - // - var result = string.Empty; - - // - var notesSlidePart = slidePart.NotesSlidePart; - if (notesSlidePart?.NotesSlide == null) - { - return result; - } - - // - var notesTexts = notesSlidePart.NotesSlide - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)) - .ToList(); - - // - result = notesTexts.Count > 0 - ? string.Join(Environment.NewLine, notesTexts) - : null; - - // - return result; - } - - /// - /// Extract OpenXML Tables ... - /// - /// - /// - private static string ExtractOpenXmlTables(SlidePart slidePart) - { - // - var sb = new StringBuilder(); - - // - var tableElements = slidePart.Slide - .Descendants(); - - // - var tableIndex = 0; - foreach (var table in tableElements) - { - // - tableIndex++; - sb.AppendLine($" Table {tableIndex}:"); - - // - foreach (var row in table - .Descendants()) - { - // - var cells = row - .Descendants() - .Select(c => string.Join(" ", c - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t)))) - .ToList(); - - // - if (cells.Count > 0) - { - sb.AppendLine($" | {string.Join(" | ", cells)} |"); - } - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString(); - - // - return result; - } - - /// - /// Extract Open XML Format ... - /// - /// - /// - /// - private async Task ExtractOpenXmlAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - var sb = new StringBuilder(); - - // - // Copy to MemoryStream (OpenXml requires seekable stream) - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - using var presentationDocument = PresentationDocument.Open(ms, false); - var presentationPart = presentationDocument.PresentationPart; - if (presentationPart == null) - { - XException.InvalidData.Throw(); - } - - // - var slideParts = presentationPart.SlideParts.ToList(); - var slideIndex = 0; - foreach (var slidePart in slideParts) - { - // - if (cancellationToken.IsCancellationRequested) break; - slideIndex++; - - // - sb.AppendLine($"[Slide {slideIndex}]"); - - // - // 1. Extract slide title - var slideTitle = GetSlideTitle(slidePart); - if (!string.IsNullOrWhiteSpace(slideTitle)) - { - sb.AppendLine($"Title: {slideTitle}"); - } - - // - // 2. Extract body texts - var bodyTexts = slidePart.Slide - .Descendants() - .Select(t => t.Text?.Trim()) - .Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle) - .ToList(); - if (bodyTexts.Count > 0) - { - // - sb.AppendLine("Content:"); - foreach (var text in bodyTexts) - { - sb.AppendLine($" - {text}"); - } - } - - // - // 3. Extract tables - var tables = ExtractOpenXmlTables(slidePart); - if (!string.IsNullOrWhiteSpace(tables)) - { - // - sb.AppendLine("[Tables]"); - sb.AppendLine(tables); - } - - // - // 4. Extract speaker notes - var notes = GetSpeakerNotes(slidePart); - if (!string.IsNullOrWhiteSpace(notes)) - { - // - sb.AppendLine("[Speaker Notes]"); - sb.AppendLine(notes); - } - - // - // 5. Image count metadata - var imageCount = slidePart.ImageParts?.Count() ?? 0; - if (imageCount > 0) - { - sb.AppendLine($"[Images: {imageCount}]"); - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - - /// - /// Extract Legacy Format ... - /// - /// - /// - /// - private async Task ExtractLegacyAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - var sb = new StringBuilder(); - - // - await using var ms = new MemoryStream(); - await fileStream.CopyToAsync(ms, cancellationToken); - ms.Position = 0; - - // - using var presentation = PowerPointPresentation.Load(ms); - var slideIndex = 0; - foreach (var slide in presentation.Slides) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - slideIndex++; - - // - sb.AppendLine($"[Slide {slideIndex}]"); - - // - var textParts = new List(); - var imageCount = 0; - foreach (var shape in slide.Shapes) - { - // - if (shape is PowerPointTextBox textBox) - { - // - if (!textBox.Text.IsNullOrEmpty()) - { - textParts.Add(textBox.Text.Trim()); - } - } - else if (shape is PowerPointAutoShape autoShape) - { - // - if (!autoShape.AltText.IsNullOrEmpty()) - { - textParts.Add(autoShape.AltText.Trim()); - } - } - else if (shape is PowerPointPicture picture) - { - imageCount++; - } - } - - // - if (textParts.Count > 0) - { - // - sb.AppendLine("Content:"); - foreach (var text in textParts) - { - sb.AppendLine($" - {text}"); - } - } - - // - if (imageCount > 0) - { - sb.AppendLine($"[Images: {imageCount}]"); - } - - // - sb.AppendLine(); - } - - // - var result = sb.ToString().TrimEnd(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XRtfFileContentExtractor.cs - -using System; -using RtfPipe; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using System.Threading.Tasks; -using xAiApi.Interfaces.Extractors; -using System.Text.RegularExpressions; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extractor for Rich Text Format (RTF) documents - /// (application/rtf, text/rtf) - /// - public class XRtfFileContentExtractor : IXRtfFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "text/rtf", - "application/rtf", - ]; - - /// - /// Check if this extractor supports the specified MIME type ... - /// - /// - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - /// - /// - /// - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractRichAsync( - fileStream, - "document.rtf", - mimeType, - cancellationToken - ); - - // - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - result.Text = await ExtractRtfAsync( - fileStream, - cancellationToken - ); - } - catch (Exception ex) - { - // - result.ErrorMessage = - $"RTF extraction failed: {ex.Message}"; - } - - // - return result; - } - - /// - /// Extract RTF Content ... - /// - /// - /// - /// - private async Task ExtractRtfAsync( - Stream fileStream, - CancellationToken cancellationToken - ) - { - // - var result = string.Empty; - - // - // Read RTF content as string ... - using var reader = new StreamReader( - fileStream, - Encoding.UTF8, - detectEncodingFromByteOrderMarks: true, - leaveOpen: true - ); - var rtfContent = await reader.ReadToEndAsync(); - if (rtfContent.IsNullOrEmpty()) - { - result = string.Empty; - } - - // - // Convert RTF to HTML using RtfPipe ... - var html = Rtf.ToHtml(rtfContent); - - // - // Convert HTML to plain text ... - result = HtmlToPlainText(html); - - // - return result; - } - - /// - /// Converts Html to Text ... - /// - /// - /// - private string HtmlToPlainText(string html) - { - // - var result = string.Empty; - - // - if (html.IsNullOrEmpty()) - { - result = string.Empty; - } - - // - // Remove HTML tags ... - result = Regex.Replace( - html, - "<.*?>", - string.Empty, - RegexOptions.Singleline - ); - - // - // Decode HTML entities ... - result = System.Net.WebUtility.HtmlDecode(result); - - // - // Normalize whitespace ... - result = Regex.Replace(result, @"\s+", " ").Trim(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XVisionFileContentExtractor.cs - -using System; -using System.IO; -using System.Linq; -using System.Threading; -using xAiApi.Constants; -using xAiModels.Models; -using xAiApi.Extensions; -using xAiApi.Interfaces; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiApi.Configurations; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; -using System.Collections.Generic; -using xAiApi.Interfaces.Extractors; -using System.Runtime.CompilerServices; - -namespace xAiApi.Providers.Extractors -{ - /// - /// Extracts content from files using Vision Model ... - /// - public class XVisionFileContentExtractor : IXVisionFileContentExtractor - { - /// - /// Supported MIME Types ... - /// - private static readonly string[] SupportedMimeTypes = - [ - "image/png", - "image/jpeg", - "image/jpg", - "image/webp", - "image/bmp", - "application/pdf", - ]; - - // - private readonly string prompt; - private readonly XAiModelDescriptor descriptor; - - public XVisionFileContentExtractor( - XAiApiConfiguration configuration, - string promptName = XAiApiConstants.XAiApiContentExtractionPromptName, - string modelName = XAiApiConstants.XAiDefaultVisionModelName - ) - { - // - // Retrieve Descriptoir ... - if (modelName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - descriptor = configuration.GetModel(modelName); - - // - // Retrieve Extraction Prompt ... - if (promptName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - prompt = configuration.GetPrompt( - name: promptName, - @params: null - ); - - // - // Validate Requirements ... - if (prompt.IsNullOrEmpty() || descriptor.IsNullOrDefault()) - { - XException.InvalidData.Throw(); - } - } - - /// - /// Check if this extractor supports the specified MIME type ... - /// - public bool CanExtract(string mimeType) - { - // - return SupportedMimeTypes.Contains( - mimeType?.ToLowerInvariant() ?? string.Empty - ); - } - - /// - /// Extract text content from file stream ... - /// - public async Task ExtractAsync( - Stream fileStream, - string mimeType, - CancellationToken cancellationToken = default - ) - { - var result = await ExtractRichAsync(fileStream, "file", mimeType, cancellationToken); - return result.Text; - } - - /// - /// Extract content from stream as Rich Result ... - /// - /// - /// - /// - /// - /// - public async Task ExtractRichAsync( - Stream fileStream, - string fileName, - string mimeType, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileExtractionResult - { - FileName = fileName, - MimeType = mimeType - }; - - // - try - { - // - using var memoryStream = new MemoryStream(); - await fileStream.CopyToAsync(memoryStream, cancellationToken); - var imageBytes = memoryStream.ToArray(); - var messages = new[] - { - // - new ChatMessage(ChatRole.User, new[] - { - new DataContent(imageBytes, mimeType) - }) - }; - - // - var extractedContent = await RequestOCRAsync( - messages: messages, - cancellationToken: cancellationToken - ); - if (!extractedContent.IsNullOrEmpty()) - { - result.Text = extractedContent.Trim(); - } - else - { - result.ErrorMessage = "there is not any Extracted Content ..."; - } - } - catch (Exception ex) - { - result.ErrorMessage = $"Error in Vision Extraction: {ex.Message} ..."; - } - - // - return result; - } - - // - #region OCR ... - /// - /// Request for Doing OCR on Given Data Contents ... - /// - /// - /// - /// - public virtual async Task RequestOCRAsync( - IList messages, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!messages.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = descriptor.GetClient(); - - // - // Preparing Extraction Prompt Message ... - var pMessage = new ChatMessage( - ChatRole.System, - prompt - ); - - // - messages = [pMessage, .. messages]; - - // - var response = await client.GetResponseAsync( - messages: messages, - cancellationToken: cancellationToken - ); - - // - // Validate Response ... - if (!response.IsValid()) - { - // - // Dispose Client ... - client.Dispose(); - XException.ActionFailed.Throw(); - } - - // - // Retrieve Response Text ... - var result = response.Text; - - // - return result; - } - - /// - /// Request for Doing OCR on Given Data Contents as Stream ... - /// - /// - /// - /// - public virtual async IAsyncEnumerable RequestOCRAsEnumerable( - IList messages, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!messages.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - using var client = descriptor.GetClient(); - - // - // Preparing Extraction Prompt Message ... - var pMessage = new ChatMessage( - ChatRole.System, - prompt - ); - - // - messages = [pMessage, .. messages]; - - // - var enumerable = client.GetStreamingResponseAsync( - options: null, - messages: messages - ); - - // - await foreach (var res in enumerable) - { - // - // Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return res.Text; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_093cc96f-7927-40f4-a61b-2cc948412f09.html - - - - - - -ثبت XAiMcpServer به عنوان Entity و مدیریت داینامیک | مستند فنی - - - - -
- -
-
-
-
-
شماره مستند: ARCH-MCP-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: آبان ۱۴۰۵
-
طبقه‌بندی: فنی-داخلی
-
-
-
- TECHNICAL DESIGN DOCUMENT -

ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک

-

Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager

-
-
- -
- -
- هدف مستند:
- این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول xAiModels، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از appSettings، کنترلرهای CRUD، و اتصال به XMcpServerConnectionManager را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند XAiProject و XAiConversation) پیاده‌سازی می‌شوند. -
- - - - -
-
-
۰
-
-

نمای کلی معماری و جریان داده

-
Architecture Overview
-
-
-
-

جریان کلی سیستم به این شکل خواهد بود:

- -
-┌─────────────────────────────────────────────────────────────────┐
-│  appsettings.json → "McpServers:Servers[]"                      │
-│         │                                                        │
-│         ▼                                                        │
-│  XMcpServerSeederService (IHostedService)                       │
-│         │   (در Startup اجرا می‌شود)                              │
-│         ▼                                                        │
-│  IXAiMcpServerRepositoryService → AddAsync/UpdateAsync           │
-│         │                                                        │
-│         ▼                                                        │
-│  [AiMcpServers] Table (SQL/Mongo/InMemory)                      │
-│         │                                                        │
-│         ├──→ McpServersController (CRUD API)                    │
-│         │         │                                              │
-│         │         ▼                                              │
-│         │    XMcpServerConnectionManager.RefreshAsync()          │
-│         │                                                        │
-│         ▼                                                        │
-│  XMcpServerConnectionManager                                    │
-│         │   (Ping + ListTools + Cache)                          │
-│         ▼                                                        │
-│  ChatOptions.Tools → IXDefaultAiService                         │
-└─────────────────────────────────────────────────────────────────┘
-
- -
- 💡 نکته کلیدی: appSettings فقط نقش Seed اولیه را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به appSettings اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر UpdateExisting = true باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند. -
- -

ساختار فایل‌های جدید/تغییر یافته:

-
-xSaherelmWorkspace/ -├── Modules/xAiModels/ -│ ├── Models/ -│ │ ├── Entities/ -│ │ │ └── XAiMcpServer.cs [NEW] -│ │ │ ├── Dtos/ -│ │ │ │ └── XAiMcpServerDto.cs [NEW] -│ │ │ └── XMcpServerDescriptor.cs [NEW] -│ │ ├── Configurations/ -│ │ │ ├── XAiModelMappersProfile.cs [MODIFY] -│ │ │ └── Entities/ -│ │ │ └── XAiMcpServerEntityConfiguration.cs [NEW] -│ │ ├── Constants/XAiModelsConstants.cs [MODIFY] -│ │ ├── Interfaces/ -│ │ │ ├── Entities/ -│ │ │ │ ├── IXAiMcpServerKeyGenerator.cs -│ │ │ │ ├── IXAiMcpServerRepository.cs -│ │ │ │ ├── IXAiMcpServerRepositoryEvents.cs -│ │ │ │ ├── IXAiMcpServerRepositoryProvider.cs -│ │ │ │ └── IXAiMcpServerEntityHub.cs -│ │ │ ├── Dtos/ -│ │ │ │ ├── IXAiMcpServerDtoHub.cs -│ │ │ │ ├── IXAiMcpServerRepositoryService.cs -│ │ │ │ └── IXAiMcpServerServiceProvider.cs -│ │ │ └── Enrichers/ -│ │ │ └── IXAiMcpServerEnricher.cs -│ │ ├── Providers/ -│ │ │ ├── Entities/ -│ │ │ │ ├── XAiMcpServerEFRepository.cs -│ │ │ │ ├── XAiMcpServerInMemoryRepository.cs -│ │ │ │ ├── XAiMcpServerMongoRepository.cs -│ │ │ │ ├── XAiMcpServerKeyGenerator.cs -│ │ │ │ ├── XAiMcpServerRepositoryEvents.cs -│ │ │ │ ├── XAiMcpServerEntityHub.cs -│ │ │ │ ├── XAiMcpServerRepositoryProvider.cs -│ │ │ │ └── XAiMcpServerSeederBase.cs -│ │ │ ├── Dtos/ -│ │ │ │ ├── XAiMcpServerDtoHub.cs -│ │ │ │ ├── XAiMcpServerRepositoryService.cs -│ │ │ │ └── XAiMcpServerServiceProvider.cs -│ │ │ ├── Enrichers/ -│ │ │ │ └── XAiMcpServerEnricher.cs -│ │ │ └── XAiMcpServerEntityRegisterar.cs -│ │ ├── Helpers/XAiModelsHelper.cs [MODIFY] -│ │ └── DI/XDIHelperExtension.cs [MODIFY] -│ │ -├── xAiApi/ -│ ├── Configurations/ -│ │ └── XMcpServersConfiguration.cs [NEW] -│ ├── Services/ -│ │ ├── XMcpServerSeederService.cs [NEW] -│ │ └── XMcpServerConnectionManager.cs [MODIFY] -│ ├── Controllers/ -│ │ └── McpServersController.cs [NEW] -│ ├── Database/XAiApiDbContext.cs [MODIFY] -│ ├── Startup.cs [MODIFY] -│ └── appsettings.json [MODIFY] -
-
-
- - - - -
-
-
۱
-
-

تعریف Entity در xAiModels

-
Entity Layer / Models/Entities/XAiMcpServer.cs
-
-
-
-

ابتدا موجودیت اصلی را با الگوبرداری دقیق از XAiProject و XAiVector تعریف می‌کنیم. فیلدهای JSON (مانند Arguments، Headers، EnvironmentVariables) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.

- -
xAiModels/Models/Entities/XAiMcpServer.cs
-
using System;
-using xModels.Base;
-using System.ComponentModel.DataAnnotations;
-
-namespace xAiModels.Models.Entities
-{
-    /// <summary>
-    /// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
-    /// </summary>
-    public class XAiMcpServer : XBaseGuidIDEntity
-    {
-        /// <summary>
-        /// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
-        /// </summary>
-        [Required]
-        [StringLength(255)]
-        public string OwnerId { get; set; }
-
-        /// <summary>
-        /// نام یکتای سرور (برای هر Owner) ...
-        /// </summary>
-        [Required]
-        [StringLength(255)]
-        public string Name { get; set; }
-
-        /// <summary>
-        /// توضیحات ...
-        /// </summary>
-        [StringLength(1000)]
-        public string Description { get; set; }
-
-        /// <summary>
-        /// فعال/غیرفعال ...
-        /// </summary>
-        public bool Enabled { get; set; } = true;
-
-        /// <summary>
-        /// نوع Transport: "stdio" یا "http" ...
-        /// </summary>
-        [Required]
-        [StringLength(50)]
-        public string Transport { get; set; } = "stdio";
-
-        // --- تنظیمات Stdio ---
-        [StringLength(500)]
-        public string Command { get; set; }
-
-        /// <summary>
-        /// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
-        /// </summary>
-        public string Arguments { get; set; }
-
-        [StringLength(1000)]
-        public string WorkingDirectory { get; set; }
-
-        /// <summary>
-        /// متغیرهای محیطی به‌صورت JSON Object ...
-        /// </summary>
-        public string EnvironmentVariables { get; set; }
-
-        // --- تنظیمات HTTP ---
-        [StringLength(1000)]
-        public string Endpoint { get; set; }
-
-        /// <summary>
-        /// هدرهای HTTP به‌صورت JSON Object ...
-        /// </summary>
-        public string Headers { get; set; }
-
-        /// <summary>
-        /// مهلت اتصال و اعتبارسنجی (ثانیه) ...
-        /// </summary>
-        public int TimeoutSeconds { get; set; } = 30;
-
-        // --- Audit ---
-        public DateTime CreatedOn { get; set; }
-        public DateTime UpdatedAt { get; set; }
-    }
-}
- -
xAiModels/Models/Dtos/XAiMcpServerDto.cs
-
using System;
-using xModels.Base;
-using xModels.Dtos;
-
-namespace xAiModels.Models.Dtos
-{
-    public class XAiMcpServerDto : XBaseGuidIDEntityDto
-    {
-        public string OwnerId { get; set; }
-        public virtual XPersonDto Owner { get; set; } = null;
-
-        public string Name { get; set; }
-        public string Description { get; set; }
-        public bool Enabled { get; set; }
-        public string Transport { get; set; }
-
-        public string Command { get; set; }
-        public string Arguments { get; set; }
-        public string WorkingDirectory { get; set; }
-        public string EnvironmentVariables { get; set; }
-
-        public string Endpoint { get; set; }
-        public string Headers { get; set; }
-
-        public int TimeoutSeconds { get; set; }
-
-        public DateTime CreatedOn { get; set; }
-        public DateTime UpdatedAt { get; set; }
-    }
-}
- -
xAiModels/Models/XMcpServerDescriptor.cs
-
using System.Collections.Generic;
-
-namespace xAiModels.Models
-{
-    /// <summary>
-    /// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
-    /// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
-    /// </summary>
-    public class XMcpServerDescriptor
-    {
-        public string Name { get; set; }
-        public string Description { get; set; }
-        public bool Enabled { get; set; } = true;
-        public string Transport { get; set; } = "stdio";
-        public int TimeoutSeconds { get; set; } = 30;
-
-        // Stdio
-        public string Command { get; set; }
-        public List<string> Arguments { get; set; } = new();
-        public string WorkingDirectory { get; set; }
-        public Dictionary<string, string> EnvironmentVariables { get; set; }
-
-        // HTTP
-        public string Endpoint { get; set; }
-        public Dictionary<string, string> Headers { get; set; }
-    }
-}
-
-
- - - - -
-
-
۲
-
-

ثابت‌ها و Configuration

-
Constants / EntityConfiguration
-
-
-
-

ثابت‌های جدید را به XAiModelsConstants اضافه کنید (دقیقاً مطابق الگوی موجود):

- -
xAiModels/Constants/XAiModelsConstants.cs (MODIFY)
-
// ── اضافه کنید در struct XAiModelsConstants ──
-
-// Table Mapping
-public const string XAiMcpServerTable = "AiMcpServers";
-
-// GraphQL Collection Mappings
-public const string XAiMcpServerSingleName = "aiMcpServer";
-public const string XAiMcpServerCollectionName = "aiMcpServers";
-
-// Hubs
-public const string XAiMcpServerDtoHub = "aiMcpServerDto";
-public const string XAiMcpServerEntityHub = "aiMcpServerEntity";
-
-// EF Repositories Helper Extensions
-public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor";
- -
xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs
-
using System;
-using xAiModels.Constants;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.EntityFrameworkCore.Metadata.Builders;
-
-namespace xAiModels.Configurations.Entities
-{
-    public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration<XAiMcpServer, Guid>
-    {
-        public override void Configure(EntityTypeBuilder<XAiMcpServer> builder)
-        {
-            builder.ToTable(XAiModelsConstants.XAiMcpServerTable);
-
-            // نام برای هر Owner یکتاست
-            builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
-        }
-    }
-}
- -
xAiModels/Providers/XAiMcpServerEntityRegisterar.cs
-
using System;
-using xDataService.Providers;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-using Microsoft.EntityFrameworkCore;
-using xAiModels.Configurations.Entities;
-
-namespace xAiModels.Providers
-{
-    public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
-    {
-        public XAiMcpServerEntityRegisterar()
-        : base(nameof(XAiMcpServerEntityRegisterar))
-        {
-            AddEntity<XAiMcpServer, Guid>();
-        }
-
-        public override void ConfigureEntities(ModelBuilder modelBuilder)
-        {
-            modelBuilder
-                .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);
-
-            base.ConfigureEntities(modelBuilder);
-        }
-    }
-}
-
-
- - - - -
-
-
۳
-
-

لایه Interfaces

-
Interfaces / Entities + Dtos + Enrichers
-
-
-
-

مطابق الگوی XAiProject، تمام اینترفیس‌های مربوطه را در سه پوشه Entities، Dtos و Enrichers ایجاد کنید:

- -

الف) Interfaces/Entities

- -
xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs
-
using System;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerKeyGenerator : IXKeyGenerator<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs
-
using System;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepository : IXBaseRepository<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs
-
using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents<XAiMcpServer> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs
-
using System;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerEntityHub : IXBaseEntityHub<XAiMcpServer, Guid> { }
-}
- -
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs
-
using System;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-using xAiModels.Providers.Entities;
-
-namespace xAiModels.Interfaces.Entities
-{
-    public interface IXAiMcpServerRepositoryProvider
-        : IXBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub> { }
-}
- -

ب) Interfaces/Dtos

- -
xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs
-
using System;
-using xAiModels.Models.Dtos;
-using xPushService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerDtoHub
-        : IXBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid> { }
-}
- -
xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs
-
using System;
-using System.Threading;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerRepositoryService
-        : IXBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>
-    {
-        /// <summary>
-        /// یافتن سرور بر اساس OwnerId و Name ...
-        /// </summary>
-        Task<XAiMcpServerDto> FindByNameAsync(
-            string ownerId,
-            string name,
-            CancellationToken cancellationToken = default
-        );
-    }
-}
- -
xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs
-
using System;
-using xAiModels.Models.Dtos;
-using xPushService.Interfaces;
-using xAiModels.Providers.Dtos;
-using xAiModels.Models.Entities;
-
-namespace xAiModels.Interfaces.Dtos
-{
-    public interface IXAiMcpServerServiceProvider
-        : IXBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub> { }
-}
- -

ج) Interfaces/Enrichers

- -
xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs
-
using System.Threading;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xAiModels.Models.Entities;
-using System.Collections.Generic;
-
-namespace xAiModels.Interfaces.Enrichers
-{
-    public interface IXAiMcpServerEnricher
-    {
-        Task<XAiMcpServerDto> Enrich(
-            XAiMcpServer source,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<XAiMcpServerDto> Enrich(
-            XAiMcpServerDto source,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServer> sources,
-            CancellationToken cancellationToken = default
-        );
-
-        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServerDto> sources,
-            CancellationToken cancellationToken = default
-        );
-    }
-}
-
-
- - - - -
-
-
۴
-
-

لایه Repository

-
EF / Mongo / InMemory + KeyGenerator + Events + Hubs
-
-
-
-

سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با XAiProjectEFRepository و XAiProjectMongoRepository بسازید:

- -
xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs
-
using System;
-using xDataService.Db;
-using xDataService.Providers;
-using xDataService.Interfaces;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerEFRepository<TContext>
-        : XBaseEFRepository<XAiMcpServer, Guid, TContext>, IXAiMcpServerRepository
-        where TContext : XDbContext
-    {
-        public XAiMcpServerEFRepository(
-            IXUnitOfWorks<TContext> unitOfWorks,
-            XDataServiceConfiguration configuration,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs
-
using System;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerMongoRepository
-        : XBaseMongoRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
-    {
-        public XAiMcpServerMongoRepository(
-            XDataBaseConfiguration dbConfiguration,
-            XDataServiceConfiguration configuration,
-            string collectionName = null,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs
-
using System;
-using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerInMemoryRepository
-        : XBaseInMemoryRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
-    {
-        public XAiMcpServerInMemoryRepository(
-            XDataServiceConfiguration configuration,
-            IXAiMcpServerKeyGenerator keyGenerator = null,
-            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
-        ) : base(configuration, keyGenerator, baseRepositoryEvents) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs
-
using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerKeyGenerator
-        : XGuidKeyGenerator<XAiMcpServer>, IXAiMcpServerKeyGenerator { }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs
-
using xDataService.Providers;
-using xAiModels.Models.Entities;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerRepositoryEvents
-        : XBaseRepositoryEvents<XAiMcpServer>, IXAiMcpServerRepositoryEvents { }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Entities;
-using Microsoft.Extensions.Logging;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerEntityHub
-        : XBaseEntityHub<XAiMcpServer, Guid>, IXAiMcpServerEntityHub
-    {
-        public XAiMcpServerEntityHub(ILogger<XAiMcpServerEntityHub> logger)
-            : base(logger) { }
-    }
-}
- -
xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xIdentityService.Interfaces;
-using Microsoft.AspNetCore.SignalR;
-using xAiModels.Interfaces.Entities;
-
-namespace xAiModels.Providers.Entities
-{
-    public class XAiMcpServerRepositoryProvider
-        : XBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub>, IXAiMcpServerRepositoryProvider
-    {
-        public XAiMcpServerRepositoryProvider(
-            IHubContext<XAiMcpServerEntityHub> hub,
-            IXAiMcpServerRepository repository,
-            XDataServiceConfiguration dataConfiguration,
-            IXIdentityProvider identityProvider = null
-        ) : base(hub, repository, dataConfiguration, identityProvider) { }
-    }
-}
-
-
- - - - -
-
-
۵
-
-

لایه Service (RepositoryService + ServiceProvider + Enricher)

-
Providers/Dtos + Enrichers
-
-
-
-
xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)
-
// ── درون سازنده XAiModelMappersProfile اضافه کنید ──
-
-// XAiMcpServer
-CreateMap<XAiMcpServer, XAiMcpServerDto>();
-CreateMap<XAiMcpServerDto, XAiMcpServer>();
- -
xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs
-
using System.Linq;
-using xModels.Dtos;
-using System.Threading;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xAiModels.Models.Entities;
-using System.Collections.Generic;
-using xIdentityService.Interfaces;
-using xIdentityService.Extensions;
-using xAiModels.Interfaces.Enrichers;
-
-namespace xAiModels.Providers.Enrichers
-{
-    public class XAiMcpServerEnricher : IXAiMcpServerEnricher
-    {
-        private readonly IXIdentityProvider identityProvider;
-
-        public XAiMcpServerEnricher(IXIdentityProvider identityProvider)
-        {
-            this.identityProvider = identityProvider;
-        }
-
-        public virtual async Task<XAiMcpServerDto> Enrich(
-            XAiMcpServer source,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServer>();
-            result = await Enrich(source: result, cancellationToken: cancellationToken);
-            return result;
-        }
-
-        public virtual async Task<XAiMcpServerDto> Enrich(
-            XAiMcpServerDto source,
-            CancellationToken cancellationToken = default
-        )
-        {
-            XPersonDto owner = null;
-            if (!source.OwnerId.IsNullOrEmpty())
-            {
-                var device = identityProvider.GetDevice();
-                var userInfo = await identityProvider.GetUserInfo(
-                    device: device,
-                    userSelectByParam: source.OwnerId
-                );
-                owner = userInfo.ToXPersonDto();
-            }
-
-            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServerDto>();
-            result.Owner = owner;
-            return result;
-        }
-
-        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServer> sources,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var tasks = sources.Select(x => Enrich(x, cancellationToken));
-            return await Task.WhenAll(tasks);
-        }
-
-        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
-            IEnumerable<XAiMcpServerDto> sources,
-            CancellationToken cancellationToken = default
-        )
-        {
-            var tasks = sources.Select(x => Enrich(x, cancellationToken));
-            return await Task.WhenAll(tasks);
-        }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs
-
using System;
-using System.Linq;
-using System.Threading;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Threading.Tasks;
-using xDataService.Providers;
-using xAiModels.Configurations;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Interfaces.Entities;
-using xAiModels.Interfaces.Enrichers;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerRepositoryService
-        : XBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerRepositoryService
-    {
-        private readonly IXAiMcpServerEnricher enricher;
-        private readonly IXAiMcpServerRepository repository;
-
-        public XAiMcpServerRepositoryService(
-            IXAiMcpServerRepository repository,
-            IXAiMcpServerEnricher enricher
-        ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()])
-        {
-            this.enricher = enricher;
-            this.repository = repository;
-        }
-
-        /// <summary>
-        /// یافتن سرور بر اساس OwnerId و Name ...
-        /// </summary>
-        public virtual async Task<XAiMcpServerDto> FindByNameAsync(
-            string ownerId,
-            string name,
-            CancellationToken cancellationToken = default
-        )
-        {
-            // اعتبارسنجی ورودی‌ها
-            if (ownerId.IsNullOrEmpty() || name.IsNullOrEmpty())
-                return null;
-
-            // جستجو در Repository
-            var entity = await repository.FindOneAsync(
-                includeBuilder: null,
-                ignoreSoftDeleteds: true,
-                cancellationToken: cancellationToken,
-                predicate: x => x.OwnerId == ownerId && x.Name == name
-            );
-
-            // عدم یافتن → null
-            if (entity.IsNullOrDefault())
-                return null;
-
-            // Enrich و بازگشت
-            return await enricher.Enrich(source: entity, cancellationToken: cancellationToken);
-        }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Dtos;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Models.Entities;
-using Microsoft.Extensions.Logging;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerDtoHub
-        : XBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerDtoHub
-    {
-        public XAiMcpServerDtoHub(ILogger<XAiMcpServerDtoHub> logger)
-            : base(logger) { }
-    }
-}
- -
xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs
-
using System;
-using xPushService.Base;
-using xAiModels.Models.Dtos;
-using xAiModels.Interfaces.Dtos;
-using xAiModels.Models.Entities;
-using xDataService.Configuration;
-using xIdentityService.Interfaces;
-using Microsoft.AspNetCore.SignalR;
-
-namespace xAiModels.Providers.Dtos
-{
-    public class XAiMcpServerServiceProvider
-        : XBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub>, IXAiMcpServerServiceProvider
-    {
-        public XAiMcpServerServiceProvider(
-            IHubContext<XAiMcpServerDtoHub> hub,
-            XDataServiceConfiguration dataConfiguration,
-            IXAiMcpServerRepositoryService service,
-            IXIdentityProvider identityProvider = null
-        ) : base(hub, dataConfiguration, service, identityProvider) { }
-    }
-}
-
-
- - - - -
-
-
۶
-
-

Helper و ثبت در DI

-
XAiModelsHelper + XDIHelperExtension
-
-
-
-

مطابق الگوی موجود در XAiModelsHelper، سه متد برای ساخت Repository Descriptor اضافه کنید:

- -
xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)
-
// ── درون کلاس XAiModelsHelper اضافه کنید ──
-
-#region XAiMcpServer ...
-// EF Repository Descriptor
-public static XEFRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository,
-    XAiMcpServerEFRepository<TContext>, TContext
-> GetXAiMcpServerEFRepositoryDescriptor<TContext>()
-where TContext : XDbContext
-{
-    return new XEFRepositoryDescriptor<...>();  // پر کردن کامل نوع‌ها
-}
-
-// Mongo Repository Descriptor
-public static XMongoRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository, XAiMcpServerMongoRepository
-> GetXAiMcpServerMongoRepositoryDescriptor()
-{
-    return new XMongoRepositoryDescriptor<...>();
-}
-
-// InMemory Repository Descriptor
-public static XInMemoryRepositoryDescriptor<
-    XAiMcpServer, Guid,
-    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
-    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
-    XAiMcpServerGraphType, GuidGraphType,
-    XAiMcpServerGraphQuery,
-    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
-    XAiMcpServerGraphSchema,
-    IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
-> GetXAiMcpServerInMemoryRepositoryDescriptor()
-{
-    return new XInMemoryRepositoryDescriptor<...>();
-}
-#endregion
- -
- ⚠️ توجه: برای سادگی، GraphQL types (مانند XAiMcpServerGraphType، XAiMcpServerGraphQuery و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با null جایگزین کنید یا با الگوگیری دقیق از XAiProjectGraphType و... آن‌ها را ایجاد نمایید. -
- -

سپس در XDIHelperExtension پروژه xAiModels، ثبت‌ها را اضافه کنید:

- -
xAiModels/DI/XDIHelperExtension.cs (MODIFY)
-
// ── ۱) متغیر استاتیک جدید اضافه کنید ──
-private static XRepositoryDescriptor aiMcpServerDescriptor = null;
-
-// ── ۲) درون switch روی repositoryType، در بخش EF ──
-aiMcpServerDescriptor = typeof(XAiModelsHelper)
-    .InvokeGenericMethod<XRepositoryDescriptor>(
-        args: null,
-        runtimeType: contextType,
-        methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor
-    );
-
-// ── ۳) درون switch، در بخش Mongo ──
-aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor();
-
-// ── ۴) درون switch، در بخش InMemory ──
-aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor();
-
-// ── ۵) درون region Register Repository Descriptor ──
-if (!aiMcpServerDescriptor.IsNull())
-{
-    services.AddXRepository(lifeTime: lifeTime, descriptor: aiMcpServerDescriptor);
-}
-
-// ── ۶) درون region Register Services، یک region جدید اضافه کنید ──
-#region AiMcpServer ...
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider),
-                          typeof(XAiMcpServerServiceProvider), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService),
-                          typeof(XAiMcpServerRepositoryService), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider),
-                          typeof(XAiMcpServerRepositoryProvider), lifeTime)
-);
-services.Add(
-    new ServiceDescriptor(typeof(IXAiMcpServerEnricher),
-                          typeof(XAiMcpServerEnricher), lifeTime)
-);
-#endregion
- -

همچنین در UseXAiDataService (همان فایل، برای Hubs):

- -
// ── اضافه کنید ──
-pushHelper.AddHub<XAiMcpServerDtoHub>(XAiModelsConstants.XAiMcpServerDtoHub);
-pushHelper.AddHub<XAiMcpServerEntityHub>(XAiModelsConstants.XAiMcpServerEntityHub);
-
-// در بخش Use Repository Descriptor
-if (!aiMcpServerDescriptor.IsNull())
-{
-    app.UseXRepository(descriptor: aiMcpServerDescriptor,
-                       isDevelopmentEnvironment: isDevelopmentEnvironment);
-}
-
-
- - - - -
-
-
۷
-
-

ثبت Registerar در DbContext

-
XAiApiDbContext.cs (MODIFY)
-
-
-
-

در فایل XAiApiDbContext.cs، نام Registerar جدید را به لیست dynamicEntityRegisterarsNames اضافه کنید:

- -
xAiApi/Database/XAiApiDbContext.cs (MODIFY)
-
dynamicEntityRegisterarsNames: [
-    nameof(XTagEntityRegisterar),
-    nameof(XFileEntityRegisterar),
-    nameof(XStringEntityRegisterar),
-    nameof(XAiMessageEntityRegisterar),
-    nameof(XAiProjectEntityRegisterar),
-    nameof(XAiConversationEntityRegisterar),
-    nameof(XAiMcpServerEntityRegisterar),    // ← جدید
-]
- -
- 💡 نکته: پس از این تغییر، یک Migration جدید برای جدول AiMcpServers بسازید: -

- dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext -

- سپس dotnet ef database update. -
-
-
- - - - -
-
-
۸
-
-

Seeder از appSettings

-
XMcpServersConfiguration + XMcpServerSeederService
-
-
-
-

این بخش هسته اصلی درخواست شماست: خواندن McpServers از appSettings، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت IHostedService در استارتاپ اجرا می‌شود.

- -

الف) مدل Configuration

- -
xAiApi/Configurations/XMcpServersConfiguration.cs
-
using System.Collections.Generic;
-using xAiModels.Models;
-
-namespace xAiApi.Configurations
-{
-    /// <summary>
-    /// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
-    /// </summary>
-    public class XMcpServersConfiguration
-    {
-        /// <summary>
-        /// آیا Seeder در استارتاپ اجرا شود؟
-        /// </summary>
-        public bool SyncOnStartup { get; set; } = true;
-
-        /// <summary>
-        /// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
-        /// </summary>
-        public bool UpdateExisting { get; set; } = false;
-
-        /// <summary>
-        /// OwnerId پیش‌فرض برای سرورهای Seed شده ...
-        /// (اگر خالی باشد از "system" استفاده می‌شود)
-        /// </summary>
-        public string DefaultOwnerId { get; set; } = "system";
-
-        /// <summary>
-        /// لیست سرورهای MCP ...
-        /// </summary>
-        public List<XMcpServerDescriptor> Servers { get; set; } = new();
-    }
-}
- -

ب) سرویس Seeder

- -
xAiApi/Services/XMcpServerSeederService.cs
-
using System;
-using System.Linq;
-using System.Text.Json;
-using xAiModels.Models;
-using System.Threading;
-using System.Threading.Tasks;
-using xCommons.Extensions;
-using xAiModels.Models.Dtos;
-using System.Collections.Generic;
-using Microsoft.Extensions.Hosting;
-using xAiApi.Configurations;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
-using xAiModels.Interfaces.Dtos;
-
-namespace xAiApi.Services
-{
-    /// <summary>
-    /// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
-    /// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
-    /// </summary>
-    public class XMcpServerSeederService : IHostedService
-    {
-        private readonly ILogger<XMcpServerSeederService> logger;
-        private readonly XMcpServersConfiguration config;
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-
-        public XMcpServerSeederService(
-            ILogger<XMcpServerSeederService> logger,
-            IOptions<XMcpServersConfiguration> config,
-            IXAiMcpServerRepositoryService repositoryService
-        )
-        {
-            this.logger = logger;
-            this.config = config.Value;
-            this.repositoryService = repositoryService;
-        }
-
-        public async Task StartAsync(CancellationToken cancellationToken)
-        {
-            // اگر Sync غیرفعال است، هیچ کاری نکن
-            if (!config.SyncOnStartup)
-            {
-                logger.LogInformation(
-                    "MCP Seed: SyncOnStartup=false، عملیات Seed اجرا نشد.");
-                return;
-            }
-
-            // اگر لیست خالی است، خارج شو
-            if (!config.Servers.HasChild())
-            {
-                logger.LogInformation(
-                    "MCP Seed: هیچ سروری در appSettings تعریف نشده است.");
-                return;
-            }
-
-            logger.LogInformation(
-                "MCP Seed: شروع Seed برای {Count} سرور ...",
-                config.Servers.Count);
-
-            foreach (var descriptor in config.Servers)
-            {
-                // اعتبارسنجی حداقلی
-                if (descriptor.IsNullOrDefault() ||
-                    descriptor.Name.IsNullOrEmpty())
-                {
-                    logger.LogWarning("MCP Seed: یک Descriptor نامعتبر نادیده گرفته شد.");
-                    continue;
-                }
-
-                await SeedOneAsync(descriptor, cancellationToken);
-            }
-
-            logger.LogInformation("MCP Seed: عملیات به پایان رسید.");
-        }
-
-        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
-
-        // ────────────────────────────────────────────────────────
-        // Seed یک Descriptor
-        // ────────────────────────────────────────────────────────
-        private async Task SeedOneAsync(
-            XMcpServerDescriptor descriptor,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                var ownerId = config.DefaultOwnerId.IsNullOrEmpty()
-                    ? "system"
-                    : config.DefaultOwnerId;
-
-                // بررسی وجود سرور با این نام و Owner
-                var existing = await repositoryService.FindByNameAsync(
-                    ownerId: ownerId,
-                    name: descriptor.Name,
-                    cancellationToken: cancellationToken
-                );
-
-                // ── حالت ایجاد ──
-                if (existing.IsNullOrDefault())
-                {
-                    var item = MapToDto(descriptor, ownerId, id: null);
-                    item.CreatedOn = DateTime.UtcNow;
-
-                    await repositoryService.AddAsync(
-                        item: item,
-                        saveChanges: true,
-                        cancellationToken: cancellationToken
-                    );
-
-                    logger.LogInformation(
-                        "MCP Seed: سرور '{Name}' ایجاد شد.", descriptor.Name);
-                    return;
-                }
-
-                // ── حالت به‌روزرسانی ──
-                if (!config.UpdateExisting)
-                {
-                    logger.LogDebug(
-                        "MCP Seed: سرور '{Name}' از قبل وجود دارد (UpdateExisting=false).",
-                        descriptor.Name);
-                    return;
-                }
-
-                var updateItem = MapToDto(descriptor, ownerId, id: existing.Id);
-                updateItem.CreatedOn = existing.CreatedOn;
-                updateItem.UpdatedAt = DateTime.UtcNow;
-
-                await repositoryService.UpdateAsync(
-                    item: updateItem,
-                    id: existing.Id,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                logger.LogInformation(
-                    "MCP Seed: سرور '{Name}' به‌روزرسانی شد.", descriptor.Name);
-            }
-            catch (Exception ex)
-            {
-                logger.LogError(ex,
-                    "MCP Seed: خطا در Seed سرور '{Name}'. این سرور نادیده گرفته می‌شود.",
-                    descriptor.Name);
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        // تبدیل Descriptor به DTO
-        // ────────────────────────────────────────────────────────
-        private static XAiMcpServerDto MapToDto(
-            XMcpServerDescriptor d,
-            string ownerId,
-            Guid? id)
-        {
-            var item = new XAiMcpServerDto
-            {
-                OwnerId = ownerId,
-                Name = d.Name,
-                Description = d.Description,
-                Enabled = d.Enabled,
-                Transport = d.Transport,
-                Command = d.Command,
-                Endpoint = d.Endpoint,
-                TimeoutSeconds = d.TimeoutSeconds,
-                WorkingDirectory = d.WorkingDirectory,
-
-                // تبدیل لیست/دیکشنری به JSON برای ذخیره در DB
-                Arguments = d.Arguments.HasChild()
-                    ? JsonSerializer.Serialize(d.Arguments)
-                    : null,
-                EnvironmentVariables = d.EnvironmentVariables.HasChild()
-                    ? JsonSerializer.Serialize(d.EnvironmentVariables)
-                    : null,
-                Headers = d.Headers.HasChild()
-                    ? JsonSerializer.Serialize(d.Headers)
-                    : null,
-            };
-
-            if (id.HasValue) item.Id = id.Value;
-
-            return item;
-        }
-    }
-}
- -
- ✓ رفتار Seeder: -
    -
  • اگر سروری در DB نیست → ایجاد می‌شود
  • -
  • اگر هست و UpdateExisting = false → دست نمی‌خورد
  • -
  • اگر هست و UpdateExisting = true → فیلدها به‌روزرسانی می‌شوند
  • -
  • خطای یک سرور باعث توقف کل فرآیند نمی‌شود
  • -
-
-
-
- - - - -
-
-
۹
-
-

ثبت در Startup.cs

-
Startup.cs (MODIFY)
-
-
-
- -
// ── در ConfigureServices، بعد از AddXAiServices ──
-
-// ۱. ثبت XMcpServersConfiguration از appSettings
-services.Configure<XMcpServersConfiguration>(
-    Configuration.GetSection("McpServers"));
-
-// ۲. ثبت Seeder به‌صورت HostedService
-services.AddHostedService<XMcpServerSeederService>();
-
-// ۳. ثبت Connection Manager (از مرحله قبل)
-services.AddSingleton<XMcpServerConnectionManager>();
-
-// ۴. ثبت Health Monitor
-services.AddHostedService<XMcpHealthMonitorService>();
- -
- ⚠️ ترتیب اجرا: Seeder به‌عنوان IHostedService پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به IXAiMcpServerRepositoryService دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول xAiModels پیش از اجرای Seeder کامل شده باشند. -
-
-
- - - - -
-
-
۱۰
-
-

کنترلر CRUD برای مدیریت از طریق API

-
Controllers/McpServersController.cs
-
-
-
- -
xAiApi/Controllers/McpServersController.cs
-
using System;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using xAiApi.Services;
-using xCommons.Providers;
-using xCommons.Extensions;
-using xExceptions.Constants;
-using xAiModels.Models.Dtos;
-using xCommons.Configurations;
-using Microsoft.AspNetCore.Mvc;
-using System.Collections.Generic;
-using xIdentityService.Interfaces;
-using xIdentityService.Controllers;
-using xAiModels.Interfaces.Dtos;
-using Microsoft.Extensions.Logging;
-using Microsoft.AspNetCore.Authorization;
-
-namespace xAiApi.Controllers
-{
-    [Authorize]
-    [Route("[controller]")]
-    public class McpServersController : XBaseIdentityApiV1Controller
-    {
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-        private readonly XMcpServerConnectionManager connectionManager;
-
-        public McpServersController(
-            ILogger<McpServersController> logger,
-            XAppConfiguration appConfiguration,
-            IXIdentityProvider identityProvider,
-            XValidationProvider validationProvider,
-            XMcpServerConnectionManager connectionManager,
-            IXAiMcpServerRepositoryService repositoryService
-        ) : base(logger, appConfiguration, identityProvider, validationProvider)
-        {
-            this.connectionManager = connectionManager;
-            this.repositoryService = repositoryService;
-        }
-
-        #region Loaders ...
-        /// <summary>
-        /// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
-        /// </summary>
-        [HttpGet("")]
-        public async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> LoadAll(
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var result = await repositoryService.FindManyAsync(
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken,
-                    predicate: x => x.OwnerId == userInfo.UserId,
-                    orderBuilder: x => x.OrderBy(y => y.Name)
-                );
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-
-        /// <summary>
-        /// دریافت یک سرور بر اساس Id ...
-        /// </summary>
-        [HttpGet("{id:guid}")]
-        public async Task<ActionResult<XAiMcpServerDto>> GetById(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var item = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                return Ok(item);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Creators ...
-        /// <summary>
-        /// ایجاد سرور MCP جدید ...
-        /// </summary>
-        [HttpPost("")]
-        public async Task<ActionResult<XAiMcpServerDto>> Create(
-            [FromBody] XAiMcpServerDto item,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                if (item.IsNullOrDefault() || item.Name.IsNullOrEmpty())
-                    XException.InvalidArgs.Throw();
-
-                var userInfo = await GetUserInfo();
-
-                // بررسی یکتایی نام برای این Owner
-                var existing = await repositoryService.FindByNameAsync(
-                    ownerId: userInfo.UserId,
-                    name: item.Name,
-                    cancellationToken: cancellationToken
-                );
-
-                if (!existing.IsNullOrDefault())
-                    XException.InvalidArgs.Throw("این نام قبلاً استفاده شده است.");
-
-                // پر کردن فیلدهای ضروری
-                item.Id = Guid.Empty;  // اطمینان از اینکه Id جدید تولید می‌شود
-                item.OwnerId = userInfo.UserId;
-                item.CreatedOn = DateTime.UtcNow;
-                item.UpdatedAt = DateTime.UtcNow;
-
-                var result = await repositoryService.AddAsync(
-                    item: item,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Updaters ...
-        /// <summary>
-        /// به‌روزرسانی سرور MCP ...
-        /// </summary>
-        [HttpPut("{id:guid}")]
-        public async Task<ActionResult<XAiMcpServerDto>> Update(
-            Guid id,
-            [FromBody] XAiMcpServerDto item,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                if (item.IsNullOrDefault() || id == Guid.Empty)
-                    XException.InvalidArgs.Throw();
-
-                var userInfo = await GetUserInfo();
-
-                var existing = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                // پر کردن فیلدهای سیستم
-                item.Id = id;
-                item.OwnerId = existing.OwnerId;
-                item.CreatedOn = existing.CreatedOn;
-                item.UpdatedAt = DateTime.UtcNow;
-
-                var result = await repositoryService.UpdateAsync(
-                    item: item,
-                    id: id,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(result);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Removers ...
-        /// <summary>
-        /// حذف نرم یک سرور MCP ...
-        /// </summary>
-        [HttpDelete("{id:guid}")]
-        public async Task<ActionResult<bool>> Remove(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var existing = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                await repositoryService.RemoveAsync(
-                    id: id,
-                    softDelete: true,
-                    saveChanges: true,
-                    cancellationToken: cancellationToken
-                );
-
-                // بازسازی اتصال‌ها
-                await connectionManager.RefreshAsync();
-
-                return Ok(true);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-
-        #region Actions ...
-        /// <summary>
-        /// اعتبارسنجی و اتصال دستی به یک سرور ...
-        /// </summary>
-        [HttpPost("{id:guid}/Test")]
-        public async Task<ActionResult<string>> Test(
-            Guid id,
-            CancellationToken cancellationToken = default)
-        {
-            try
-            {
-                var userInfo = await GetUserInfo();
-
-                var item = await repositoryService.GetAsync(
-                    id: id,
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken
-                );
-
-                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
-                    XException.NotFound.Throw();
-
-                var message = await connectionManager.TestServerAsync(
-                    item, cancellationToken);
-
-                return Ok(message);
-            }
-            catch (Exception ex)
-            {
-                return GetExceptionActionResult(ex);
-            }
-        }
-        #endregion
-    }
-}
- -
- 💡 مسیرهای API: - - - - - - - - - - -
متدمسیرتوضیح
GET/McpServersلیست تمام سرورهای کاربر
GET/McpServers/{id}دریافت یک سرور
POST/McpServersایجاد سرور جدید
PUT/McpServers/{id}به‌روزرسانی
DELETE/McpServers/{id}حذف نرم
POST/McpServers/{id}/Testاعتبارسنجی و تست اتصال
-
-
-
- - - - -
-
-
۱۱
-
-

به‌روزرسانی XMcpServerConnectionManager

-
حالا از DB می‌خواند، نه از IOptionsMonitor
-
-
-
-

در نسخه قبل، Connection Manager مستقیماً از IOptionsMonitor<XMcpServersConfiguration> می‌خواند. اکنون باید از دیتابیس بخواند:

- -
xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)
-
using System;
-using System.Linq;
-using System.Text.Json;
-using System.Threading;
-using System.Threading.Tasks;
-using xAiApi.Constants;
-using xAiModels.Models.Dtos;
-using System.Collections.Generic;
-using Microsoft.Extensions.Logging;
-using ModelContextProtocol.Client;
-using xAiModels.Interfaces.Dtos;
-
-namespace xAiApi.Services
-{
-    public class XMcpServerConnectionManager : IAsyncDisposable
-    {
-        private readonly ILogger<XMcpServerConnectionManager> logger;
-        private readonly IXAiMcpServerRepositoryService repositoryService;
-        private readonly Dictionary<Guid, McpClient> clients = new();
-        private readonly Dictionary<Guid, IList<McpClientTool>> tools = new();
-        private readonly SemaphoreSlim initLock = new(1, 1);
-        private bool isInitialized = false;
-
-        public XMcpServerConnectionManager(
-            ILogger<XMcpServerConnectionManager> logger,
-            IXAiMcpServerRepositoryService repositoryService)
-        {
-            this.logger = logger;
-            this.repositoryService = repositoryService;
-        }
-
-        /// <summary>
-        /// دریافت تمام ابزارهای موجود از سرورهای فعال ...
-        /// </summary>
-        public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
-            CancellationToken cancellationToken = default)
-        {
-            if (isInitialized)
-                return tools.Values.SelectMany(t => t).ToList();
-
-            await initLock.WaitAsync(cancellationToken);
-            try
-            {
-                if (isInitialized)
-                    return tools.Values.SelectMany(t => t).ToList();
-
-                // ← خواندن از DB به‌جای IOptions
-                var servers = await repositoryService.FindManyAsync(
-                    includeBuilder: null,
-                    ignoreSoftDeleteds: true,
-                    cancellationToken: cancellationToken,
-                    predicate: x => x.Enabled
-                );
-
-                if (servers.HasChild())
-                {
-                    var tasks = servers.Select(s =>
-                        ConnectAndValidateAsync(s, cancellationToken));
-                    await Task.WhenAll(tasks);
-                }
-
-                isInitialized = true;
-                return tools.Values.SelectMany(t => t).ToList();
-            }
-            finally
-            {
-                initLock.Release();
-            }
-        }
-
-        /// <summary>
-        /// تست دستی یک سرور خاص ...
-        /// </summary>
-        public async Task<string> TestServerAsync(
-            XAiMcpServerDto server,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
-
-                var client = await CreateClientAsync(server, cts.Token);
-                await client.PingAsync(cts.Token);
-                var serverTools = await client.ListToolsAsync(cts.Token);
-
-                var names = string.Join(", ", serverTools.Select(t => t.Name));
-                return $"✓ سرور '{server.Name}' پاسخگو است. {serverTools.Count} ابزار: {names}";
-            }
-            catch (Exception ex)
-            {
-                return $"✗ خطا: {ex.Message}";
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        private async Task ConnectAndValidateAsync(
-            XAiMcpServerDto descriptor,
-            CancellationToken cancellationToken)
-        {
-            try
-            {
-                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
-                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
-
-                var client = await CreateClientAsync(descriptor, cts.Token);
-                await client.PingAsync(cts.Token);
-                var serverTools = await client.ListToolsAsync(cts.Token);
-
-                clients[descriptor.Id] = client;
-                tools[descriptor.Id] = serverTools;
-
-                logger.LogInformation(
-                    "MCP '{Name}': {Count} ابزار کشف شد.",
-                    descriptor.Name, serverTools.Count);
-            }
-            catch (Exception ex)
-            {
-                logger.LogWarning(ex,
-                    "MCP '{Name}': اتصال برقرار نشد، نادیده گرفته شد.",
-                    descriptor.Name);
-            }
-        }
-
-        // ────────────────────────────────────────────────────────
-        private static async Task<McpClient> CreateClientAsync(
-            XAiMcpServerDto s,
-            CancellationToken cancellationToken)
-        {
-            IClientTransport transport = s.Transport?.ToLowerInvariant() switch
-            {
-                "http" => new HttpClientTransport(new HttpClientTransportOptions
-                {
-                    Endpoint = new Uri(s.Endpoint!),
-                    AdditionalHeaders = ParseJsonDict(s.Headers),
-                    TransportMode = HttpTransportMode.AutoDetect
-                }),
-                _ => new StdioClientTransport(new StdioClientTransportOptions
-                {
-                    Command = s.Command ?? "dotnet",
-                    Arguments = ParseJsonList(s.Arguments) ?? new List<string>(),
-                    WorkingDirectory = s.WorkingDirectory,
-                    EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
-                        .ToDictionary(kv => kv.Key, kv => (string?)kv.Value),
-                    Name = s.Name,
-                    ShutdownTimeout = TimeSpan.FromSeconds(5)
-                })
-            };
-
-            return await McpClient.CreateAsync(transport,
-                cancellationToken: cancellationToken);
-        }
-
-        // ────────────────────────────────────────────────────────
-        private static Dictionary<string, string> ParseJsonDict(string json)
-            => json.IsNullOrEmpty() ? null
-                : JsonSerializer.Deserialize<Dictionary<string, string>>(json);
-
-        private static List<string> ParseJsonList(string json)
-            => json.IsNullOrEmpty() ? null
-                : JsonSerializer.Deserialize<List<string>>(json);
-
-        // ────────────────────────────────────────────────────────
-        public async Task RefreshAsync()
-        {
-            logger.LogInformation("MCP: بازسازی اتصال‌ها ...");
-
-            foreach (var client in clients.Values)
-            {
-                try { await client.DisposeAsync(); } catch { }
-            }
-            clients.Clear();
-            tools.Clear();
-
-            isInitialized = false;
-            await GetAvailableToolsAsync(CancellationToken.None);
-        }
-
-        public async ValueTask DisposeAsync()
-        {
-            foreach (var client in clients.Values)
-            {
-                try { await client.DisposeAsync(); } catch { }
-            }
-            initLock.Dispose();
-        }
-    }
-}
- -
- ✓ نتیجه: حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد RefreshAsync() فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. appSettings فقط منبع Seed اولیه است. -
-
-
- - - - -
-
-
۱۲
-
-

نمونه کامل appsettings.json

-
appsettings.json (MODIFY)
-
-
-
- -
{
-  "AiApiConfiguration": {
-    "Models": [ /* ... مدل‌های موجود ... */ ],
-    "Prompts": [ /* ... پرامپت‌های موجود ... */ ]
-  },
-
-  "McpServers": {
-    "SyncOnStartup": true,
-    "UpdateExisting": false,
-    "DefaultOwnerId": "system",
-    "Servers": [
-      {
-        "Name": "xai-knowledge",
-        "Description": "سرور MCP جستجو در پایگاه دانش",
-        "Enabled": true,
-        "Transport": "stdio",
-        "Command": "dotnet",
-        "Arguments": [ "xAiMcpServer.dll" ],
-        "TimeoutSeconds": 20
-      },
-      {
-        "Name": "remote-tools",
-        "Description": "ابزارهای تیمی از راه دور",
-        "Enabled": true,
-        "Transport": "http",
-        "Endpoint": "https://tools.example.com/mcp",
-        "Headers": {
-          "X-API-Key": "your-key"
-        },
-        "TimeoutSeconds": 30
-      },
-      {
-        "Name": "file-processor",
-        "Description": "پردازش فایل با معیارهای سفارشی",
-        "Enabled": false,
-        "Transport": "stdio",
-        "Command": "node",
-        "Arguments": [ "file-processor.js", "--port", "3000" ],
-        "EnvironmentVariables": {
-          "LOG_LEVEL": "info"
-        },
-        "TimeoutSeconds": 15
-      }
-    ]
-  },
-
-  "ConnectionStrings": { /* ... */ },
-  "Logging": { /* ... */ }
-}
-
-
- - - - -
-
-
۱۳
-
-

تست و اعتبارسنجی

-
Testing & Validation
-
-
-
-

جریان تست پیشنهادی:

- -
    -
  1. Migration: پس از اعمال Migration، جدول AiMcpServers را در دیتابیس بررسی کنید.
  2. -
  3. اجرای اپلیکیشن: لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند "MCP Seed: سرور 'xai-knowledge' ایجاد شد." نمایش داده شود.
  4. -
  5. بررسی DB: با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.
  6. -
  7. تست API: با یک توکن معتبر، GET /McpServers را فراخوانی کنید و لیست سرورها را ببینید.
  8. -
  9. تست ایجاد: یک سرور جدید با POST /McpServers بسازید.
  10. -
  11. تست Connection: با POST /McpServers/{id}/Test اعتبارسنجی کنید.
  12. -
  13. تست Function Calling: از /DefaultAi/AskText استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.
  14. -
- -
- ⚠️ نکات مهم: -
    -
  • اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.
  • -
  • هنگام اجرای dotnet ef migrations add، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.
  • -
  • در محیط توسعه، پیشنهاد می‌شود UpdateExisting = true باشد تا تغییرات appSettings سریع اعمال شوند.
  • -
  • در محیط عملیاتی، UpdateExisting = false باشد تا APIها بازنویسی نشوند.
  • -
-
-
-
- - - - -
-
-
۱۴
-
-

جمع‌بندی و چک‌لیست نهایی

-
Summary & Checklist
-
-
-
-

چک‌لیست فایل‌های جدید/تغییر یافته:

- -
    -
  • Entity، DTO و Descriptor در xAiModels/Models ایجاد شد
  • -
  • EntityConfiguration و EntityRegisterar اضافه شد
  • -
  • Constants جدید در XAiModelsConstants افزوده شد
  • -
  • تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد
  • -
  • Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد
  • -
  • RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد
  • -
  • Helper (سه متد Descriptor) به XAiModelsHelper اضافه شد
  • -
  • ثبت در XDIHelperExtension انجام شد
  • -
  • Mapper Profile به‌روزرسانی شد
  • -
  • Registerar در XAiApiDbContext ثبت شد
  • -
  • Migration اجرا شد
  • -
  • XMcpServersConfiguration و XMcpServerSeederService ایجاد شد
  • -
  • XMcpServerConnectionManager برای خواندن از DB تغییر کرد
  • -
  • McpServersController با CRUD کامل اضافه شد
  • -
  • Startup.cs به‌روزرسانی شد (Configure + HostedServices)
  • -
  • appsettings.json با بخش McpServers تکمیل شد
  • -
- -
-

🎯 نتیجه نهایی

-

با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:

-

- appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM -

-

- سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت. -

-
-
-
- -
- -
- - -
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی-داخلی
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0da0136c-9f49-439d-bc78-84aa19e17262.html - - - - - - -نقشه BPMN2 تعاملی | مولفه‌های معماری سامانه هوش مصنوعی سازمانی - - - - -
- -
-
-
- -
-
-
شماره مستند: BPMN-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- BPMN 2.0 INTERACTIVE MAP -

نقشه فرایندی تعاملی مولفه‌ها

-

سامانه هوش مصنوعی سازمانی — بر اساس معماری کلان ARCH-1405-001

-
-
- -
- -
- خلاصه مدیریتی،
- این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را بر اساس استاندارد BPMN 2.0 رسم می‌کند. مولفه‌ها در قالب Lane (لایه‌های معماری) سازمان‌دهی شده‌اند و روابط میان آنها با Sequence Flow نمایش داده می‌شود. با کلیک روی هر مولفه، مودالی شامل وظایف، ورودی‌ها و خروجی‌ها و ارتباطات آن نمایش داده می‌شود. -
- -
-
-
۱
-
-

راهنمای نقشه BPMN2

-
How to Read the Map
-
-
-
-

نقشه زیر بر اساس استاندارد BPMN 2.0 ترسیم شده است. هر Lane نماینده یک لایه معماری است و هر Task (مستطیل) نماینده یک مولفه. فلش‌ها جریان درخواست/کنترل را نشان می‌دهند. روی هر مولفه کلیک کنید تا جزئیات آن را در مودال مشاهده کنید.

- -
-
-
۸
-
Lane (لایه + محور عرضی)
-
-
-
۲۵+
-
مولفه قابل کلیک
-
-
-
BPMN 2.0
-
استاندارد رسم
-
-
- -
- 💡 نحوه استفاده: نشانگر ماوس را روی هر مستطیل ببرید تا هایلایت شود؛ سپس کلیک کنید تا مودال اطلاعات (وظایف، ورودی‌ها، خروجی‌ها و ارتباطات) باز شود. برای بستن مودال، کلید Esc را بزنید یا روی پس‌زمینه کلیک کنید. -
-
-
- -
-
-
۲
-
-

نقشه BPMN2 تعاملی

-
Interactive BPMN2 Process Map
-
-
-
- -
-
- لایه تعامل/گزارش - لایه کنترل/هوش - لایه ارکستراسیون - لایه داده - محور حاکمیت - محور مشاهده‌پذیری -
- 👆 روی هر مولفه کلیک کنید -
- -
- - - - - - - - - - - - - - - - - L1 — تعامل و تجربه - Interaction Layer - - - - - - - - L2 — کنترل دسترسی - Access & Session - - - - - - - - L3 — ارکستراسیون - Orchestration / Agent Core - - - - - - - - L4 — هوش و مدل‌ها - Intelligence Layer - - - - - - - - L5 — داده و منابع - Data & Resources - - - - - - - - L6 — خروجی و گزارش - Output & Reporting - - - - - - - - X — حاکمیت داده - Data Governance (Cross-cutting) - - - - - - - - Y — مشاهده‌پذیری - Observability (Cross-cutting) - - - - - - - - کاربر / Actor - External Actor - - - - - - - - رابط وب - Web UI - - - - - - نسخه دسکتاپ - Desktop App - - - - - - درگاه API - API Gateway - - - - - - - احراز هویت - Authentication - - - - - - مدیریت نشست - Session Manager - - - - - - موتور مجوزها - Permission Engine - - - - - - مدیریت نقش‌ها - Role Manager - - - - - - - موتور ایجنت - Agent Engine - - - - - - برنامه‌ریز - Planner - - - - - - انتخاب‌گر ابزار - Tool Selector - - - - - - مدیریت جریان - Flow Manager - - - - - - تأیید انسانی - Human-in-the-loop - - - - - - - درگاه مدل‌ها - Model Gateway - - - - - - مدیریت مدل - Model Manager - - - - - - بازیابی و تقویت - RAG - - - - - - حافظه و زمینه - Memory & Context - - - - - - - منابع دانش - Knowledge Sources - - - - - - مدیریت فایل - File & Folder - - - - - - سرویس‌های خارجی - External Services - - - - - - ابزارهای عملیاتی - Operational Tools - - - - - - - تولید گزارش - Report Generator - - - - - - مبدل قالب - Format Converter - - - - - - داشبورد مصرف - Usage Dashboard - - - - - - - سیاست‌گذار داده - Data Policy - - - - - - ممیزی و لاگ - Audit & Log - - - - - - سنسور محرمانگی - Confidentiality Sensor - - - - - - - متریک و ردیابی - Metrics & Tracing - - - - - - - کاربر سازمانی - Actor / User - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - درخواست - درخواست - درخواست - زمینه - مجوزها - استدلال - ابزار - نتیجه - فایل - فیلتر - متریک - - - - راهنمای نمادها (BPMN 2.0): - - Task / مولفه - - Sequence Flow - - Data / Control Flow - - Actor - - - -
- -
- 💡 نکته: این نقشه بر اساس استاندارد BPMN 2.0 ترسیم شده است. Laneها نماینده لایه‌های معماری (L1 تا L6) و محورهای عرضی (X و Y) هستند. فلش‌های ممتد نماینده Sequence Flow (جریان اصلی درخواست) و فلش‌های نقطه‌چین نماینده Data/Control Flow (جریان داده و کنترل عرضی) هستند. -
-
-
- -
-
-
۳
-
-

جدول مولفه‌ها و ارتباطات

-
Component & Connection Summary
-
-
-
-

جدول زیر خلاصه‌ای از تمام مولفه‌های نقشه و ارتباطات ورودی/خروجی آنهاست. برای جزئیات بیشتر، روی هر مولفه در نقشه کلیک کنید.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Laneمولفهورودی اصلیخروجی اصلیمقصد
L1رابط وب / دسکتاپ / APIدرخواست کاربردرخواست ساختاریافتهمدیریت نشست
L2احراز هویتاعتبارنامههویت تأییدشدهمدیریت نشست
L2مدیریت نشستهویت + درخواستنشست فعالموتور ایجنت
L2موتور مجوزهانقش‌هافهرست مجازموتور ایجنت
L2مدیریت نقش‌هاتعریف نقشمجوزهای به‌روزموتور مجوزها
L3موتور ایجنتهدف + زمینهبرنامه / نتیجهبرنامه‌ریز / گزارش
L3برنامه‌ریزهدفمراحل اجراییانتخاب‌گر ابزار
L3انتخاب‌گر ابزارمرحلهابزار انتخاب‌شدهابزارهای عملیاتی
L3مدیریت جریاننتیجه اجراتصمیم ادامه/اصلاحموتور ایجنت
L3تأیید انسانیدرخواست تأییدتأیید/ردموتور ایجنت
L4درگاه مدل‌هادرخواست استدلالپاسخ مدلموتور ایجنت
L4مدیریت مدلفهرست مدلمدل مجازدرگاه مدل‌ها
L4بازیابی و تقویتپرسششواهددرگاه مدل‌ها
L4حافظه و زمینهتاریخچهزمینه فعالدرگاه مدل‌ها
L5منابع دانشدرخواست بازیابیاطلاعات مرتبطبازیابی و تقویت
L5مدیریت فایلمسیر فایلمحتوای فایلتولید گزارش
L5سرویس‌های خارجیدرخواست APIپاسخ سرویسدرگاه مدل‌ها
L5ابزارهای عملیاتیفراخوانینتیجه اجرامدیریت جریان
L6تولید گزارشنتیجه ایجنتگزارشمبدل قالب
L6مبدل قالبگزارشWord/Excelرابط کاربری
L6داشبورد مصرفمتریکگزارش مصرفرابط کاربری
Xسیاست‌گذار دادهسیاست سازمانیمحدودیت انتقالسرویس خارجی / درگاه مدل
Xممیزی و لاگرخدادهالاگ ممیزیداشبورد
Xسنسور محرمانگیپاسخ پیش از ارائهپاسخ فیلترشدهرابط کاربری
Yمتریک و ردیابیرخداد اجرامتریکداشبورد مصرف
-
-
- -
-
-
۴
-
-

جمع‌بندی

-
Summary
-
-
-
-

این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی را بر اساس استاندارد BPMN 2.0 رسم کرده است. ویژگی‌های کلیدی این نقشه:

- -
    -
  • ۸ Lane: شش لایه معماری + دو محور عرضی (حاکمیت داده و مشاهده‌پذیری) + Actor
  • -
  • ۲۵+ مولفه قابل کلیک: هر مولفه دارای مودال اطلاعاتی شامل وظایف، ورودی، خروجی و ارتباطات
  • -
  • دو نوع جریان: Sequence Flow (ممتد) برای جریان اصلی و Data/Control Flow (نقطه‌چین) برای جریان عرضی
  • -
  • رنگ‌بندی معنادار: هر لایه با رنگ مشخص، محورهای عرضی با خط‌چین و رنگ متمایز
  • -
  • نگاشت به نیازمندی‌ها: هر مولفه به محور نیازمندی مرتبط (REQ-1405-001) ارجاع داده شده است
  • -
- -
- نکته کلیدی: این نقشه BPMN2، پل ارتباطی بین معماری کلان (ARCH-1405-001) و طراحی تفصیلی است. هر مولفه در این نقشه، در مرحله طراحی تفصیلی به یک یا چند سرویس/ماژول قابل پیاده‌سازی تبدیل خواهد شد. -
-
-
- -
-

🎯 ارزش این مستند

-

نقشه BPMN2 تعاملی، امکان درک سریع و دقیق معماری را برای ذی‌نفعان فنی و غیرفنی فراهم می‌کند.

-

هر مولفه با کلیک، اطلاعات کامل وظایف و ارتباطات ورودی/خروجی را نمایش می‌دهد و مبنای طراحی تفصیلی و پیاده‌سازی قرار می‌گیرد.

-
- 💎 ارزش پیشنهادی:
- استاندارد BPMN 2.0 + تعامل‌پذیری کامل + نگاشت به نیازمندی‌ها + مبنای طراحی تفصیلی -
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - - - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0e4bdfcb-39a4-4b1f-94fa-d8159119150e.html - - - - - - -طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی | مستند فنی - - - -
-
-
-
- -
-
-
شماره مستند: ARCH-APIKEY-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: ۱۲ مهر ۱۴۰۵
-
تهیه‌کننده: هادی خزاعی اصل
-
طبقه‌بندی: محرمانه
-
-
-
-API KEY MANAGEMENT SYSTEM -

طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی

-

بررسی نیازمندی‌ها، معماری و پیاده‌سازی گام به گام

-
-
- -
- -
-توسعه‌دهنده گرامی،
-این مستند به‌عنوان یک طرح جامع فنی، قابلیت ایجاد برنامه‌های کاربردی دارای ApiKey را با پیروی از الگوهای OAuth2 در پلتفرم xDashboard بررسی می‌کند. در این سند، علاوه بر نیازمندی‌های اعلام‌شده، نیازمندی‌های تکمیلی و پیشنهادات بهبودی نیز ارائه شده است تا یک راهکار کامل، امن و مقیاس‌پذیر طراحی گردد. -
- - - - - -
-
-
۱
-
-

خلاصه اجرایی و آمار کلیدی

-
Executive Summary & Key Statistics
-
-
-
-

سیستم مدیریت ApiKey، یک لایه امنیتی جدید به پلتفرم xDashboard اضافه می‌کند که امکان ایجاد برنامه‌های کاربردی (Applications) با کلیدهای دسترسی موقت را فراهم می‌سازد. این سیستم بر پایه الگوهای OAuth2 Client Credentials طراحی شده و با زیرساخت IdentityServer4 موجود در xIds یکپارچه می‌گردد.

- -
-
-
۳
-
لایه اصلی پیاده‌سازی
-
-
-
۵
-
Entity جدید
-
-
-
۱۲+
-
نیازمندی تکمیلی
-
-
-
۴
-
مرحله پیاده‌سازی
-
-
- -
-نکته کلیدی: این راهکار با حفظ سازگاری کامل با الگوهای موجود پروژه (مانند XValidationProvider، XException، XPolicies و IXIdentityManager)، قابلیت ادغام بدون اصطکاک با اکوسیستم فعلی را دارد. -
-
-
- - -
-
-
۲
-
-

بررسی نیازمندی‌های اعلام‌شده

-
Analysis of Stated Requirements
-
-
-
-

بر اساس درخواست اعلام‌شده، سه نیازمندی اصلی شناسایی شده‌اند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#نیازمندیمحل پیاده‌سازیالگوی مرجع
۱ایجاد برنامه کاربردی و تولید ApiKey با مدت انقضای قابل تنظیمxIdsOAuth2 Client Credentials
۲اعتبارسنجی ApiKey در سرویس‌های مرتبطxIdentityServiceToken Introspection
۳تعریف دسترسی بر اساس ApiKey در احراز هویتxIds + xApiPolicy-based Authorization
- -
-💡 تحلیل اولیه: این نیازمندی‌ها در واقع پیاده‌سازی یک OAuth2 Client کامل هستند که در آن هر "برنامه کاربردی" معادل یک Client در IdentityServer4 بوده و ApiKey معادل ClientSecret است. با این حال، برای مدیریت بهتر چرخه حیات، نیاز به یک لایه انتزاعی بالاتر داریم. -
-
-
- - -
-
-
۳
-
-

نیازمندی‌های تکمیلی و پیشنهادات بهبود

-
Additional Requirements & Improvement Suggestions
-
-
-
-

در بررسی دقیق‌تر، نیازمندی‌های زیر شناسایی شدند که در درخواست اولیه ذکر نشده‌اند اما برای یک پیاده‌سازی کامل و امن ضروری هستند:

- -

🔐 الف) نیازمندی‌های امنیتی

-
-
-
🔑
-

۱. چرخش کلید (Key Rotation)

-

امکان تولید کلید جدید بدون اختلال در سرویس‌های در حال اجرا، با پشتیبانی از همزیستی موقت کلید قدیم و جدید.

-
-
-
🚫
-

۲. ابطال فوری (Revocation)

-

امکان Revoke کردن ApiKey قبل از انقضای طبیعی، برای موارد اضطراری مانند نشت کلید.

-
-
-
🌐
-

۳. IP Whitelist

-

محدودسازی استفاده از ApiKey به IPهای مشخص برای کاهش ریسک سوءاستفاده در صورت نشت.

-
-
-
🔒
-

۴. Rate Limiting

-

محدودیت تعداد درخواست در واحد زمان برای هر ApiKey جهت جلوگیری از سوءاستفاده و حملات DoS.

-
-
- -

📊 ب) نیازمندی‌های مدیریتی

-
-
-
📝
-

۵. Metadata و توضیحات

-

ذخیره نام برنامه، توضیحات، نام مالک و اطلاعات تماس برای هر ApiKey.

-
-
-
👤
-

۶. Owner Assignment

-

تخصیص هر ApiKey به یک کاربر یا سازمان مشخص برای مدیریت متمرکز و حسابرسی.

-
-
-
📈
-

۷. Audit Log

-

ثبت کامل لاگ استفاده از هر ApiKey شامل زمان، IP، Endpoint و نتیجه درخواست.

-
-
-
🏷️
-

۸. Scope Management

-

تعریف دقیق Scopeهای مجاز برای هر ApiKey (مانند read, write, admin) مشابه OAuth2.

-
-
- -

⚙️ ج) نیازمندی‌های عملیاتی

-
-
-
🔔
-

۹. Notification System

-

اطلاع‌رسانی به مالک قبل از انقضای ApiKey (مثلاً ۷ روز قبل) از طریق Email/SMS.

-
-
-
🔄
-

۱۰. Auto-Extension

-

امکان تمدید خودکار ApiKey در صورت فعال بودن برنامه (اختیاری).

-
-
-
📦
-

۱۱. Bulk Operations

-

امکان ایجاد، ابطال یا تمدید دسته‌ای ApiKeyها برای مدیریت در مقیاس بزرگ.

-
-
-
🗂️
-

۱۲. Tagging & Categorization

-

دسته‌بندی ApiKeyها بر اساس نوع برنامه (Mobile, Web, IoT, Third-party) برای گزارش‌گیری.

-
-
- -
-⚠️ پیشنهاد مهم: پیاده‌سازی حداقل موارد ۱ تا ۴ (چرخش کلید، ابطال فوری، IP Whitelist، Rate Limiting) برای یک سیستم تولیدی (Production) الزامی است. سایر موارد بر اساس اولویت کسب‌وکار در فازهای بعدی قابل اضافه شدن هستند. -
-
-
- - -
-
-
۴
-
-

طراحی معماری و مدل داده

-
Architecture Design & Data Model
-
-
-
- -

🏗️ معماری کلی سیستم

-
-
-
لایه API
-
ApplicationController — مدیریت برنامه‌ها و ApiKeyها (CRUD)
-
-
-
لایه سرویس
-
XApplicationManager — منطق تجاری، تولید کلید، مدیریت چرخه حیات
-
-
-
لایه زیرساخت
-
XApiKeyValidator + XApiKeyAuthProvider — اعتبارسنجی و احراز هویت
-
-
-
لایه داده
-
XApplication + XApiKey + XApiKeyUsageLog — Entityهای جدید
-
-
- -

📋 مدل‌های داده پیشنهادی

- -
-// Entity: XApplication (برنامه کاربردی)
-public class XApplication : XBaseGuidIDEntity
-{
-    [Required][StringLength(255)]
-    public string Name { get; set; }
-    
-    [StringLength(1000)]
-    public string Description { get; set; }
-    
-    [Required][StringLength(255)]
-    public string OwnerId { get; set; } // XUser.Id
-    
-    public XApplicationType Type { get; set; }
-    public bool IsActive { get; set; } = true;
-    public DateTime CreatedOn { get; set; }
-    public DateTime UpdatedAt { get; set; }
-    
-    // Navigation
-    public virtual ICollection<XApiKey> ApiKeys { get; set; }
-} -
- -
-// Entity: XApiKey (کلید دسترسی)
-public class XApiKey : XBaseGuidIDEntity
-{
-    [Required]
-    public Guid ApplicationId { get; set; }
-    
-    [Required][StringLength(512)]
-    public string KeyHash { get; set; } // SHA256 of ApiKey
-    
-    [StringLength(100)]
-    public string KeyPrefix { get; set; } // "xapp_abc123..."
-    
-    [Required]
-    public DateTime ExpiresAt { get; set; }
-    
-    public DateTime CreatedOn { get; set; }
-    public DateTime? LastUsedAt { get; set; }
-    public DateTime? RevokedAt { get; set; }
-    public string RevokedBy { get; set; }
-    
-    public bool IsRevoked => RevokedAt.HasValue;
-    public bool IsExpired => DateTime.UtcNow >= ExpiresAt;
-    public bool IsActive => !IsRevoked && !IsExpired;
-    
-    // Scope & Restrictions
-    [StringLength(1000)]
-    public string AllowedScopes { get; set; } // JSON array
-    
-    [StringLength(2000)]
-    public string AllowedIPs { get; set; } // Comma-separated
-    
-    public int RateLimitPerMinute { get; set; } = 60;
-    
-    // Navigation
-    public virtual XApplication Application { get; set; }
-} -
- -
-// Entity: XApiKeyUsageLog (لاگ استفاده)
-public class XApiKeyUsageLog : XBaseLongIDEntity
-{
-    public Guid ApiKeyId { get; set; }
-    public string Endpoint { get; set; }
-    public string HttpMethod { get; set; }
-    public string ClientIP { get; set; }
-    public int StatusCode { get; set; }
-    public DateTime RequestedOn { get; set; }
-    public long ResponseTimeMs { get; set; }
-} -
- -

🔢 Enumهای مورد نیاز

-
-public enum XApplicationType
-{
-    Web, Mobile, Desktop, IoT, ThirdParty, Service
-}
-
-public enum XApiKeyScope
-{
-    [StringValue("read")] Read,
-    [StringValue("write")] Write,
-    [StringValue("admin")] Admin,
-    [StringValue("manage")] Manage
-} -
-
-
- - -
-
-
۵
-
-

مرحله ۱: پیاده‌سازی در xIds

-
Phase 1: Implementation in xIds Module
-
-
-
- -

📌 گام ۱.۱: افزودن تنظیمات قابل پیکربندی

-

در کلاس XIdentityConfiguration (موجود در xIdentityModels)، بخش جدید برای تنظیمات ApiKey اضافه می‌شود:

- -
-// File: xIdentityModels/Configurations/XIdentityConfiguration.cs
-public class XIdentityConfiguration
-{
-    // ... existing properties ...
-    
-    public XApiKeyConfiguration ApiKey { get; set; } = new();
-}
-
-public class XApiKeyConfiguration
-{
-    // Default expiration in minutes (e.g., 43200 = 30 days)
-    public int DefaultExpirationMinutes { get; set; } = 43200;
-    
-    // Maximum allowed expiration (e.g., 525600 = 1 year)
-    public int MaxExpirationMinutes { get; set; } = 525600;
-    
-    // Maximum ApiKeys per Application
-    public int MaxKeysPerApplication { get; set; } = 10;
-    
-    // Notification before expiration (minutes)
-    public int NotifyBeforeMinutes { get; set; } = 10080; // 7 days
-    
-    // Enable audit logging
-    public bool EnableAuditLog { get; set; } = true;
-    
-    // Default rate limit (requests per minute)
-    public int DefaultRateLimit { get; set; } = 60;
-} -
- -

📌 گام ۱.۲: افزودن DbContext و Migration

-

در XIdentityDbContext، DbSetهای جدید اضافه می‌شوند:

- -
-// File: xIds/DbContext/XIdentityDbContext.cs
-public class XIdentityDbContext : IdentityDbContext
-{
-    // ... existing DbSets ...
-    
-    public DbSet<XApplication> Applications { get; set; }
-    public DbSet<XApiKey> ApiKeys { get; set; }
-    public DbSet<XApiKeyUsageLog> ApiKeyUsageLogs { get; set; }
-    
-    protected override void OnModelCreating(ModelBuilder modelBuilder)
-    {
-        base.OnModelCreating(modelBuilder);
-        
-        // Configure XApplication
-        modelBuilder.Entity<XApplication>(e => {
-            e.HasIndex(a => a.Name).IsUnique();
-            e.HasMany(a => a.ApiKeys)
-             .WithOne(k => k.Application)
-             .HasForeignKey(k => k.ApplicationId);
-        });
-        
-        // Configure XApiKey
-        modelBuilder.Entity<XApiKey>(e => {
-            e.HasIndex(k => k.KeyHash).IsUnique();
-            e.HasIndex(k => k.ExpiresAt);
-        });
-    }
-} -
- -

📌 گام ۱.۳: پیاده‌سازی XApplicationManager

-

یک کلاس جدید برای مدیریت برنامه‌ها و ApiKeyها مشابه الگوی XIdentityManager موجود:

- -
-// File: xIds/Interfaces/IXApplicationManager.cs
-public interface IXApplicationManager
-{
-    // Application CRUD
-    Task<XApplicationDto> CreateApplication(XApplicationDto item, string ownerId);
-    Task<XApplicationDto> UpdateApplication(Guid id, XApplicationDto item);
-    Task<bool> DeleteApplication(Guid id);
-    Task<XApplicationDto> GetApplication(Guid id);
-    Task<IEnumerable<XApplicationDto>> GetOwnerApplications(string ownerId);
-    
-    // ApiKey Management
-    Task<XApiKeyCreationResult> CreateApiKey(
-        Guid applicationId,
-        TimeSpan? expiration = null,
-        IEnumerable<string> scopes = null,
-        IEnumerable<string> allowedIPs = null,
-        int? rateLimit = null);
-    
-    Task<bool> RevokeApiKey(Guid apiKeyId, string revokedBy);
-    Task<XApiKeyDto> RotateApiKey(Guid apiKeyId, TimeSpan? newExpiration = null);
-    Task<IEnumerable<XApiKeyDto>> GetApplicationApiKeys(Guid applicationId);
-    
-    // Validation
-    Task<XApiKeyValidationResult> ValidateApiKey(string apiKey, string clientIP);
-} -
- -

📌 گام ۱.۴: تولید امن ApiKey

-

الگوی تولید کلید باید از نظر رمزنگاری امن باشد:

- -
-// File: xIds/Helpers/XApiKeyGenerator.cs
-public static class XApiKeyGenerator
-{
-    public static (string plainKey, string hash, string prefix) Generate()
-    {
-        // Generate 32 bytes of cryptographically secure random data
-        var randomBytes = new byte[32];
-        using (var rng = RandomNumberGenerator.Create())
-        {
-            rng.GetBytes(randomBytes);
-        }
-        
-        // Format: xapp_{base64url}
-        var plainKey = $"xapp_{Convert.ToBase64String(randomBytes)
-            .Replace("+", "-").Replace("/", "_").TrimEnd('=')}";
-        
-        // Hash with SHA256 for storage (never store plain key)
-        using (var sha256 = SHA256.Create())
-        {
-            var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
-            var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
-            
-            // Prefix for quick identification (first 12 chars)
-            var prefix = plainKey.Substring(0, 16) + "...";
-            
-            return (plainKey, hash, prefix);
-        }
-    }
-    
-    public static bool Verify(string plainKey, string storedHash)
-    {
-        using (var sha256 = SHA256.Create())
-        {
-            var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
-            var computedHash = BitConverter.ToString(hashBytes)
-                .Replace("-", "").ToLower();
-            return computedHash == storedHash;
-        }
-    }
-} -
- -
-✅ ویژگی‌های امنیتی این طراحی: -
    -
  • کلید ApiKey هرگز به‌صورت Plain Text ذخیره نمی‌شود (فقط Hash)
  • -
  • استفاده از RandomNumberGenerator برای تولید امن
  • -
  • پیشوند xapp_ برای شناسایی سریع نوع کلید
  • -
  • Prefix کوتاه برای نمایش در UI بدون افشای کلید کامل
  • -
-
-
-
- - -
-
-
۶
-
-

مرحله ۲: سرویس اعتبارسنجی ApiKey

-
Phase 2: ApiKey Validation Service
-
-
-
- -

📌 گام ۲.۱: طراحی XApiKeyValidator

-

این سرویس مسئولیت اعتبارسنجی کامل ApiKey را بر عهده دارد:

- -
-// File: xIds/Validators/XApiKeyValidator.cs
-public class XApiKeyValidator : IXApiKeyValidator
-{
-    private readonly XIdentityDbContext _dbContext;
-    private readonly IXIdentityConfiguration _config;
-    private readonly IMemoryCache _cache; // For rate limiting
-    
-    public async Task<XApiKeyValidationResult> ValidateAsync(
-        string apiKey, string clientIP, string requiredScope = null)
-    {
-        var result = new XApiKeyValidationResult();
-        
-        // Step 1: Compute hash of provided key
-        var hash = XApiKeyGenerator.ComputeHash(apiKey);
-        
-        // Step 2: Lookup in database
-        var keyEntity = await _dbContext.ApiKeys
-            .Include(k => k.Application)
-            .FirstOrDefaultAsync(k => k.KeyHash == hash);
-        
-        if (keyEntity == null)
-        {
-            result.IsValid = false;
-            result.Error = XException.InvalidApiKey;
-            return result;
-        }
-        
-        // Step 3: Check expiration
-        if (keyEntity.IsExpired)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApiKeyExpired;
-            return result;
-        }
-        
-        // Step 4: Check revocation
-        if (keyEntity.IsRevoked)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApiKeyRevoked;
-            return result;
-        }
-        
-        // Step 5: Check application active
-        if (!keyEntity.Application.IsActive)
-        {
-            result.IsValid = false;
-            result.Error = XException.ApplicationDisabled;
-            return result;
-        }
-        
-        // Step 6: Check IP whitelist
-        if (!string.IsNullOrEmpty(keyEntity.AllowedIPs))
-        {
-            var allowedIPs = keyEntity.AllowedIPs.Split(',');
-            if (!allowedIPs.Contains(clientIP))
-            {
-                result.IsValid = false;
-                result.Error = XException.IPNotAllowed;
-                return result;
-            }
-        }
-        
-        // Step 7: Check rate limit
-        if (!CheckRateLimit(keyEntity.Id, keyEntity.RateLimitPerMinute))
-        {
-            result.IsValid = false;
-            result.Error = XException.RateLimitExceeded;
-            return result;
-        }
-        
-        // Step 8: Check scope (if required)
-        if (!string.IsNullOrEmpty(requiredScope))
-        {
-            var scopes = JsonConvert.DeserializeObject<List<string>>(keyEntity.AllowedScopes);
-            if (!scopes.Contains(requiredScope))
-            {
-                result.IsValid = false;
-                result.Error = XException.InsufficientScope;
-                return result;
-            }
-        }
-        
-        // Step 9: Update LastUsedAt
-        keyEntity.LastUsedAt = DateTime.UtcNow;
-        await _dbContext.SaveChangesAsync();
-        
-        // Step 10: Build success result
-        result.IsValid = true;
-        result.ApplicationId = keyEntity.ApplicationId;
-        result.OwnerId = keyEntity.Application.OwnerId;
-        result.Scopes = JsonConvert.DeserializeObject<List<string>>(keyEntity.AllowedScopes);
-        
-        return result;
-    }
-} -
- -

📌 گام ۲.۲: پیاده‌سازی Rate Limiter

-
-private bool CheckRateLimit(Guid apiKeyId, int limitPerMinute)
-{
-    var cacheKey = $"ratelimit:{apiKeyId}";
-    var currentCount = _cache.GetOrCreate(cacheKey, entry => {
-        entry.SlidingExpiration = TimeSpan.FromMinutes(1);
-        return 0;
-    });
-    
-    if (currentCount >= limitPerMinute)
-        return false;
-    
-    _cache.Set(cacheKey, currentCount + 1, TimeSpan.FromMinutes(1));
-    return true;
-} -
-
-
- - -
-
-
۷
-
-

مرحله ۳: سرویس احراز هویت مبتنی بر ApiKey

-
Phase 3: ApiKey Authentication Service
-
-
-
- -

📌 گام ۳.۱: ایجاد Authentication Handler

-

برای یکپارچگی با ASP.NET Core Authentication، یک Handler جدید ایجاد می‌کنیم:

- -
-// File: xIdentityService/Authentication/XApiKeyAuthenticationHandler.cs
-public class XApiKeyAuthenticationHandler : AuthenticationHandler<XApiKeyAuthenticationOptions>
-{
-    public const string AuthenticationScheme = "XApiKey";
-    public const string HeaderName = "X-Api-Key";
-    
-    private readonly IXApiKeyValidator _validator;
-    
-    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
-    {
-        // Extract ApiKey from header
-        if (!Request.Headers.ContainsKey(HeaderName))
-            return AuthenticateResult.NoResult();
-        
-        var apiKey = Request.Headers[HeaderName].ToString();
-        var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
-        
-        // Validate ApiKey
-        var validationResult = await _validator.ValidateAsync(apiKey, clientIP);
-        
-        if (!validationResult.IsValid)
-            return AuthenticateResult.Fail(validationResult.Error.Message);
-        
-        // Build ClaimsPrincipal
-        var claims = new[]
-        {
-            new Claim(ClaimTypes.Name, validationResult.OwnerId),
-            new Claim("application_id", validationResult.ApplicationId.ToString()),
-            new Claim("auth_type", "apikey"),
-            new Claim(JwtClaimTypes.Scope, "apikey"),
-        };
-        
-        // Add scope claims
-        var scopeClaims = validationResult.Scopes
-            .Select(s => new Claim(JwtClaimTypes.Scope, s));
-        
-        var identity = new ClaimsIdentity(claims.Union(scopeClaims), AuthenticationScheme);
-        var principal = new ClaimsPrincipal(identity);
-        var ticket = new AuthenticationTicket(principal, AuthenticationScheme);
-        
-        return AuthenticateResult.Success(ticket);
-    }
-} -
- -

📌 گام ۳.۲: ثبت در Startup

-
-// File: xApi/Startup.cs - ConfigureServices
-services.AddAuthentication(options => {
-    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
-})
-.AddJwtBearer(/* existing config */)
-.AddScheme<XApiKeyAuthenticationOptions, XApiKeyAuthenticationHandler>(
-    XApiKeyAuthenticationHandler.AuthenticationScheme,
-    options => { });
-
-// Authorization policies for ApiKey
-services.AddAuthorization(options => {
-    options.AddPolicy("ApiKeyAccess", policy => {
-        policy.AddAuthenticationSchemes(XApiKeyAuthenticationHandler.AuthenticationScheme);
-        policy.RequireAuthenticatedUser();
-    });
-    
-    // Scope-based policies
-    options.AddPolicy("ApiKeyRead", policy => {
-        policy.AddAuthenticationSchemes(XApiKeyAuthenticationHandler.AuthenticationScheme);
-        policy.RequireClaim(JwtClaimTypes.Scope, "read", "write", "admin");
-    });
-}); -
- -

📌 گام ۳.۳: استفاده در Controllerها

-
-// Example: Supporting both JWT and ApiKey authentication
-[Authorize(Policy = "ApiKeyRead")]
-public class DataController : ControllerBase
-{
-    [HttpGet("items")]
-    public async Task<ActionResult> GetItems()
-    {
-        // Works with both JWT Bearer and X-Api-Key header
-        var userId = User.Identity.Name;
-        // ...
-    }
-} -
-
-
- - -
-
-
۸
-
-

مرحله ۴: API Endpoints

-
Phase 4: API Endpoints Design
-
-
-
- -

📌 طراحی Controller

-
-// File: xIds/Controllers/ApplicationController.cs
-[ApiController]
-[Route("api/v1/applications")]
-[Authorize(Policy = XPolicies.EnabledUser)]
-public class ApplicationController : XIBaseController
-{
-    // Application CRUD
-    [HttpPost]
-    public async Task<ActionResult<XApplicationDto>> Create(XApplicationDto model);
-    
-    [HttpGet]
-    public async Task<ActionResult<IEnumerable<XApplicationDto>>> GetMyApplications();
-    
-    [HttpPut("{id}")]
-    public async Task<ActionResult> Update(Guid id, XApplicationDto model);
-    
-    [HttpDelete("{id}")]
-    public async Task<ActionResult> Delete(Guid id);
-    
-    // ApiKey Management
-    [HttpPost("{appId}/apikeys")]
-    public async Task<ActionResult<XApiKeyCreationResponse>> CreateApiKey(
-        Guid appId, XCreateApiKeyRequest request);
-    
-    [HttpGet("{appId}/apikeys")]
-    public async Task<ActionResult<IEnumerable<XApiKeyDto>>> GetApiKeys(Guid appId);
-    
-    [HttpPost("apikeys/{id}/revoke")]
-    public async Task<ActionResult> RevokeApiKey(Guid id);
-    
-    [HttpPost("apikeys/{id}/rotate")]
-    public async Task<ActionResult<XApiKeyCreationResponse>> RotateApiKey(Guid id);
-} -
- -

📋 DTOهای مورد نیاز

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DTOکاربردفیلدهای کلیدی
XApplicationDtoنمایش برنامهId, Name, Description, Type, IsActive, CreatedOn
XCreateApplicationRequestدرخواست ساخت برنامهName, Description, Type
XApiKeyDtoنمایش ApiKey (بدون کلید کامل)Id, KeyPrefix, ExpiresAt, LastUsedAt, Scopes, IsActive
XCreateApiKeyRequestدرخواست ساخت ApiKeyExpirationMinutes, Scopes, AllowedIPs, RateLimit
XApiKeyCreationResponseپاسخ ساخت (فقط یکبار کلید کامل)ApiKey (plain), ExpiresAt, KeyPrefix
- -
-🔴 نکته امنیتی بسیار مهم: کلید ApiKey به‌صورت Plain Text فقط یکبار در پاسخ XApiKeyCreationResponse به کاربر نمایش داده می‌شود. پس از آن، فقط KeyPrefix قابل مشاهده است و کاربر در صورت فراموشی کلید، باید آن را Rotate کند. -
-
-
- - -
-
-
۹
-
-

جریان عملیات و سناریوها

-
Operational Flows & Scenarios
-
-
-
- -

🔄 سناریوی ۱: ایجاد برنامه و دریافت ApiKey

-
-
-
۱
-
-کاربر درخواست ایجاد برنامه را ارسال می‌کند -POST /api/v1/applications با payload شامل نام، توضیحات و نوع برنامه -
-
-
-
۲
-
-سیستم برنامه را ایجاد می‌کند -ذخیره XApplication با OwnerId = کاربر فعلی -
-
-
-
۳
-
-کاربر درخواست ApiKey می‌کند -POST /api/v1/applications/{appId}/apikeys با تنظیمات انقضا و scope -
-
-
-
۴
-
-سیستم ApiKey تولید و برمی‌گرداند -کلید Plain Text فقط یکبار نمایش داده می‌شود، Hash در DB ذخیره می‌شود -
-
-
- -

🔄 سناریوی ۲: استفاده از ApiKey در درخواست API

-
-
-
۱
-
-کلاینت درخواست API را ارسال می‌کند -Header: X-Api-Key: xapp_abc123... -
-
-
-
۲
-
-Authentication Handler کلید را استخراج می‌کند -XApiKeyAuthenticationHandler فعال می‌شود -
-
-
-
۳
-
-اعتبارسنجی کامل انجام می‌شود -بررسی انقضا، ابطال، IP whitelist، rate limit، scope -
-
-
-
۴
-
-ClaimsPrincipal ساخته می‌شود -با OwnerId، ApplicationId و Scopes -
-
-
-
۵
-
-درخواست به Controller هدایت می‌شود -Authorization policy بررسی و پاسخ ارسال می‌گردد -
-
-
- -

🔄 سناریوی ۳: چرخش کلید (Key Rotation)

-
-
-
۱
-
-کاربر درخواست چرخش کلید را می‌دهد -POST /api/v1/applications/apikeys/{id}/rotate -
-
-
-
۲
-
-کلید جدید تولید می‌شود -کلید قدیمی برای مدت grace period (مثلاً ۱ ساعت) فعال می‌ماند -
-
-
-
۳
-
-کلید جدید به کاربر داده می‌شود -کاربر کلید جدید را در برنامه خود جایگزین می‌کند -
-
-
-
۴
-
-پس از grace period، کلید قدیمی منقضی می‌شود -Background job کلیدهای قدیمی را غیرفعال می‌کند -
-
-
-
-
- - -
-
-
۱۰
-
-

الگوهای امنیتی و ملاحظات

-
Security Patterns & Considerations
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
الگوی امنیتیپیاده‌سازیاهمیت
Hashing کلیدSHA256 - کلید Plain Text هرگز ذخیره نمی‌شودحیاتی
HTTPS OnlyApiKey فقط از طریق HTTPS قابل ارسال استحیاتی
Rate Limitingبر اساس ApiKey و IP با MemoryCacheبالا
IP Whitelistمحدودسازی به IPهای مجازبالا
Scope Managementهر ApiKey scope مشخصی داردبالا
Audit Loggingثبت تمام استفاده‌ها در XApiKeyUsageLogمتوسط
Expirationمدت زمان محدود با قابلیت تمدیدبالا
Revocationامکان ابطال فوری در صورت نشتحیاتی
Key Rotationچرخش بدون downtime با grace periodمتوسط
One-time Displayکلید فقط یکبار به کاربر نمایش داده می‌شودبالا
- -
-🎯 یکپارچگی با OAuth2: این طراحی با الگوی OAuth2 Client Credentials Grant همخوانی کامل دارد. در واقع هر Application معادل یک OAuth2 Client و هر ApiKey معادل یک Client Secret است. در آینده می‌توان به‌راحتی این سیستم را به IdentityServer4 متصل کرد و از token endpoint آن برای تبدیل ApiKey به JWT استفاده نمود. -
- -

🔐 ملاحظات امنیتی تکمیلی

-
    -
  • ذخیره‌سازی: کلید ApiKey هرگز در Log یا Response بعد از ساخت ذخیره نمی‌شود
  • -
  • انتقال: فقط از طریق Header (X-Api-Key)، نه URL Query
  • -
  • طول کلید: حداقل ۲۵۶ بیت (۳۲ بایت) entropy
  • -
  • Brute Force Protection: پس از ۵ تلاش ناموفق، IP برای ۱۵ دقیقه block می‌شود
  • -
  • CORS: برای Endpoints حساس، CORS باید به‌دقت پیکربندی شود
  • -
-
-
- - -
-
-
۱۱
-
-

جمع‌بندی و گام‌های بعدی

-
Summary & Next Steps
-
-
-
- -

✅ خلاصه طراحی

-

این مستند یک راهکار کامل برای مدیریت ApiKey در پلتفرم xDashboard ارائه می‌دهد که شامل موارد زیر است:

-
    -
  • مدل داده کامل با ۳ Entity جدید (XApplication, XApiKey, XApiKeyUsageLog)
  • -
  • پیاده‌سازی امن تولید و ذخیره‌سازی کلید با SHA256
  • -
  • Authentication Handler یکپارچه با ASP.NET Core
  • -
  • سیستم Rate Limiting و IP Whitelist
  • -
  • امکان چرخش کلید بدون downtime
  • -
  • سیستم Audit Log کامل
  • -
  • یکپارچگی با OAuth2 برای توسعه آینده
  • -
- -

📋 گام‌های اجرایی پیشنهادی

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فازفعالیتزمان تخمینی
۱طراحی و تصویب مدل داده + Migration۱ روز
۲پیاده‌سازی XApplicationManager + XApiKeyGenerator۲ روز
۳پیاده‌سازی XApiKeyValidator + Rate Limiter۱ روز
۴پیاده‌سازی Authentication Handler۱ روز
۵طراحی و پیاده‌سازی API Endpoints۲ روز
۶تست امنیتی و Unit Test۲ روز
۷مستندسازی API و راهنمای کلاینت۱ روز
مجموع زمان تخمینی۱۰ روز کاری
- -
-

🎯 توصیه نهایی

-

این طراحی با رعایت کامل اصول امنیتی و انطباق با الگوهای موجود پروژه (IdentityServer4, XPolicies, XValidationProvider) آماده پیاده‌سازی است. پیشنهاد می‌شود فاز اول با حداقل نیازمندی‌های امنیتی (Hashing, HTTPS, Expiration, Revocation) شروع شود و قابلیت‌های پیشرفته (IP Whitelist, Rate Limiting, Audit Log) در فازهای بعدی اضافه گردند.

-
-💎 ارزش پیشنهادی:
-امنیت سطح Enterprise + یکپارچگی کامل با OAuth2 + مقیاس‌پذیری بالا + قابلیت ردیابی و حسابرسی کامل -
-
- -
-📞 گام بعدی: در صورت تأیید این طراحی، می‌توانیم پیاده‌سازی را با فاز ۱ (مدل داده و Migration) شروع کنیم. کدها دقیقاً مطابق الگوهای موجود پروژه (Partial Classes برای Manager، Validation با GroupValidationBuilder، و Exception Handling با XException) نوشته خواهند شد. -
-
-
- -
-این مستند محرمانه بوده و صرفاً جهت طراحی و پیاده‌سازی داخلی تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: ۱۲ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_28cb240e-d19e-453e-872d-b7ba14ecd418.html - - - - - - -معرفی ساختار محصول هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف - - - - -
- -
-
-
- -
-
-
شماره مستند: PROD-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- PRODUCT ARCHITECTURE OVERVIEW -

معرفی ساختار محصول هوش مصنوعی سازمانی

-

محصول در دست توسعه — رایان پرداز کاوش | معرفی به شرکت پارسا پلیمر شریف

-
-
- -
- -
- کارفرمای محترم، شرکت پارسا پلیمر شریف،
- این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش در دست توسعه است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌هایی مانند شرکت پارسا پلیمر پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی سازمان شما، مستلزم گفتگو و دریافت بازخورد از تیم فنی شماست و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.

- -

این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی مانند شرکت پارسا پلیمر شریف که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های سازمان شما و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.

- -
-
-
معماری
شش‌لایه
-
پایه طراحی محصول
-
-
-
MCP
محور
-
توسعه‌پذیری نامحدود
-
-
-
مدل
لوکال
-
حاکمیت داده و محرمانگی
-
-
- -
- نکته کلیدی: این مستند، معرفی ساختار محصول در دست توسعه است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی شرکت پارسا پلیمر شریف قرار گیرند. -
-
-
- -
-
-
۲
-
-

معماری محصول در دست توسعه

-
Product Architecture Under Development
-
-
-
-

محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت‌های پیش‌بینی‌شده در محصولوضعیت توسعه
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه APIدر دست توسعه
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌هادر دست توسعه
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیدر دست توسعه
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینهدر دست توسعه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتیدر دست توسعه
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرفدر دست توسعه
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگیدر دست توسعه
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطادر دست توسعه
- -
- 💡 نکته: معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف، از جمله شرکت پارسا پلیمر شریف، را فراهم کند. -
-
-
- -
-
-
۳
-
-

ساختار محصول: سامانه ایجنت‌محور سازمانی

-
Product Structure: Enterprise Agentic System
-
-
-
-

هسته محصول در دست توسعه، یک موتور ایجنت است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت پیش‌بینی‌شده در ساختار محصول
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
- -
- 💡 نکته: قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی شرکت پارسا پلیمر شریف بررسی و با نیازمندی‌های سازمان شما تطبیق داده شود. -
-
-
- -
-
-
۴
-
-

توسعه‌پذیری از طریق MCP

-
Extensibility via MCP
-
-
-
-

MCP (Model Context Protocol) در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و به سامانه اضافه گردد.

- -
- تأکید معماری: از منظر ساختار محصول، محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی، از جمله نیازهای محتمل شرکت پارسا پلیمر شریف، هم‌راستا شود. -
- -

نمونه قابلیت‌های قابل افزودن با MCP:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
حوزه سازمانینمونه MCP Serverکاربرد بالقوه
منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
- -
- ✓ نتیجه: ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد. -
-
-
- -
-
-
۵
-
-

حاکمیت داده و رویکرد مدل‌های لوکال

-
Data Governance & Local Model Approach
-
-
-
-

در ساختار محصول، حاکمیت داده به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

- -
- ⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس: -
    -
  • خروج داده‌های حساس از مرز سازمان
  • -
  • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
  • -
  • احتمال استفاده از داده برای آموزش مدل‌های بعدی
  • -
  • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
  • -
  • عدم انطباق با سیاست‌های محرمانگی سازمانی
  • -
-
- -

رویکرد پیش‌بینی‌شده در ساختار محصول:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
تصمیمرویکرد در ساختار محصول
مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
داده حساسعدم خروج از مرز سازمان
مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
آموزش مدلعدم استفاده از داده سازمان برای آموزش مدل‌های خارجی
استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
- -
- ✓ نتیجه: در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا، از جمله شرکت پارسا پلیمر شریف، مناسب باشد. -
-
-
- -
-
-
۶
-
-

کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

-
Agent Access Control & Tool Restriction
-
-
-
-

در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

- -
- - -
- -

این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

- -
- نکته حساس: ساختار محصول از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده، از جمله شرکت پارسا پلیمر شریف، مناسب باشد. -
-
-
- -
-
-
۷
-
-

دفاع لایه‌ای برای حفظ محرمانگی

-
Layered Defense for Confidentiality
-
-
-
-

در ساختار محصول، برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایهکنترلهدف
لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
- -
- ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود. -
- -
- ✓ رویکرد ساختاری: دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود. -
-
-
- -
-
-
۸
-
-

مثال جریان کار: یک درخواست، دو ایجنت

-
Workflow Example: One Request, Two Agents
-
-
-
-

برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

- -
-

«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

-
— درخواست نمونه واحد کارمند
-
- -

این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مرحلهمسئولاقدامکنترل دسترسی
۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
- -

نحوه اعمال کنترل دسترسی در این سناریو:

- -
    -
  • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
  • -
  • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
  • -
  • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
  • -
  • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
  • -
  • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
  • -
- -
- 💡 نتیجه مثال: ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
-
-
- -
-
-
۹
-
-

قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی

-
Product Capabilities vs. Common Organizational Needs
-
-
-
-

ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، مستلزم گفتگوی فنی با تیم ارزیابی شماست.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
نیاز رایج سازمانیقابلیت پیش‌بینی‌شده در ساختار محصول
دستیار هوشمند و ایجنت تصمیم‌گیرندهموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
مدیریت دسترسی کاربران و واحدهای سازمانیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
شفافیت مصرف و هزینهداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API
تعامل کاربری و تولید گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
حاکمیت داده و محرمانگی اطلاعاتمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
پیاده‌سازی، آموزش و پشتیبانینقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
عملکرد پایدار و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
- -
- ✓ نتیجه: ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، آماده دریافت و بررسی نیازمندی‌های تیم فنی شما هستیم. -
-
-
- -
-
-
۱۰
-
-

وضعیت توسعه محصول و گام بعدی

-
Development Status & Next Step
-
-
-
-

وضعیت فعلی: محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، در دست توسعه است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:

- -
-
-
-
فاز A: هسته ایجنت و رابط پایه
-

درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه

-
-
-
-
-
-
فاز B: ابزارها، RAG و منابع دانش
-

Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه

-
-
-
-
-
-
فاز C: حاکمیت داده و کنترل دسترسی
-

موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه

-
-
-
-
-
-
فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
-

تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه

-
-
-
-
-
-
فاز E: Cross-Platform و آماده‌سازی محصول
-

نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه

-
-
-
-
- -

گام بعدی پیشنهادی:

- -
    -
  • - برگزاری جلسه معرفی و گفتگوی فنی - معرفی ساختار محصول و دریافت بازخورد از تیم فنی شرکت پارسا پلیمر شریف -
  • -
  • - دریافت نیازمندی‌های اختصاصی سازمان - شناخت دقیق نیازهای شرکت پارسا پلیمر شریف برای تطبیق محصول -
  • -
  • - ارائه سناریوی نمونه Agent - نمایش ساختار ایجنت بر اساس معماری محصول -
  • -
  • - بررسی امکان اجرای پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
  • -
  • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه همکاری و نیازمندی‌های سازمانی -
  • -
- -
- 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
-
-
- -
-
-
۱۱
-
-

جمع‌بندی و پیشنهاد نهایی

-
Final Summary & Recommendation
-
-
-
-

این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ویژگیرویکرد ساختار محصول
معماری پایهشش لایه + دو محور عرضی
توسعه‌پذیری MCPبدون محدودیت معماری
حاکمیت دادهمدل لوکال (حاکمیت کامل)
کنترل دسترسی ایجنتتا سطح ابزار و رکورد
دفاع محرمانگیشش لایه مستقل
وضعیت توسعهدر دست توسعه
- -
-

🎯 پیشنهاد نهایی

-

ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.

-

توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.

-
- 💎 ارزش پیشنهادی ساختار محصول:
- معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای -
-
- -
- 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
-
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2a48ed4e-5c7a-406a-97d7-044165d6365c.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
-
-
-
- -
-
-
شماره مستند: TECH-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: ۲۸ مهر ۱۴۰۵
-
طبقه‌بندی: داخلی / فنی
-
-
-
-TECHNICAL REVIEW & GUIDE -

بررسی فنی و راهنمای جامع ابزار AirLLM

-

تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

-
-
- -
-
-همکاران و ذینفعان محترم،
-این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

-
-نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
-
-
- -
-
-
۲
-
-

معماری و مکانیزم عملکرد

-
Architecture & Mechanism
-
-
-
-

مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

-
-گام ۱: تجزیه و ذخیره‌سازی اولیه
-در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

-گام ۲: بارگذاری پویا در GPU
-در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

-گام ۳: محاسبه و انتقال حالت (State)
-پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
-
-💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
-
-
- -
-
-
۳
-
-

مدل‌های پشتیبانی‌شده و مصرف حافظه

-
Supported Models & VRAM Consumption
-
-
-
-

این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
Llama 3.x 70B (full precision)70B~۴ گیگابایت
DeepSeek-V3671B~۱۲ گیگابایت
-
-
- -
-
-
۴
-
-

راهنمای گام‌به‌گام پیاده‌سازی

-
Step-by-Step Implementation Guide
-
-
-
-

برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

-
-پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
-

گام ۱: نصب کتابخانه

-
pip install airllm
- -

گام ۲: مقداردهی اولیه مدل

-
from airllm import AutoModel
-
-# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
-model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
-
-# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
-# model = AutoModel.from_pretrained("model-name", compression='4bit')
-
- -

گام ۳: آماده‌سازی ورودی و اجرای استنتاج

-
MAX_LENGTH = 128
-input_text = ['What is the capital of United States?']
-
-input_tokens = model.tokenizer(
-    input_text,
-    return_tensors="pt",
-    return_attention_mask=False,
-    truncation=True,
-    max_length=MAX_LENGTH,
-    padding=False
-)
-
-generation_output = model.generate(
-    input_tokens['input_ids'].cuda(),
-    max_new_tokens=20,
-    use_cache=True,
-    return_dict_in_generate=True
-)
-
-output = model.tokenizer.decode(generation_output.sequences[0])
-print(output)
-
-
-
- -
-
-
۵
-
-

جمع‌بندی و توصیه‌های فنی

-
Conclusion & Technical Recommendations
-
-
-
-

با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
ارزش خالص فنی—بسیار بالاتر
- -
-

🎯 توصیه نهایی معماری

-

با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

-

این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

-
-💎 ارزش پیشنهادی:
-حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
-
-
-
- -
-این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
-
- -
- - -
شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
-
-
- - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2e627fe4-93a8-4d6f-8f18-38eb87b1587b.html - - - - - - -پروپوزال راهکار هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف - - - - -
- -
-
-
- -
-
-
شماره مستند: PROP-1405-002
-
نسخه: ۱.۰
-
تاریخ تهیه: مهر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- PROPOSAL & SOLUTION -

پروپوزال راهکار هوش مصنوعی سازمانی

-

سامانه ایجنت‌محور با توسعه‌پذیری MCP و حاکمیت داده درون‌سازمانی

-
-
- -
- -
- کارفرمای محترم، شرکت پارسا پلیمر شریف،
- این مستند در پاسخ به درخواست رسمی شما (REQ-1405-001) تهیه شده است و راهکار پیشنهادی ما را به‌عنوان محصولی که معماری کلان آن در سازمان ما طراحی و پیاده‌سازی شده است معرفی می‌نماید. تمرکز این پروپوزال بر چهار محور اساسی است: ایجنت قابل‌آزمون، توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت. هدف، ارائه شفافیت کامل و اثبات عملی قابلیت‌ها در جلسه دمو و پایلوت محدود است. -
- -
-
-
۱
-
-

خلاصه اجرایی

-
Executive Summary
-
-
-
-

درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است. تیم ارزیابی شما با مفاهیمی مانند Agent در برابر Assistant، Human-in-the-loop، RAG، مدیریت دسترسی تا سطح سند/رکورد و حاکمیت داده کاملاً آشناست. بنابراین، پیشنهاد ما بر «ادعا» استوار نیست؛ بر قابلیت اثبات عملی استوار است.

- -

محصول پیشنهادی، یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن در سازمان ما طراحی و پیاده‌سازی شده و آماده ارائه در جلسه دمو و اجرای پایلوت محدود است. این محصول با تمرکز بر چهار محور کلیدی طراحی شده است:

- -
-
-
ایجنت
قابل‌آزمون
-
برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح
-
-
-
MCP
نامحدود
-
توسعه‌پذیری بدون محدودیت معماری
-
-
-
مدل
لوکال
-
حاکمیت داده و محرمانگی کامل
-
-
- -
- نتیجه کلیدی: آنچه به سازمان شما ارائه می‌شود، نه یک طرح مفهومی، بلکه یک محصول عملیاتی است که معماری شش‌لایه + دو محور عرضی آن پیاده‌سازی شده و آماده اثبات در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) می‌باشد. -
-
-
- -
-
-
۲
-
-

جایگاه پیشنهاد: محصول پیاده‌سازی‌شده، نه طرح مفهومی

-
Implemented Product vs. Conceptual Design
-
-
-
-

نکته متمایز این پیشنهاد آن است که معماری مطرح‌شده در مستندات فنی شما (ARCH-1405-001)، در سازمان ما به‌عنوان یک محصول طراحی و پیاده‌سازی شده است. این یعنی:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
شاخصطرح مفهومی (رایج در بازار)محصول پیاده‌سازی‌شده (پیشنهاد ما)
وضعیت معماریروی کاغذ و در مرحله طراحیطراحی و پیاده‌سازی شده
قابلیت اثبات عملیمحدود به ادعا و اسلایدقابل نمایش در جلسه دمو
ریسک پیاده‌سازیبالا (عدم اطمینان از تحقق)حداقل (محصول موجود است)
زمان تحویلطولانی (چرخه کامل توسعه)کوتاه (سفارشی‌سازی و استقرار)
نتیجه نهاییریسک بالا و زمان طولانیاطمینان بالا و تحویل سریع
- -
- ✓ مزیت کلیدی: شما با یک محصول زنده و آزمون‌پذیر مواجه هستید، نه با وعده‌های آینده. تمام قابلیت‌های مطرح‌شده در این پروپوزال، امروز در سازمان ما قابل نمایش و آزمون هستند. -
-
-
- -
-
-
۳
-
-

محصول پیشنهادی: سامانه ایجنت‌محور سازمانی

-
Proposed Product: Enterprise Agentic System
-
-
-
-

محصول ما یک چت‌بات ساده نیست. هسته محصول، یک موتور ایجنت است که هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایه معماریقابلیت در محصول پیشنهادی
لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
- -
- 💡 نکته: تمام لایه‌های فوق در محصول ما پیاده‌سازی شده‌اند و در جلسه دمو به‌صورت عملی قابل نمایش هستند. این ادعا با اجرای سناریوی چندمرحله‌ای Agent و آزمون‌های دسترسی، اثبات خواهد شد. -
-
-
- -
-
-
۴
-
-

توسعه‌پذیری نامحدود از طریق MCP

-
Unlimited Extensibility via MCP
-
-
-
-

MCP (Model Context Protocol) در محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع استفاده می‌شود. هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و بدون تغییر در هسته محصول به سامانه اضافه گردد.

- -
- تأکید معماری: از منظر معماری محصول، هیچ محدودیتی برای افزودن قابلیت از طریق MCP وجود ندارد. محدودیت تنها از جنس سیاست سازمانی و مجوزهای دسترسی است، نه از جنس معماری. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. -
- -

نمونه قابلیت‌های قابل افزودن با MCP:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
حوزه سازمانینمونه MCP Serverکاربرد پیشنهادی
منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
- -
- ✓ نتیجه: توسعه‌پذیری محصول از طریق MCP، عملاً نامحدود است. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود — بدون نیاز به تغییر در هسته محصول. -
-
-
- -
-
-
۵
-
-

حاکمیت داده و ضرورت مدل‌های لوکال

-
Data Governance & Local Model Necessity
-
-
-
-

در سناریوی شرکت پارسا پلیمر شریف — با اطلاعات حساس فرمولاسیون، مشتریان، فرایندها و اسناد سازمانی — استفاده از مدل‌های آنلاین، ذاتاً با حاکمیت داده و محرمانگی در تناقض است. زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

- -
- ⚠️ ریسک مدل‌های آنلاین: -
    -
  • خروج داده‌های حساس از مرز سازمان
  • -
  • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
  • -
  • احتمال استفاده از داده برای آموزش مدل‌های بعدی
  • -
  • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
  • -
  • عدم انطباق با سیاست‌های محرمانگی سازمانی
  • -
-
- -

معماری پیشنهادی حاکمیت داده:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
تصمیمپیاده‌سازی در محصول
مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
داده حساسهرگز از مرز سازمان خارج نمی‌شود
مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
آموزش مدلداده سازمان برای آموزش مدل‌های خارجی استفاده نمی‌شود
استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
- -
- ✓ نتیجه: در سناریوی پیشنهادی، حاکمیت داده نه یک ادعا، بلکه یک سیاست اجرایی در معماری محصول است. مدل لوکال، پیش‌فرض است و داده حساس سازمان هرگز از مرز آن خارج نمی‌شود. -
-
-
- -
-
-
۶
-
-

کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

-
Agent Access Control & Tool Restriction
-
-
-
-

محصول ما کنترل دسترسی را تنها به رابط کاربری محدود نمی‌کند. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

- -
- - -
- -

این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

- -
- نکته حساس: پشتیبانی از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) در محصول ما، کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن می‌سازد. این دقیقاً پاسخ به نیازمندی محور ۲ RFP شماست. -
-
-
- -
-
-
۷
-
-

دفاع لایه‌ای برای حفظ محرمانگی

-
Layered Defense for Confidentiality
-
-
-
-

محصول ما برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای را پیاده‌سازی کرده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
لایهکنترلهدف
لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
- -
- ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این دقیقاً پاسخ به آزمون نفوذ دسترسی کارفرماست. -
- -
- ✓ قابلیت اثبات: در جلسه دمو، پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت مطرح خواهد شد تا نشان داده شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، مسدود خواهد شد. -
-
-
- -
-
-
۸
-
-

مثال جریان کار: یک درخواست، دو ایجنت

-
Workflow Example: One Request, Two Agents
-
-
-
-

برای روشن‌تر شدن کنترل دسترسی در محصول، یک سناریوی واقعی را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

- -
-

«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

-
— درخواست واحد کارمند
-
- -

این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. محصول ما این درخواست را به‌صورت زیر پردازش می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
مرحلهمسئولاقدامکنترل دسترسی
۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
- -

نحوه اعمال کنترل دسترسی در این سناریو:

- -
    -
  • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
  • -
  • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
  • -
  • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
  • -
  • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
  • -
  • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
  • -
- -
- 💡 نتیجه مثال: محصول ما می‌تواند یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
-
-
- -
-
-
۹
-
-

انطباق با محورهای RFP شرکت پارسا پلیمر شریف

-
Compliance with RFP Requirements
-
-
-
-

جدول زیر نشان می‌دهد محصول پیشنهادی، چگونه به هر یک از هفت محور RFP شما پاسخ می‌دهد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
محور RFPپاسخ محصول
محور ۱: ماهیت ایجنتموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
محور ۲: دسترسیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
محور ۳: پلن و مصرفداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، API
محور ۴: رابط و گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
محور ۵: حاکمیت دادهمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
محور ۶: پیاده‌سازی و آموزشنقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
محور ۷: عملکرد و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
- -
- ✓ نتیجه: محصول پیشنهادی، به‌صورت سیستماتیک به تمام هفت محور RFP شما پاسخ می‌دهد. این پاسخ‌ها نه ادعای مکتوب، بلکه قابلیت‌های پیاده‌سازی‌شده و قابل‌آزمون هستند. -
-
-
- -
-
-
۱۰
-
-

وضعیت بلوغ محصول و گام بعدی

-
Product Maturity & Next Step
-
-
-
-

وضعیت فعلی: معماری مطرح‌شده در سازمان ما طراحی و پیاده‌سازی شده و به‌عنوان محصول قابل ارائه درآمده است. فازهای کلیدی محصول شامل موارد زیر است:

- -
-
-
-
فاز A: هسته ایجنت و رابط پایه
-

درگاه مدل، موتور ایجنت، رابط Blazor، احراز هویت — پیاده‌سازی شده

-
-
-
-
-
-
فاز B: ابزارها، RAG و منابع دانش
-

Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — پیاده‌سازی شده

-
-
-
-
-
-
فاز C: حاکمیت داده و کنترل دسترسی
-

موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — پیاده‌سازی شده

-
-
-
-
-
-
فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
-

تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — پیاده‌سازی شده

-
-
-
-
-
-
فاز E: Cross-Platform و آماده‌سازی محصول
-

نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — پیاده‌سازی شده

-
-
-
-
- -

گام بعدی پیشنهادی:

- -
    -
  • - برگزاری جلسه معرفی و دموی فنی - نمایش عملی محصول و پاسخ به سؤالات فنی تیم ارزیابی -
  • -
  • - اجرای سناریوی چندمرحله‌ای Agent - در محیط آزمایشی، شامل ابزار، خطا و مداخله انسانی -
  • -
  • - اجرای آزمون نفوذ دسترسی - با حساب‌های متفاوت و تلاش برای دور زدن مجوزها -
  • -
  • - ارائه برنامه پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
  • -
  • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه پایلوت و نیازمندی‌های سازمانی -
  • -
- -
- 📞 گام بعدی: در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات محصول، اجرای دموی عملی و ارائه برنامه پایلوت محدود هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد. -
-
-
- -
-
-
۱۱
-
-

جمع‌بندی و پیشنهاد نهایی

-
Final Summary & Recommendation
-
-
-
-

محصول پیشنهادی ما برای شرکت پارسا پلیمر شریف، یک سامانه هوش مصنوعی سازمانی آماده ارائه است که معماری آن در سازمان ما طراحی و پیاده‌سازی شده است. ویژگی‌های متمایز این پیشنهاد:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ویژگیطرح مفهومی (رایج)محصول پیشنهادی ما
وضعیت پیاده‌سازیروی کاغذپیاده‌سازی شده
توسعه‌پذیری MCPمحدود یا نامشخصنامحدود از منظر معماری
حاکمیت دادهمدل آنلاین (ریسک محرمانگی)مدل لوکال (حاکمیت کامل)
کنترل دسترسی ایجنتمحدود به رابط کاربریتا سطح ابزار و رکورد
دفاع محرمانگییک لایهشش لایه مستقل
قابلیت اثباتادعای مکتوبدموی عملی و آزمون‌پذیر
ارزش خالص ایجاد شده—بسیار بالاتر
- -
-

🎯 پیشنهاد نهایی

-

با توجه به تحلیل‌های انجام‌شده، محصول پیشنهادی ما نه یک طرح مفهومی، بلکه یک سامانه پیاده‌سازی‌شده و آزمون‌پذیر است که به تمام محورهای RFP شما پاسخ می‌دهد.

-

توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این پیشنهاد هستند.

-
- 💎 ارزش پیشنهادی:
- ایجنت قابل‌آزمون + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای + آمادگی پایلوت -
-
- -
- 📞 گام بعدی: در صورت تأیید این پروپوزال، آماده ارائه نسخه تفصیلی پیشنهاد فنی و تجاری، سناریوی نمونه Agent برای جلسه دمو، و برنامه زمان‌بندی پایلوت هستم. جلسه فنی پیشنهادی در اسرع وقت قابل برگزاری است. -
-
-
- -
- این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
- -
- -
- - -
تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
-
- -
- - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_3096683f-c9d2-4ee3-aa17-f6d2100104f0.html - - - - - - -نگاشت نقشه راه دانش فنی به roadmap.sh | سامانه هوش مصنوعی سازمانی - - - - -
- -
-
-
- -
-
-
شماره مستند: MAP-1405-001
-
نسخه: ۱.۰
-
تاریخ تهیه: آذر ۱۴۰۵
-
طبقه‌بندی: محرمانه
-
-
- -
- ROADMAP.SH MAPPING -

نگاشت نقشه راه دانش فنی به roadmap.sh

-

سامانه هوش مصنوعی سازمانی — از معماری تا محصول

-
-
- -
- -
- خلاصه مدیریتی،
- این مستند، نگاشت نقشه راه دانش فنی سامانه هوش مصنوعی سازمانی (مستند ROAD-1405-001) به نقشه‌های راه موجود در سایت roadmap.sh را ارائه می‌دهد. هدف، استفاده از منابع آموزشی جامعه‌محور و شناخته‌شده این سایت به‌عنوان ستون فقرات آموزشی برای هر فاز نقشه راه است. در این نگاشت، مشخص می‌شود هر فاز از نقشه راه دانش فنی، با کدام نقشه(های) راه roadmap.sh پوشش داده می‌شود، چه شکاف‌هایی وجود دارد و چگونه باید تکمیل شود. رویکرد نگاشت، فارغ از سکو و مبتنی بر مفاهیم و الگوها است. -
- -
-
-
۱
-
-

معرفی roadmap.sh و رویکرد نگاشت

-
About roadmap.sh & Mapping Approach
-
-
-
-

roadmap.sh یکی از محبوب‌ترین منابع جامعه‌محور برای نقشه‌های راه مهارت‌های فنی است که توسط صدها هزار توسعه‌دهنده در ماه استفاده می‌شود. این سایت مجموعه‌ای از نقشه‌های راه برای نقش‌های مختلف (Backend، Frontend، DevOps، AI Engineer، Cyber Security، Software Architect و...) ارائه می‌دهد که هر یک شامل موضوعات، منابع و مسیر یادگیری است.

- -
-
-
◇
-
فارغ از سکو
-

در استفاده از نقشه‌های راه، تمرکز بر مفاهیم و الگوهاست، نه ابزارهای خاص.

-
-
-
◈
-
ستون فقرات آموزشی
-

roadmap.sh چارچوب کلی می‌دهد؛ تکمیل با منابع تخصصی در بخش‌های دارای شکاف.

-
-
-
▤
-
نگاشت فاز به نقشه
-

هر فاز از ROAD-1405-001 به یک یا چند نقشه راه roadmap.sh نگاشت می‌شود.

-
-
-
✓
-
حفظ خروجی قابل‌آزمون
-

خروجی‌های قابل‌آزمون (Deliverable) هر فاز، مبنای ارزیابی پیشرفت باقی می‌مانند.

-
-
- -
- اصل حاکم: roadmap.sh به‌عنوان نقشه راه آموزشی استفاده می‌شود، نه به‌عنوان نقشه راه محصول. یعنی موضوعات آن برای کسب دانش فنی تیم به کار می‌رود، اما خروجی‌های قابل‌آزمون و الزامات کارفرما (REQ-1405-001) همچنان معیار اصلی پیشرفت هستند. -
-
-
- -
-
-
۲
-
-

نمای کلی نگاشت

-
Mapping Overview
-
-
-
-

جدول زیر، نگاشت کلی هفت فاز نقشه راه دانش فنی به نقشه‌های راه roadmap.sh را نشان می‌دهد:

- -
-
-
۷
-
فاز نقشه راه
-
-
-
۶
-
نقشه راه roadmap.sh
-
-
-
۱
-
شکاف اصلی (ایجنت)
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فاز ROAD-1405-001نقشه(های) راه roadmap.shدرجه پوششنیاز به تکمیل
فاز ۱: مبانی سیستم‌ها و دادهBackend Developer (بخش‌های ابتدایی)بالاجزئی (مدیریت کلید، رمزنگاری پیشرفته)
فاز ۲: مبانی مهندسی نرم‌افزارSoftware Design and Architectureبالاجزئی (Hexagonal، آزمون‌پذیری)
فاز ۳: مبانی هوش مصنوعی و مدل‌هاAI Engineerبالامتوسط (ارزیابی مدل، حاکمیت AI)
فاز ۴: معماری سیستم‌های توزیع‌شدهSystem Designبالامتوسط (BPMN 2.0، Event Sourcing)
فاز ۵: معماری ایجنت و ارکستراسیونAI Engineer (پیشرفته) + Software Architectپایینقابل توجه (منابع تخصصی ایجنت)
فاز ۶: امنیت، حاکمیت داده و انطباقCyber Securityبالامتوسط (OWASP LLM، ISO 42001)
فاز ۷: معماری کلان، محصول و عملیاتDevOps + Software Architectمتوسطمتوسط (مدیریت محصول، ADR)
- -
- 💡 نکته: بیشترین شکاف در فاز ۵ (معماری ایجنت) است. roadmap.sh در نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است. -
-
-
- -
-
-
۳
-
-

نگاشت تفصیلی فاز به نقشه راه

-
Detailed Phase-to-Roadmap Mapping
-
-
-
-

در ادامه، هر فاز به‌صورت تفصیلی نگاشت شده است؛ شامل موضوعات پوشش‌داده‌شده، شکاف‌ها و منابع تکمیلی پیشنهادی:

- - -
-
-
۱
-
-

مبانی سیستم‌ها و داده

-
Phase 1 — Foundations of Systems & Data
-
-
←
-
Backend Developer
-
-
-

نقشه راه Backend Developer در roadmap.sh، مبانی اینترنت، پروتکل HTTP، پایگاه‌های داده، مدل داده و مبانی امنیت را پوشش می‌دهد که با فاز ۱ نقشه راه دانش فنی هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مبانی اینترنت و DNS
  • -
  • HTTP/HTTPS و REST
  • -
  • پایگاه‌های داده رابطه‌ای و NoSQL
  • -
  • مدل‌سازی داده
  • -
  • مبانی احراز هویت
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • مدیریت کلید پیشرفته (NIST SP 800-57)
  • -
  • رمزنگاری نامتقارن و امضای دیجیتال
  • -
  • Data Lake و Data Warehouse
  • -
  • مدل تهدید پایه
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- RFC 8446 (TLS 1.3) - NIST SP 800-57 - ISO/IEC 27001 (مبانی) -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • نقشه مفهومی داده سازمان + سند مدل تهدید پایه
  • -
-
-
- - -
-
-
۲
-
-

مبانی مهندسی نرم‌افزار

-
Phase 2 — Software Engineering Foundations
-
-
←
-
Software Design and Architecture
-
-
-

نقشه راه Software Design and Architecture، الگوهای طراحی، اصول SOLID، معماری تمیز و جداسازی دغدغه‌ها را پوشش می‌دهد که با فاز ۲ هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • اصول SOLID
  • -
  • الگوهای طراحی (GoF)
  • -
  • معماری لایه‌ای و MVC
  • -
  • Separation of Concerns
  • -
  • مبانی آزمون‌پذیری
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • معماری Hexagonal (Ports & Adapters)
  • -
  • Test Double (Mock، Stub، Fake)
  • -
  • Contract Testing
  • -
  • ADR (Architecture Decision Records)
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- Clean Architecture (Robert C. Martin) - Hexagonal Architecture (Alistair Cockburn) - ISO/IEC 25010 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند اصول و الگوهای منتخب + نمونه اولیه ساختار Hexagonal
  • -
-
-
- - -
-
-
۳
-
-

مبانی هوش مصنوعی و مدل‌ها

-
Phase 3 — AI & Model Foundations
-
-
←
-
AI Engineer
-
-
-

نقشه راه AI Engineer در roadmap.sh، مبانی LLM، Prompt Engineering، RAG، پایگاه‌های داده برداری و ارزیابی مدل‌ها را پوشش می‌دهد. این نقشه راه، هسته لایه هوش (L4) معماری را پوشش می‌دهد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مبانی مدل‌های زبانی
  • -
  • Prompt Engineering
  • -
  • RAG و Vector Database
  • -
  • Function Calling
  • -
  • ارزیابی کیفیت پاسخ
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • NIST AI RMF و ISO 42001
  • -
  • Hallucination Detection پیشرفته
  • -
  • Bias و Fairness
  • -
  • سیاست دسترسی به مدل‌های جدید
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- NIST AI RMF - ISO/IEC 42001 - Attention Is All You Need -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند ارزیابی مدل‌ها + نمونه اولیه RAG
  • -
-
-
- - -
-
-
۴
-
-

معماری سیستم‌های توزیع‌شده

-
Phase 4 — Distributed Systems Architecture
-
-
←
-
System Design
-
-
-

نقشه راه System Design، مباحث مقیاس‌پذیری، دسترس‌پذیری، الگوهای توزیع‌شده (CQRS، Event-Driven) و trade-offها را پوشش می‌دهد که با فاز ۴ هم‌پوشانی بالایی دارد.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • مقیاس‌پذیری و Load Balancing
  • -
  • Caching Strategies
  • -
  • Event-Driven Architecture
  • -
  • CQRS و Event Sourcing (مفهومی)
  • -
  • Circuit Breaker و Retry
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • BPMN 2.0 (برای مدل‌سازی فرایند)
  • -
  • OpenTelemetry (مشاهده‌پذیری)
  • -
  • Saga Pattern پیشرفته
  • -
  • Idempotency و Distributed Locking
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- Enterprise Integration Patterns - Release It! (Michael Nygard) - OpenTelemetry Spec - BPMN 2.0 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند الگوهای معماری منتخب + نقشه BPMN2 تکمیلی
  • -
-
-
- - -
-
-
۵
-
-

معماری ایجنت و ارکستراسیون

-
Phase 5 — Agent Architecture & Orchestration
-
-
←
-
AI Engineer + Software Architect
-
-
-

این فاز، بیشترین شکاف را در roadmap.sh دارد. نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. نقشه Software Architect نیز دید کلان می‌دهد اما تخصصی ایجنت نیست.

- -
- ⚠️ شکاف اصلی: roadmap.sh معماری ایجنت (Agent Architecture) را به‌طور عمیق پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است: مقالات علمی (ReAct، Reflexion، Plan-and-Execute)، مستندات پروتکل‌ها (MCP)، و منابع تخصصی طراحی ایجنت. -
- -
-
-
موضوعات پوشش‌داده‌شده (جزئی)
-
    -
  • مفاهیم پایه AI Agent
  • -
  • Function Calling
  • -
  • Tool Use (مقدماتی)
  • -
  • حافظه و زمینه
  • -
-
-
-
موضوعات نیازمند منابع تخصصی
-
    -
  • الگوهای برنامه‌ریزی (ReAct، Reflexion)
  • -
  • Tool Selection Strategies
  • -
  • Human-in-the-loop Patterns
  • -
  • Multi-Agent Orchestration
  • -
  • ارزیابی ایجنت (Task Success Rate)
  • -
  • Guardrails و Kill Switch
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- ReAct (Yao et al.) - Reflexion (Shinn et al.) - Model Context Protocol (MCP) - NIST AI RMF (کنترل) -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سناریوی نمونه Agent (قابل ارائه در جلسه دمو) + چارچوب ارزیابی ایجنت
  • -
-
-
- - -
-
-
۶
-
-

امنیت، حاکمیت داده و انطباق

-
Phase 6 — Security, Data Governance & Compliance
-
-
←
-
Cyber Security
-
-
-

نقشه راه Cyber Security در roadmap.sh، مباحث IAM (Identity & Access Management)، رمزنگاری، امنیت وب و OWASP را پوشش می‌دهد که با فاز ۶ هم‌پوشانی بالایی دارد و مستقیماً به محور عرضی حاکمیت (X) مرتبط است.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • OAuth 2.0 و OpenID Connect
  • -
  • RBAC و ABAC
  • -
  • OWASP Top 10 و API Security
  • -
  • رمزنگاری و TLS
  • -
  • Audit Logging
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • OWASP LLM Top 10
  • -
  • Prompt Injection و Jailbreak
  • -
  • ISO/IEC 42001 (مدیریت AI)
  • -
  • NIST AI RMF (کنترل)
  • -
  • ReBAC و Fine-grained Access
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- OAuth 2.0 (RFC 6749) - OpenID Connect Core - OWASP LLM Top 10 - ISO/IEC 27001 - ISO/IEC 42001 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند مدل دسترسی و حاکمیت داده + سناریوی آزمون نفوذ دسترسی
  • -
-
-
- - -
-
-
۷
-
-

معماری کلان، محصول و عملیات

-
Phase 7 — Enterprise Architecture, Product & Operations
-
-
←
-
DevOps + Software Architect
-
-
-

ترکیب دو نقشه راه DevOps (برای SRE، مشاهده‌پذیری و عملیات) و Software Architect (برای نگاشت معماری به محصول و مدیریت چرخه عمر) پوشش مناسبی برای فاز ۷ فراهم می‌کند.

- -
-
-
موضوعات پوشش‌داده‌شده
-
    -
  • SLI/SLO/SLA
  • -
  • مشاهده‌پذیری (Logging، Metrics، Tracing)
  • -
  • Incident Management
  • -
  • معماری سازمانی (TOGAF مفهومی)
  • -
  • Release Strategies
  • -
-
-
-
موضوعات نیازمند تکمیل
-
    -
  • مدیریت محصول (Product Vision، Roadmap)
  • -
  • Token Accounting و Cost Attribution
  • -
  • ADR (Architecture Decision Records)
  • -
  • Capability Mapping
  • -
  • Team Topologies (مفهومی)
  • -
-
-
- -

منابع تکمیلی پیشنهادی:

-
- TOGAF ADM - Google SRE Book - OpenAPI Specification - ADR - ISO/IEC 20000 -
- -

خروجی قابل‌آزمون (از ROAD-1405-001):

-
    -
  • سند معماری محصول + سند SLA و SLO
  • -
-
-
- -
-
- -
-
-
۴
-
-

شکاف‌های کلیدی و راهکار تکمیل

-
Key Gaps & Completion Strategy
-
-
-
-

roadmap.sh به‌عنوان ستون فقرات آموزشی، پوشش خوبی برای فازهای ۱ تا ۴، ۶ و ۷ دارد. اما شکاف‌های زیر باید با منابع تخصصی تکمیل شوند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
شکاففاز مرتبطراهکار تکمیل
معماری ایجنت (Agent Architecture)فاز ۵مقالات ReAct، Reflexion، Plan-and-Execute + مستندات MCP + منابع تخصصی طراحی ایجنت
ارزیابی ایجنتفاز ۵چارچوب‌های ارزیابی (Task Success Rate، Step Efficiency) + آزمون سناریومحور
امنیت LLMفاز ۶OWASP LLM Top 10 + Prompt Injection + Jailbreak Detection
حاکمیت AIفاز ۳، ۶NIST AI RMF + ISO/IEC 42001 + OECD AI Principles
BPMN 2.0فاز ۴مستندات OMG BPMN 2.0 + الگوهای مدل‌سازی فرایند
مدیریت محصولفاز ۷منابع تخصصی Product Management + Prioritization Frameworks
- -
- ⚠️ نکته مهم: شکاف معماری ایجنت (فاز ۵) بحرانی‌ترین شکاف است، زیرا این فاز مستقیماً به محور ۱ نیازمندی‌های کارفرما (ایجنت قابل‌آزمون) و نقطه عطف M4 (آمادگی برای جلسه دمو) مرتبط است. بنابراین، منابع تخصصی این فاز باید به‌صورت جدی و جداگانه دنبال شوند. -
-
-
- -
-
-
۵
-
-

نقشه راه تلفیقی پیشنهادی

-
Recommended Integrated Roadmap
-
-
-
-

بر اساس نگاشت فوق، نقشه راه تلفیقی زیر پیشنهاد می‌شود که roadmap.sh را با منابع تخصصی تکمیل می‌کند:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
فازمنبع اصلی (roadmap.sh)منبع تکمیلیخروجی قابل‌آزمون
۱Backend DeveloperNIST SP 800-57، RFC 8446نقشه داده + مدل تهدید
۲Software Design & ArchitectureClean Architecture، Hexagonalسند الگوها + نمونه Hexagonal
۳AI EngineerNIST AI RMF، ISO 42001ارزیابی مدل + نمونه RAG
۴System DesignBPMN 2.0، OpenTelemetry، Release It!الگوهای معماری + BPMN2
۵AI Engineer + Software ArchitectReAct، Reflexion، MCP، منابع تخصصی ایجنتسناریوی Agent + چارچوب ارزیابی
۶Cyber SecurityOWASP LLM Top 10، ISO 27001/42001مدل دسترسی + آزمون نفوذ
۷DevOps + Software ArchitectGoogle SRE، TOGAF، OpenAPIمعماری محصول + SLA/SLO
- -
- ✓ نکته کلیدی: نقطه عطف M4 (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و به‌ویژه فاز ۵ با منابع تخصصی محقق می‌شود. roadmap.sh برای فازهای ۱ تا ۴ و ۶ ستون فقرات است، اما فاز ۵ نیازمند منابع تخصصی جداگانه است. -
-
-
- -
-
-
۶
-
-

لینک‌های مرجع roadmap.sh

-
roadmap.sh Reference Links
-
-
-
-

لینک‌های مستقیم به نقشه‌های راه پیشنهادی در roadmap.sh:

- -
-
  • - Backend Developer - -
  • -
  • - Software Design and Architecture - -
  • -
  • - AI Engineer - -
  • -
  • - System Design - -
  • -
  • - Software Architect - -
  • -
  • - Cyber Security - -
  • -
  • - DevOps - -
  • -
    - -
    - 💡 نکته: roadmap.sh به‌طور مداوم به‌روزرسانی می‌شود. توصیه می‌شود لینک‌ها و محتوای نقشه‌های راه به‌صورت دوره‌ای بازبینی شوند تا از آخرین تغییرات مطلع شوید. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    جمع‌بندی

    -
    Summary
    -
    -
    -
    -

    این مستند، نگاشت نقشه راه دانش فنی (ROAD-1405-001) به نقشه‌های راه roadmap.sh را ارائه داد. ویژگی‌های کلیدی:

    - -
      -
    • - پوشش بالای فازهای ۱ تا ۴، ۶ و ۷ - با نقشه‌های راه Backend، Software Design، AI Engineer، System Design، Cyber Security، DevOps و Software Architect -
    • -
    • - شکاف بحرانی در فاز ۵ (ایجنت) - نیازمند منابع تخصصی تکمیلی (ReAct، Reflexion، MCP) -
    • -
    • - حفظ خروجی‌های قابل‌آزمون - هر فاز همچنان با Deliverable مشخص از ROAD-1405-001 ارزیابی می‌شود -
    • -
    • - رویکرد فارغ از سکو - استفاده از roadmap.sh برای مفاهیم و الگوها، نه ابزارهای خاص -
    • -
    • - نقشه راه تلفیقی - ترکیب roadmap.sh با منابع تخصصی برای پوشش کامل هفت فاز -
    • -
    - -
    - توصیه نهایی: roadmap.sh به‌عنوان ستون فقرات آموزشی برای فازهای ۱ تا ۴، ۶ و ۷ استفاده شود. برای فاز ۵ (هسته تمایز محصول)، منابع تخصصی ایجنت (مقالات علمی و مستندات پروتکل‌ها) به‌صورت جداگانه دنبال شوند. نقطه عطف M4 (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و منابع تخصصی فاز ۵ محقق می‌شود. -
    -
    -
    - -
    -

    🎯 ارزش این مستند

    -

    این مستند، پل ارتباطی بین نقشه راه دانش فنی داخلی و منابع آموزشی جامعه‌محور roadmap.sh را فراهم می‌کند.

    -

    با این نگاشت، تیم فنی می‌تواند از منابع شناخته‌شده و به‌روز roadmap.sh برای فازهای مختلف استفاده کند و شکاف‌ها را با منابع تخصصی تکمیل نماید.

    -
    - 💎 ارزش پیشنهادی:
    - ستون فقرات آموزشی roadmap.sh + منابع تخصصی تکمیلی + حفظ خروجی قابل‌آزمون + رویکرد فارغ از سکو + نقشه راه تلفیقی -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: آذر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_4c60f04d-bd98-4ec0-af18-7beb569dfb05.html - - - - - - - رفع مشکل تست XApiKey در Swagger | مستند فنی - - - -
    -
    -
    -
    -
    شماره مستند: XIDS-SWAGGER-APIKEY-002
    -
    نسخه: ۲.۰
    -
    تاریخ تهیه: ۲۰ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی — فنی
    -
    -
    -
    -

    رفع مشکل تست XApiKey در Swagger UI

    -

    تحلیل ریشه‌ای و راه‌حل گام‌به‌گام برای فعال‌سازی کامل

    -
    -
    - -
    - - -
    -
    -
    ۱
    -
    -

    خلاصه مشکل شناسایی‌شده

    -
    Problem Summary
    -
    -
    -
    -

    - پس از بررسی دقیق کدهای پروژه xIds، مشخص شد که اگرچه زیرساخت - XApiKeyAuthenticationHandler و Policyهای مربوطه به‌درستی پیاده‌سازی شده‌اند، - اما چهار مشکل معماری مانع از کارکرد صحیح احراز هویت با API Key در Swagger می‌شوند. -

    - -
    - 🔴 مشکلات شناسایی‌شده: -
      -
    1. ترتیب ثبت Schemeها: XApiKey اول ثبت شده و به‌عنوان DefaultScheme انتخاب می‌شود — در نتیجه درخواست‌های Bearer Token هم به آن حواله می‌شوند و شکست می‌خورند.
    2. -
    3. عدم تنظیم DefaultScheme: در AddAuthentication() هیچ DefaultScheme مشخصی تعیین نشده است.
    4. -
    5. محدودیت LocalApi Policy: Policy IdentityServerConstants.LocalApi.PolicyName فقط Scheme IdentityServerAccessToken را قبول می‌کند.
    6. -
    7. عدم وجود PolicyScheme هوشمند: هیچ مکانیزمی برای انتخاب پویای Scheme بر اساس Header درخواست وجود ندارد.
    8. -
    -
    -
    -
    - - -
    -
    -
    ۲
    -
    -

    تحلیل جریان فعلی احراز هویت

    -
    Current Authentication Flow Analysis
    -
    -
    -
    -

    - در کد فعلی XDIHelperExtension.AddXIdentityServerAuthentication، ترتیب ثبت به این صورت است: -

    - -
    // xIds/DI/XDIHelperExtension.cs — کد فعلی -var authBuilder = services.AddAuthentication(); // ← DefaultScheme تنظیم نشده! - -// ۱. ثبت XApiKey (اول) -if (addApiKeyAuthentication) -{ - authBuilder.AddScheme<..., XApiKeyAuthenticationHandler>( - "XApiKey", options => { }); -} - -// ۲. ثبت JwtBearer -authBuilder.AddJwtBearer(options => { - options.ForwardDefaultSelector = context => { ... }; -}) -// ۳. ثبت LocalApi -.AddLocalApi();
    - -
    - 💡 نکته کلیدی: - وقتی AddAuthentication() بدون پارامتر فراخوانی می‌شود و سپس اولین Scheme (XApiKey) ثبت می‌گردد، - ASP.NET Core به‌صورت خودکار XApiKey را به‌عنوان DefaultScheme در نظر می‌گیرد. - این یعنی تمام درخواست‌ها (حتی آن‌هایی که Bearer Token دارند) ابتدا به XApiKeyAuthenticationHandler می‌روند - و چون Header X-Api-Key وجود ندارد، NoResult برمی‌گردانند. -
    - -
    -
    جریان فعلی (معیوب):
    - درخواست با Bearer Token - → - DefaultScheme = XApiKey - → - NoResult (بدون Header) - → - 401 Unauthorized ❌ -
    - -
    -
    جریان مطلوب (پس از اصلاح):
    - درخواست - → - PolicyScheme (هوشمند) - → - XApiKey یا LocalApi - → - 200 OK ✓ -
    -
    -
    - - -
    -
    -
    ۳
    -
    -

    گام ۱ — اصلاح AddXIdentityServerAuthentication با PolicyScheme

    -
    Step 1: Fix Authentication Registration with PolicyScheme
    -
    -
    -
    -
    -
    حیاتی — فایل: xIds/DI/XDIHelperExtension.cs
    -

    توضیح:

    -

    - باید از AddPolicyScheme استفاده کنیم تا یک Scheme هوشمند بسازیم که بر اساس - وجود Header X-Api-Key در درخواست، Scheme مناسب را انتخاب کند. - همچنین DefaultScheme و DefaultChallengeScheme باید به‌درستی تنظیم شوند. -

    -
    - -

    کد اصلاح‌شده کامل:

    -
    // xIds/DI/XDIHelperExtension.cs -// متد: AddXIdentityServerAuthentication - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false -) -{ - // افزودنی‌های مورد نیاز - services.AddXIdentityResourceConfiguration(configuration); - - // ═══════════════════════════════════════════════════════ - // ثبت XApiKey Scheme (قبل از هر چیز دیگر) - // ═══════════════════════════════════════════════════════ - if (addApiKeyAuthentication) - { - services.AddAuthentication() - .AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), - options => { }); - } - - // ═══════════════════════════════════════════════════════ - // تعریف PolicyScheme هوشمند برای مسیریابی درخواست‌ها - // ═══════════════════════════════════════════════════════ - var smartSchemeName = "SmartAuthScheme"; - - services.AddAuthentication(options => - { - // DefaultScheme = PolicyScheme هوشمند - options.DefaultScheme = smartSchemeName; - options.DefaultAuthenticateScheme = smartSchemeName; - options.DefaultChallengeScheme = smartSchemeName; - }) - .AddPolicyScheme(smartSchemeName, "Smart Authentication Scheme", options => - { - options.ForwardDefaultSelector = context => - { - // بررسی وجود Header X-Api-Key - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - - // در غیر این صورت، از LocalApi (IdentityServer) استفاده کن - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddJwtBearer(XAuthenticationScheme.XToken.GetStringValue(), options => - { - options.Authority = configuration - .GetSection("IdentityResourceConfiguration:Authority").Value; - options.TokenValidationParameters.ValidateAudience = false; - options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" }; - }) - .AddOAuth2Introspection(XAuthenticationScheme.XIntrospection.GetStringValue(), options => - { - var identityConfig = configuration.GetXIdentityResourceConfiguration(); - options.Authority = identityConfig.Authority; - options.ClientId = identityConfig.ApiName; - options.ClientSecret = identityConfig.ClientSecret; - }) - .AddLocalApi(); -}
    - -
    - ✅ چرا این راه‌حل کار می‌کند؟ -
      -
    • PolicyScheme به‌عنوان DefaultScheme عمل می‌کند و بر اساس Header تصمیم می‌گیرد.
    • -
    • اگر X-Api-Key وجود داشته باشد → به XApiKeyAuthenticationHandler حواله می‌دهد.
    • -
    • در غیر این صورت → به LocalApi (IdentityServer) حواله می‌دهد.
    • -
    • هیچ‌گاه Scheme اشتباه انتخاب نمی‌شود.
    • -
    -
    -
    -
    - - -
    -
    -
    ۴
    -
    -

    گام ۲ — اصلاح LocalApi Policy برای پذیرش XApiKey

    -
    Step 2: Fix LocalApi Policy to Accept XApiKey
    -
    -
    -
    -
    -
    مهم — فایل: xIds/DI/XDIHelperExtension.cs
    -

    توضیح:

    -

    - در متد AddXAuthorization، Policy LocalApi.PolicyName - فقط Scheme IdentityServerAccessToken را قبول می‌کند. - باید این Policy را اصلاح کنیم تا XApiKey را هم بپذیرد. -

    -
    - -
    // xIds/DI/XDIHelperExtension.cs -// متد: AddXAuthorization - -public static void AddXAuthorization( - this IServiceCollection services, - IDictionary<string, AuthorizationPolicy> policies = null -) -{ - services.AddAuthorization(options => - { - // ... کدهای قبلی برای policies و xPolicies ... - - // ═══════════════════════════════════════════════════════ - // اصلاح LocalApi Policy برای پذیرش هر دو Scheme - // ═══════════════════════════════════════════════════════ - options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy => - { - policy.AddAuthenticationSchemes(new[] - { - IdentityServerConstants.LocalApi.AuthenticationScheme, - XAuthenticationScheme.XApiKey.GetStringValue() // ← اضافه شد - }); - policy.RequireAuthenticatedUser(); - }); - }); - - services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>(); -}
    - -
    - 💡 نکته: - با این اصلاح، Endpointهایی که [Authorize(LocalApi.PolicyName)] دارند، - هم با Bearer Token و هم با X-Api-Key قابل دسترسی خواهند بود. -
    -
    -
    - - -
    -
    -
    ۵
    -
    -

    گام ۳ — بررسی و اصلاح Swagger Security Definition

    -
    Step 3: Verify Swagger Security Configuration
    -
    -
    -
    -
    -
    بررسی — فایل: xCommons/Extensions/DIExtensions.cs
    -

    توضیح:

    -

    - در کد فعلی AddXSwaggerGenOptions، Security Definition برای XApiKey - به‌درستی تعریف شده است. اما باید مطمئن شویم که addXApiKeyAuthorization - در فراخوانی AddXSwagger مقدار true دارد. -

    -
    - -

    بررسی Startup.cs:

    -
    // xIds/Startup.cs — ConfigureServices - -// ثبت Swagger — مطمئن شوید پارامترها درست هستند -var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; -var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - -services.AddXSwagger( - Configuration, - xmlFilePath: xmlPath, - addRequiredXPoweredFilter: true, - addXTokenAuthorization: true, - addXApiKeyAuthorization: true, // ← باید true باشد - addDefaultValueFilter: true -);
    - -

    خروجی مورد انتظار در Swagger UI:

    -
    - 🔑 در Swagger UI باید دو دکمه "Authorize" ببینید: -
      -
    • accessToken: برای Bearer Token (مقدار: Bearer {token})
    • -
    • X-Api-Key: برای API Key (مقدار: xapp_xxxxxxxxxxxx)
    • -
    -
    -
    -
    - - -
    -
    -
    ۶
    -
    -

    گام ۴ — اصلاح XApiKeyAuthenticationHandler

    -
    Step 4: Verify XApiKeyAuthenticationHandler
    -
    -
    -
    -
    -
    بررسی — فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs
    -

    توضیح:

    -

    - Handler فعلی به‌درستی پیاده‌سازی شده است. فقط یک نکته مهم: - مطمئن شوید که ValidateApiKey در XApplicationProvider - مقدار requiredScope را به‌درستی بررسی می‌کند. -

    -
    - -

    کد فعلی Handler (صحیح است):

    -
    // xIds/Providers/XApiKeyAuthenticationHandler.cs -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ۱. استخراج API Key از Header - var apiKeyHeader = HeaderName; // "X-Api-Key" - if (!Request.Headers.ContainsKey(apiKeyHeader)) - return AuthenticateResult.NoResult(); - - var apiKey = Request.Headers[apiKeyHeader].ToString(); - if (apiKey.IsNullOrEmpty()) - return AuthenticateResult.NoResult(); - - // ۲. استخراج Client IP - var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - - // ۳. اعتبارسنجی API Key - var validationResult = await applicationProvider.ValidateApiKey( - apiKey: apiKey, - clientIP: clientIP - ); - - if (validationResult.Errors.HasChild()) - { - var message = validationResult.Errors.ToListString('\n'); - return AuthenticateResult.Fail(message); - } - - // ۴. ساخت Claims - var claims = new List<Claim> { - new(ClaimTypes.Name, validationResult.OwnerId), - new(JwtClaimTypes.Subject, validationResult.OwnerId), - new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()), - new(XCustomClaims.AuthType, "apikey"), - }; - - // ۵. اضافه کردن Scopeها - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - // ۶. ساخت Principal و Ticket - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -}
    - -
    - ✅ وضعیت Handler: - کد فعلی Handler صحیح است و نیازی به تغییر ندارد. - فقط مطمئن شوید که validationResult.Scopes مقادیر صحیح - (read, write, admin, manage) - را برمی‌گرداند. -
    -
    -
    - - -
    -
    -
    ۷
    -
    -

    گام ۵ — راهنمای تست در Swagger UI

    -
    Step 5: Testing Guide in Swagger UI
    -
    -
    -
    -

    مراحل تست گام‌به‌گام:

    - -
    -
    تست ۱
    -

    ساخت Application و API Key

    -

    ابتدا یک Application بسازید و سپس یک API Key برای آن ایجاد کنید:

    -
    # ۱. ساخت Application (با Bearer Token احراز هویت کنید) -POST /Applications -Content-Type: application/json -Authorization: Bearer {access_token} -X-PoweredBy: {xPoweredValue} - -{ - "name": "TestApp", - "description": "Test Application", - "type": 0 -} - -# ۲. ساخت API Key (با Bearer Token) -POST /Applications/{applicationId}/ApiKeys/Create -Content-Type: application/json -Authorization: Bearer {access_token} -X-PoweredBy: {xPoweredValue} - -{ - "scopes": ["read", "write", "manage"], - "rateLimit": 60, - "expirationMinutes": 43200, - "allowedIPs": ["127.0.0.1", "::1"] -} - -# پاسخ شامل plainKey است — آن را ذخیره کنید! -# مثال: xapp_abc123def456...
    -
    - -
    -
    تست ۲
    -

    استفاده از API Key در Swagger UI

    -

    در Swagger UI:

    -
      -
    1. روی دکمه "Authorize" (بالا سمت راست) کلیک کنید.
    2. -
    3. در بخش "X-Api-Key"، کلید API دریافتی را وارد کنید.
    4. -
    5. روی "Authorize" و سپس "Close" کلیک کنید.
    6. -
    7. Endpoint GET /Account/Test/HiApiKeyAccess را پیدا کنید.
    8. -
    9. روی "Try it out" و سپس "Execute" کلیک کنید.
    10. -
    -
    - -
    -
    تست ۳
    -

    نتایج مورد انتظار

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    سناریوپاسخ مورد انتظاروضعیت
    API Key معتبر + Scope کافی200 OK — "Hi ApiKey Access, is Passed ..."✓ صحیح
    API Key نامعتبر401 Unauthorized — "ApiKey not found"✓ صحیح
    API Key منقضی‌شده401 — "ApiKey is Expired"✓ صحیح
    Scope ناکافی403 Forbidden✓ صحیح
    IP غیرمجاز401 — "Client IP not Allowed"✓ صحیح
    Rate Limit رد شده401 — "ApiKey Rate Limit Reached"✓ صحیح
    -
    - -
    -
    تست ۴
    -

    تست با cURL (برای اطمینان بیشتر)

    -
    # تست مستقیم با cURL -curl -X GET "https://localhost:5001/Account/Test/HiApiKeyAccess" \ - -H "X-Api-Key: xapp_your_api_key_here" \ - -H "X-PoweredBy: your_powered_value" \ - -k - -# پاسخ مورد انتظار: -# "Hi ApiKey Access, is Passed ..."
    -
    -
    -
    - - -
    -
    -
    ۸
    -
    -

    چک‌لیست نهایی اصلاحات

    -
    Final Checklist
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیففایلتغییراولویت
    ۱xIds/DI/XDIHelperExtension.csبازنویسی AddXIdentityServerAuthentication با PolicyScheme🔴 حیاتی
    ۲xIds/DI/XDIHelperExtension.csاصلاح AddXAuthorization — افزودن XApiKey به LocalApi Policy🔴 حیاتی
    ۳xIds/Startup.csبررسی addXApiKeyAuthorization: true در AddXSwagger🟡 بررسی
    ۴xIds/Providers/XApiKeyAuthenticationHandler.csتأیید صحت کد (نیاز به تغییر ندارد)🟢 تأیید
    ۵xIdentityHelper/XAuthorizationHelper.csتأیید Policyهای ApiKey (نیاز به تغییر ندارد)🟢 تأیید
    -
    -
    - - -
    -
    -
    ۹
    -
    -

    جمع‌بندی و نکات پایانی

    -
    Conclusion
    -
    -
    -
    -

    - ریشه اصلی مشکل تست XApiKey در Swagger، نحوه ثبت Authentication Schemes - و عدم استفاده از PolicyScheme هوشمند بود. با اعمال اصلاحات گام ۱ و ۲، - سیستم احراز هویت به‌صورت خودکار بر اساس Header درخواست، Scheme مناسب را انتخاب می‌کند - و Swagger UI می‌تواند به‌درستی با API Key احراز هویت نماید. -

    - -
    - 🎯 نتیجه نهایی: -
      -
    • درخواست‌های دارای Header X-Api-Key → به XApiKeyAuthenticationHandler هدایت می‌شوند.
    • -
    • درخواست‌های دارای Header Authorization: Bearer → به LocalApi (IdentityServer) هدایت می‌شوند.
    • -
    • Swagger UI هر دو روش احراز هویت را پشتیبانی می‌کند.
    • -
    • Policyهای ApiKeyAccess, ApiKeyReadAccess و غیره به‌درستی کار می‌کنند.
    • -
    -
    - -
    - ⚠️ نکته مهم: - پس از اعمال تغییرات، حتماً پروژه را Clean و Rebuild کنید - و سپس Swagger UI را با Ctrl+F5 رفرش نمایید تا تغییرات Security Definition - به‌درستی اعمال شوند. -
    -
    -
    - -
    - -
    - - -
    تاریخ انتشار: ۲۰ مهر ۱۴۰۵ | نسخه: ۲.۰ | طبقه‌بندی: داخلی — فنی
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_560a6d9a-eefe-4125-9b3d-6ce0264876cb.html - - - - - - -معرفی ساختار محصول هوش مصنوعی سازمانی | رایان پرداز کاوش - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: PROD-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - PRODUCT ARCHITECTURE OVERVIEW -

    معرفی ساختار محصول هوش مصنوعی سازمانی

    -

    محصول در دست توسعه — رایان پرداز کاوش

    -
    -
    - -
    - -
    - کارفرمای محترم،
    - این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش در دست توسعه است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگو و دریافت بازخورد از تیم فنی آن سازمان است و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.

    - -

    این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های هر سازمان و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.

    - -
    -
    -
    معماری
    شش‌لایه
    -
    پایه طراحی محصول
    -
    -
    -
    MCP
    محور
    -
    توسعه‌پذیری نامحدود
    -
    -
    -
    مدل
    لوکال
    -
    حاکمیت داده و محرمانگی
    -
    -
    - -
    - نکته کلیدی: این مستند، معرفی ساختار محصول در دست توسعه است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی کارفرما قرار گیرند. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری محصول در دست توسعه

    -
    Product Architecture Under Development
    -
    -
    -
    -

    محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایه معماریقابلیت‌های پیش‌بینی‌شده در محصولوضعیت توسعه
    لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه APIدر دست توسعه
    لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌هادر دست توسعه
    لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیدر دست توسعه
    لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینهدر دست توسعه
    لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتیدر دست توسعه
    لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرفدر دست توسعه
    محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگیدر دست توسعه
    محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطادر دست توسعه
    - -
    - 💡 نکته: معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف را فراهم کند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    ساختار محصول: سامانه ایجنت‌محور سازمانی

    -
    Product Structure: Enterprise Agentic System
    -
    -
    -
    -

    هسته محصول در دست توسعه، یک موتور ایجنت است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایه معماریقابلیت پیش‌بینی‌شده در ساختار محصول
    لایه تعاملرابط وب سازمانی، نسخه دسکتاپ، درگاه API
    لایه کنترل دسترسیاحراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها
    لایه ارکستراسیون (هسته ایجنت)موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی
    لایه هوش و مدل‌هادرگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه
    لایه داده و منابعمنابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی
    لایه خروجی و گزارشتولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف
    محور عرضی حاکمیت دادهسیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی
    محور عرضی مشاهده‌پذیریمتریک و ردیابی مصرف، زمان پاسخ، نرخ خطا
    - -
    - 💡 نکته: قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی کارفرما بررسی و با نیازمندی‌های سازمان تطبیق داده شود. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    توسعه‌پذیری از طریق MCP

    -
    Extensibility via MCP
    -
    -
    -
    -

    MCP (Model Context Protocol) در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک MCP Server تعریف شود و به سامانه اضافه گردد.

    - -
    - تأکید معماری: از منظر ساختار محصول، محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی هم‌راستا شود. -
    - -

    نمونه قابلیت‌های قابل افزودن با MCP:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    حوزه سازمانینمونه MCP Serverکاربرد بالقوه
    منابع انسانیHR MCPمرخصی، آموزش، اطلاعات پرسنلی
    مالی و بودجهFinance MCPبودجه، هزینه، فاکتور، مراکز هزینه
    تولید و انبارProduction MCPموجودی، سفارش، فرمولاسیون
    مدیریت اسنادDMS MCPجستجو و بازیابی اسناد سازمانی
    پایگاه دادهDB MCPپرسش کنترل‌شده از داده‌ها
    فایل و پوشهFile MCPدسترسی کنترل‌شده به فایل‌های محلی/شبکه
    همکاری سازمانیCollaboration MCPایمیل، تقویم، اعلان
    سامانه‌های سازمانیERP/CRM MCPیکپارچه‌سازی فرایندهای سازمانی
    - -
    - ✓ نتیجه: ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    حاکمیت داده و رویکرد مدل‌های لوکال

    -
    Data Governance & Local Model Approach
    -
    -
    -
    -

    در ساختار محصول، حاکمیت داده به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.

    - -
    - ⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس: -
      -
    • خروج داده‌های حساس از مرز سازمان
    • -
    • عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی
    • -
    • احتمال استفاده از داده برای آموزش مدل‌های بعدی
    • -
    • وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس
    • -
    • عدم انطباق با سیاست‌های محرمانگی سازمانی
    • -
    -
    - -

    رویکرد پیش‌بینی‌شده در ساختار محصول:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    تصمیمرویکرد در ساختار محصول
    مدل پیش‌فرضمدل لوکال از طریق Model Gateway و Ollama/On-Prem
    داده حساسعدم خروج از مرز سازمان
    مدل آنلاینفقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا
    آموزش مدلعدم استفاده از داده سازمان برای آموزش مدل‌های خارجی
    استقرارOn-Premise با امکان عملکرد در قطع اینترنت بین‌الملل
    ممیزیثبت کامل مسیر داده و تصمیمات ایجنت
    - -
    - ✓ نتیجه: در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا مناسب باشد. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده

    -
    Agent Access Control & Tool Restriction
    -
    -
    -
    -

    در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. موتور مجوزها پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به ایجنت تصمیم‌گیرنده ابلاغ می‌شود:

    - -
    - - -
    - -

    این یعنی ایجنت تصمیم‌گیرنده نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط موتور مجوزها به ایجنت ابلاغ می‌گردد.

    - -
    - نکته حساس: ساختار محصول از ترکیب RBAC (نقش‌محور) و ABAC (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده مناسب باشد. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    دفاع لایه‌ای برای حفظ محرمانگی

    -
    Layered Defense for Confidentiality
    -
    -
    -
    -

    در ساختار محصول، برای جلوگیری از افشای اطلاعات، دفاع لایه‌ای در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایهکنترلهدف
    لایه ۱احراز هویت و نشستتأیید هویت و سطح دسترسی فعال
    لایه ۲موتور مجوزهامحدودسازی مدل، ابزار و منبع پیش از اجرا
    لایه ۳فهرست مجاز ابزار ایجنتجلوگیری از انتخاب ابزار غیرمجاز
    لایه ۴فیلتر بازیابی RAGبازیابی فقط از منابع مجاز کاربر
    لایه ۵سنسور محرمانگی خروجیجلوگیری از افشای اطلاعات در پاسخ نهایی
    لایه ۶ممیزی و لاگثبت و ردیابی تمام تصمیمات و دسترسی‌ها
    - -
    - ⚠️ نکته حیاتی: لایه‌های ۲ (موتور مجوزها) و ۵ (سنسور محرمانگی) مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود. -
    - -
    - ✓ رویکرد ساختاری: دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود. -
    -
    -
    - -
    -
    -
    ۸
    -
    -

    مثال جریان کار: یک درخواست، دو ایجنت

    -
    Workflow Example: One Request, Two Agents
    -
    -
    -
    -

    برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:

    - -
    -

    «می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»

    -
    — درخواست نمونه واحد کارمند
    -
    - -

    این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: منابع انسانی و مالی. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مرحلهمسئولاقدامکنترل دسترسی
    ۱ایجنت مسیریابتشخیص نیاز به HR و Financeفقط ابزارهای مجاز کاربر
    ۲ایجنت منابع انسانیبررسی مرخصی و شرایط آموزشفقط رکورد HR خود کارمند و سیاست آموزش
    ۳ایجنت مالیبررسی بودجه و هزینه دورهفقط بودجه مرکز هزینه واحد کاربر
    ۴ترکیب نتایجتولید پاسخ نهاییسنسور محرمانگی خروجی
    ۵تأیید انسانیاگر هزینه از سقف بیشتر باشدتوقف و دریافت تأیید
    - -

    نحوه اعمال کنترل دسترسی در این سناریو:

    - -
      -
    • - ایجنت منابع انسانی - به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد. -
    • -
    • - ایجنت مالی - به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد. -
    • -
    • - در صورت عدم مجوز مالی - اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد. -
    • -
    • - اتصال از طریق MCP - هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود. -
    • -
    • - ممیزی کامل - تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است. -
    • -
    - -
    - 💡 نتیجه مثال: ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود. -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی

    -
    Product Capabilities vs. Common Organizational Needs
    -
    -
    -
    -

    ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگوی فنی با تیم ارزیابی آن سازمان است.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نیاز رایج سازمانیقابلیت پیش‌بینی‌شده در ساختار محصول
    دستیار هوشمند و ایجنت تصمیم‌گیرندهموتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop
    مدیریت دسترسی کاربران و واحدهای سازمانیRBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای
    شفافیت مصرف و هزینهداشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API
    تعامل کاربری و تولید گزارشرابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع
    حاکمیت داده و محرمانگی اطلاعاتمدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده
    پیاده‌سازی، آموزش و پشتیبانینقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی
    عملکرد پایدار و تاب‌آوریعملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت
    - -
    - ✓ نتیجه: ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های اختصاصی کارفرما، آماده دریافت و بررسی نیازمندی‌های تیم فنی هستیم. -
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    وضعیت توسعه محصول و گام بعدی

    -
    Development Status & Next Step
    -
    -
    -
    -

    وضعیت فعلی: محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، در دست توسعه است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:

    - -
    -
    -
    -
    فاز A: هسته ایجنت و رابط پایه
    -

    درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز B: ابزارها، RAG و منابع دانش
    -

    Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز C: حاکمیت داده و کنترل دسترسی
    -

    موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری
    -

    تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه

    -
    -
    -
    -
    -
    -
    فاز E: Cross-Platform و آماده‌سازی محصول
    -

    نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه

    -
    -
    -
    -
    - -

    گام بعدی پیشنهادی:

    - -
      -
    • - برگزاری جلسه معرفی و گفتگوی فنی - معرفی ساختار محصول و دریافت بازخورد از تیم فنی کارفرما -
    • -
    • - دریافت نیازمندی‌های اختصاصی سازمان - شناخت دقیق نیازهای کارفرما برای تطبیق محصول -
    • -
    • - ارائه سناریوی نمونه Agent - نمایش ساختار ایجنت بر اساس معماری محصول -
    • -
    • - بررسی امکان اجرای پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت -
    • -
    • - ارائه پیشنهاد تجاری شفاف - بر اساس دامنه همکاری و نیازمندی‌های سازمانی -
    • -
    - -
    - 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    جمع‌بندی و پیشنهاد نهایی

    -
    Final Summary & Recommendation
    -
    -
    -
    -

    این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ویژگیرویکرد ساختار محصول
    معماری پایهشش لایه + دو محور عرضی
    توسعه‌پذیری MCPبدون محدودیت معماری
    حاکمیت دادهمدل لوکال (حاکمیت کامل)
    کنترل دسترسی ایجنتتا سطح ابزار و رکورد
    دفاع محرمانگیشش لایه مستقل
    وضعیت توسعهدر دست توسعه
    - -
    -

    🎯 پیشنهاد نهایی

    -

    ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.

    -

    توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.

    -
    - 💎 ارزش پیشنهادی ساختار محصول:
    - معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای -
    -
    - -
    - 📞 گام بعدی: در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود. -
    -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6aa5608b-7bb0-4fab-8eaa-c6345e801b03.html - - - - - - -راهنمای گام‌به‌گام ساخت MCP Server در C# .NET Standard 2.0 - - - - -
    - -
    -
    -
    -
    -
    شماره مستند: GUIDE-MCP-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: آبان ۱۴۰۵
    -
    طبقه‌بندی: آموزشی-فنی
    -
    -
    -
    - STEP-BY-STEP TUTORIAL -

    راهنمای گام‌به‌گام ساخت MCP Server در C#

    -

    پیاده‌سازی کامل با .NET Standard 2.0 و کتابخانه رسمی ModelContextProtocol

    -
    -
    - -
    - -
    - هدف مستند:
    - این مستند، یک راهنمای عملی و گام‌به‌گام برای ساخت یک MCP Server (Model Context Protocol Server) با استفاده از زبان C# و کتابخانه رسمی ModelContextProtocol است. تمام مراحل با کدهای کامل و قابل اجرا ارائه شده و پروژه نهایی روی .NET Standard 2.0 کامپایل می‌شود تا با طیف گسترده‌ای از فریم‌ورک‌ها (از جمله .NET Framework قدیمی‌تر) سازگار باشد. در پایان، سرور ما با کلاینت‌هایی مانند Claude Desktop یا GitHub Copilot قابل استفاده خواهد بود. -
    - - - - -
    -
    -
    ۰
    -
    -

    MCP چیست و چرا اهمیت دارد؟

    -
    What is MCP? / Why it matters
    -
    -
    -
    -

    Model Context Protocol (MCP) یک پروتکل باز و استاندارد است که توسط شرکت Anthropic معرفی شده و هدف آن، ایجاد یک زبان مشترک بین مدل‌های زبانی (LLM) و منابع خارجی (مانند دیتابیس، API، فایل‌سیستم، ابزارهای داخلی سازمان) است. به کمک MCP، مدل‌های زبانی می‌توانند به‌طور استاندارد و امن، به داده‌ها و قابلیت‌های خارجی دسترسی داشته باشند بدون آنکه نیاز به کدنویسی اختصاصی برای هر مدل باشد.

    - -
    -
    -
    استاندارد
    باز
    -
    پشتیبانی توسط Anthropic، Microsoft، و جامعه
    -
    -
    -
    سه
    قابلیت
    -
    Tools، Resources، Prompts
    -
    -
    -
    قابل
    حمل
    -
    یک سرور، چند کلاینت
    -
    -
    - -

    سه قابلیت اصلی MCP:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    قابلیتتوضیحمثال
    Toolsتوابع قابل فراخوانی توسط مدل (مانند Function Calling)جستجو در دیتابیس، ارسال ایمیل، محاسبه
    Resourcesداده‌های فقط‌خواندنی که مدل می‌تواند بخواندفایل، رکورد دیتابیس، تنظیمات
    Promptsقالب‌های آماده برای پرامپت‌هاالگوهای پاسخ، شخصیت‌ها، سناریوها
    - -
    - 💡 نکته: در این مستند، تمرکز ما بر روی Tools خواهد بود، چراکه پرکاربردترین قابلیت MCP است و اجازه می‌دهد منطق تجاری موجود در پروژه‌های C# خود را به‌راحتی در اختیار مدل‌های زبانی قرار دهید. -
    -
    -
    - - - - -
    -
    -
    ۱
    -
    -

    پیش‌نیازها و آماده‌سازی محیط

    -
    Prerequisites
    -
    -
    -
    -

    پیش از شروع، مطمئن شوید که موارد زیر روی سیستم شما نصب و آماده هستند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    پیش‌نیازحداقل نسخهتوضیح
    .NET SDK8.0 یا بالاتربرای اجرا و Build پروژه (خود کتابخانه روی netstandard2.0 کار می‌کند)
    IDE یا Editor—Visual Studio 2022، VS Code، یا Rider
    NuGet—به‌طور خودکار همراه .NET SDK نصب می‌شود
    کلاینت MCP (اختیاری)—Claude Desktop، GitHub Copilot، یا هر MCP Client دیگر برای تست
    - -

    بررسی نصب .NET SDK:

    -

    در ترمینال یا Command Prompt دستور زیر را اجرا کنید:

    - -
    dotnet --version
    - -

    اگر نسخه ۸.۰ یا بالاتر نمایش داده شد، همه چیز آماده است. در غیر این صورت، از سایت رسمی dotnet.microsoft.com/download آخرین نسخه را دانلود و نصب کنید.

    - -
    - ⚠️ توجه به .NET Standard 2.0: اگرچه خود پروژه شما بر روی netstandard2.0 کامپایل می‌شود، اما برای اجرای آن و ساخت DLL نیاز به یک SDK مدرن دارید. این SDK هنگام اجرا، پروژه شما را به یک باینری سازگار تبدیل می‌کند. کتابخانه ModelContextProtocol به‌طور رسمی از netstandard2.0 پشتیبانی می‌کند. -
    -
    -
    - - - - -
    -
    -
    ۲
    -
    -

    ایجاد پروژه جدید

    -
    Create a New Project
    -
    -
    -
    -

    در ترمینال، به مسیری که می‌خواهید پروژه در آن ساخته شود بروید و دستور زیر را اجرا کنید:

    - -
    dotnet new console -n SampleMcpServer
    -cd SampleMcpServer
    - -

    این دستور یک پروژه کنسول ساده با نام SampleMcpServer ایجاد می‌کند و شما را به پوشه آن منتقل می‌کند.

    - -
    -SampleMcpServer/ -├── Program.cs -├── SampleMcpServer.csproj -└── obj/ -
    - -
    - 💡 چرا Console؟ سرورهای MCP اغلب به‌صورت پروسه‌های Console اجرا می‌شوند و از طریق stdin/stdout با کلاینت (مثلاً Claude Desktop) ارتباط برقرار می‌کنند. این نوع Transport که stdio نامیده می‌شود، ساده‌ترین و پرکاربردترین روش برای اتصال کلاینت و سرور در محیط دسکتاپ است. -
    -
    -
    - - - - -
    -
    -
    ۳
    -
    -

    افزودن پکیج‌های NuGet

    -
    Add NuGet Packages
    -
    -
    -
    -

    دو پکیج اصلی نیاز دارید:

    - -
    dotnet add package ModelContextProtocol
    -dotnet add package Microsoft.Extensions.Hosting
    - -

    توضیح پکیج‌ها:

    - - - - - - - - - - - - - - - - - -
    پکیجنقش
    ModelContextProtocolهسته اصلی SDK — شامل سرور، کلاینت، Transportها (stdio/http)، و Attributeهای `[McpServerTool]`
    Microsoft.Extensions.Hostingزیرساخت Host و Dependency Injection — برای راه‌اندازی سرویس‌ها با الگوی مدرن .NET
    - -
    - 💡 تأیید نسخه: کتابخانه ModelContextProtocol به‌طور فعال توسط Microsoft و Anthropic توسعه داده می‌شود و نسخه آن مرتباً به‌روزرسانی می‌شود. برای دریافت آخرین نسخه از nuget.org استفاده کنید. -
    -
    -
    - - - - -
    -
    -
    ۴
    -
    -

    پیکربندی فایل پروژه (.csproj)

    -
    Configure Project File
    -
    -
    -
    -

    فایل SampleMcpServer.csproj را باز کنید و مطمئن شوید که TargetFramework روی netstandard2.0 تنظیم شده و پکیج‌ها به‌درستی اضافه شده‌اند:

    - -
    SampleMcpServer.csproj
    -
    <Project Sdk="Microsoft.NET.Sdk">
    -
    -  <PropertyGroup>
    -    <OutputType>Exe</OutputType>
    -    <TargetFramework>netstandard2.0</TargetFramework>
    -    <Nullable>enable</Nullable>
    -    <LangVersion>latest</LangVersion>
    -  </PropertyGroup>
    -
    -  <ItemGroup>
    -    <PackageReference Include="ModelContextProtocol" Version="*" />
    -    <PackageReference Include="Microsoft.Extensions.Hosting" Version="*" />
    -  </ItemGroup>
    -
    -</Project>
    - -

    توضیح فیلدها:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    فیلدتوضیح
    OutputTypeExe — پروژه یک برنامه اجرایی (console app) خواهد بود
    TargetFrameworknetstandard2.0 — سازگاری با .NET Framework 4.6.1+ و .NET Core 2.0+
    Nullableenable — فعال‌سازی بررسی nullability (امنیت بیشتر)
    LangVersionlatest — استفاده از آخرین امکانات زبان C#
    - -
    - ⚠️ نکته مهم: اگر از Version="*" استفاده می‌کنید، NuGet آخرین نسخه پایدار را نصب می‌کند. در محیط عملیاتی توصیه می‌شود نسخه دقیق (مانند "0.4.0-preview") را مشخص کنید تا از تغییرات ناخواسته جلوگیری شود. -
    -
    -
    - - - - -
    -
    -
    ۵
    -
    -

    تعریف اولین Tool (ابزار MCP)

    -
    Define Your First MCP Tool
    -
    -
    -
    -

    در ریشه پروژه، فایل جدیدی به نام EchoTool.cs بسازید. در این فایل، یک کلاس ساده با متد Echo تعریف می‌کنیم که هر پیامی را به مدل بازمی‌گرداند:

    - -
    EchoTool.cs
    -
    using System.ComponentModel;
    -using ModelContextProtocol.Server;
    -
    -[McpServerToolType]
    -public static class EchoTool
    -{
    -    [McpServerTool, Description("Echoes the message back to the client.")]
    -    public static string Echo(string message) => $"hello {message}";
    -}
    - -

    توضیح Attributeها و اجزا:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    جزءنقش
    [McpServerToolType]به SDK اعلام می‌کند که این کلاس شامل Tool است و باید اسکن شود
    [McpServerTool]متد را به‌عنوان یک Tool قابل فراخوانی توسط LLM ثبت می‌کند
    [Description(...)]توضیح انسانی که به مدل زبانی داده می‌شود تا بداند این Tool چه کاری انجام می‌دهد
    string messageپارامتر ورودی — SDK به‌طور خودکار JSON Schema را از این signature تولید می‌کند
    string (return type)نوع بازگشتی — می‌تواند string، Task<string> یا هر شیء سریالایزپذیر باشد
    - -
    - ✓ چرا این سادگی مهم است؟ شما نیازی به نوشتن JSON Schema دستی، یا پیاده‌سازی هندلرهای پیچیده ندارید. SDK از روی signature متد و Attributeها، به‌طور خودکار همه چیز را می‌سازد. این رویکرد «Attribute-Driven» کار را بسیار ساده می‌کند. -
    -
    -
    - - - - -
    -
    -
    ۶
    -
    -

    پیکربندی و اجرای سرور در Program.cs

    -
    Configure and Run the Server
    -
    -
    -
    -

    محتوای فایل Program.cs را با کد زیر جایگزین کنید. این کد، Host را می‌سازد، لاگ‌ها را به stderr هدایت می‌کند، و سرور را با Transport از نوع stdio راه‌اندازی می‌نماید:

    - -
    Program.cs
    -
    using Microsoft.Extensions.DependencyInjection;
    -using Microsoft.Extensions.Hosting;
    -using Microsoft.Extensions.Logging;
    -using ModelContextProtocol.Server;
    -
    -var builder = Host.CreateApplicationBuilder(args);
    -
    -builder.Logging.AddConsole(consoleLogOptions =>
    -{
    -    // Configure all logs to go to stderr so they don't corrupt the MCP protocol stream.
    -    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
    -});
    -
    -builder.Services
    -    .AddMcpServer()
    -    .WithStdioServerTransport()
    -    .WithToolsFromAssembly();
    -
    -await builder.Build().RunAsync();
    - -

    تشریح خط‌به‌خط:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    خطتوضیح
    Host.CreateApplicationBuilder(args)ساخت Builder مدرن .NET با پشتیبانی از Configuration و DI
    AddConsole(...LogToStandardErrorThreshold...)بحرانی: هدایت لاگ‌ها به stderr. اگر لاگ‌ها به stdout بروند، با پروتکل MCP تداخل می‌کنند و ارتباط قطع می‌شود
    AddMcpServer()ثبت سرویس‌های MCP در DI Container
    WithStdioServerTransport()استفاده از stdin/stdout برای ارتباط — برای کلاینت‌های دسکتاپ ایده‌آل است
    WithToolsFromAssembly()اسکن خودکار اسمبلی و ثبت هر کلاسی که با [McpServerToolType] علامت‌گذاری شده
    await builder.Build().RunAsync()ساخت Host و شروع به گوش دادن برای درخواست‌ها
    - -
    - ⚠️ هشدار بسیار مهم: در استفاده از stdio، هرگز از Console.WriteLine برای لاگ استفاده نکنید. این کار پیام‌های پروتکل را خراب می‌کند. تمام لاگ‌ها باید از طریق ILogger و با تنظیم LogToStandardErrorThreshold به stderr هدایت شوند. اگر این نکته رعایت نشود، سرور به‌ظاهر اجرا می‌شود اما کلاینت نمی‌تواند با آن ارتباط برقرار کند. -
    -
    -
    - - - - -
    -
    -
    ۷
    -
    -

    ساخت و اجرا

    -
    Build & Run
    -
    -
    -
    -

    در پوشه پروژه، دستور زیر را اجرا کنید:

    - -
    dotnet build
    -dotnet run
    - -

    سرور شما اجرا خواهد شد و منتظر دریافت پیام‌ها از طریق stdin خواهد بود. در این حالت، سرور در حالت منفعل (Passive) است و تنها زمانی که کلاینت MCP به آن متصل شود، شروع به کار خواهد کرد.

    - -

    چه اتفاقی در پس‌زمینه می‌افتد؟

    -
      -
    1. SDK اسمبلی را اسکن کرده و کلاس EchoTool را کشف می‌کند.
    2. -
    3. از روی متد Echo، یک Tool با پارامتر ورودی message: string و نوع بازگشتی string استخراج می‌کند.
    4. -
    5. یک JSON Schema خودکار برای این Tool تولید می‌کند.
    6. -
    7. سرور شروع به گوش دادن به stdin می‌کند.
    8. -
    9. وقتی کلاینت متصل می‌شود، ابتدا یک پیام initialize می‌فرستد و سرور با معرفی خودش و ابزارهای موجود پاسخ می‌دهد.
    10. -
    11. سپس کلاینت می‌تواند پیام‌های tools/list یا tools/call بفرستد.
    12. -
    - -
    - 💡 چه چیزی روی stdout می‌رود؟ فقط پیام‌های JSON-RPC پروتکل MCP. هیچ خروجی اضافی مجاز نیست. اگر می‌خواهید تست کنید، فقط از طریق یک کلاینت MCP اقدام کنید. -
    -
    -
    - - - - -
    -
    -
    ۸
    -
    -

    تست با کلاینت MCP

    -
    Testing with an MCP Client
    -
    -
    -
    -

    برای تست، می‌توانید از Claude Desktop، VS Code Copilot یا هر MCP Client دیگری استفاده کنید. در ادامه، نمونه پیکربندی برای دو کلاینت پرکاربرد ارائه شده است.

    - -

    الف) Claude Desktop

    -

    فایل پیکربندی claude_desktop_config.json را باز کنید (در ویندوز در مسیر %APPDATA%\Claude\ و در macOS در ~/Library/Application Support/Claude/) و بخش mcpServers را اضافه کنید:

    - -
    {
    -  "mcpServers": {
    -    "sample-echo": {
    -      "command": "dotnet",
    -      "args": [
    -        "run",
    -        "--project",
    -        "C:\\Path\\To\\SampleMcpServer\\SampleMcpServer.csproj"
    -      ]
    -    }
    -  }
    -}
    - -

    ب) VS Code (Copilot + MCP)

    -

    در فایل .vscode/mcp.json:

    - -
    {
    -  "servers": {
    -    "sample-echo": {
    -      "command": "dotnet",
    -      "args": [
    -        "run",
    -        "--project",
    -        "${workspaceFolder}/SampleMcpServer/SampleMcpServer.csproj"
    -      ]
    -    }
    -  }
    -}
    - -

    ج) تست دستی با JSON-RPC

    -

    اگر می‌خواهید بدون کلاینت تست کنید، می‌توانید مستقیماً پیام JSON-RPC بفرستید. در ترمینال سرور را اجرا کنید و سپس پیام‌های زیر را روی stdin آن بنویسید:

    - -
    // درخواست initialize
    -{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}
    -
    -// دریافت لیست ابزارها
    -{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
    -
    -// فراخوانی ابزار Echo
    -{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"Echo","arguments":{"message":"World"}}}
    - -
    - ✓ پاسخ مورد انتظار: پس از فراخوانی Echo، باید چیزی شبیه به این دریافت کنید: -

    - {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"hello World"}]}} -
    -
    -
    - - - - -
    -
    -
    ۹
    -
    -

    افزودن Toolهای پیشرفته‌تر

    -
    Advanced Tools
    -
    -
    -
    -

    Toolهای MCP می‌توانند پیچیده‌تر از یک Echo ساده باشند. در ادامه، چند الگوی پیشرفته آورده شده است:

    - -

    الف) Tool با چند پارامتر و نوع‌های مختلف

    -
    [McpServerTool, Description("Adds two numbers and returns the result.")]
    -public static int Add(
    -    [Description("First number")] int a,
    -    [Description("Second number")] int b
    -) => a + b;
    - -

    ب) Tool با پارامتر اختیاری

    -
    [McpServerTool, Description("Searches for a term, with optional limit.")]
    -public static string Search(
    -    [Description("The search query")] string query,
    -    [Description("Maximum results (default: 10)")] int limit = 10
    -) => $"Searching for '{query}' with limit {limit}";
    - -

    ج) Tool Async با CancellationToken

    -
    [McpServerTool, Description("Fetches data from a remote API.")]
    -public static async Task<string> FetchData(
    -    [Description("The resource identifier")] string id,
    -    CancellationToken cancellationToken = default
    -)
    -{
    -    using var http = new HttpClient();
    -    return await http.GetStringAsync($"https://api.example.com/{id}", cancellationToken);
    -}
    - -

    د) Tool با Dependency Injection

    -

    برای استفاده از سرویس‌های موجود، می‌توانید Tool را به‌صورت non-static تعریف کنید و سرویس‌ها را از طریق سازنده تزریق کنید:

    - -
    [McpServerToolType]
    -public class DatabaseTool
    -{
    -    private readonly IMyRepository _repository;
    -
    -    // DI automatically resolves the dependency
    -    public DatabaseTool(IMyRepository repository)
    -    {
    -        _repository = repository;
    -    }
    -
    -    [McpServerTool, Description("Retrieves a record by ID.")]
    -    public async Task<string> GetRecord(string id, CancellationToken ct = default)
    -    {
    -        var record = await _repository.GetByIdAsync(id, ct);
    -        return record?.ToJson() ?? "Not found";
    -    }
    -}
    - -
    - 💡 نکته: برای ثبت سرویس‌های DI، پیش از builder.Build() آن‌ها را اضافه کنید: -

    - builder.Services.AddScoped<IMyRepository, MyRepository>(); -
    -
    -
    - - - - -
    -
    -
    ۱۰
    -
    -

    روش جایگزین: استفاده از MCPSharp

    -
    Alternative: MCPSharp Community Library
    -
    -
    -
    -

    اگر به یک API ساده‌تر و مختصرتر علاقه‌مند هستید، می‌توانید از کتابخانه جامعه MCPSharp استفاده کنید. این کتابخانه نیز از netstandard2.0 پشتیبانی می‌کند و با تعداد خطوط کمتر، همان قابلیت‌ها را ارائه می‌دهد.

    - -

    نصب:

    -
    dotnet add package MCPSharp
    - -

    مثال کامل:

    -
    using MCPSharp;
    -
    -public class Calculator
    -{
    -    [McpTool("add", "Adds two numbers")]
    -    public static int Add(
    -        [McpParameter(true)] int a,
    -        [McpParameter(true)] int b
    -    ) => a + b;
    -
    -    [McpTool("multiply", "Multiplies two numbers")]
    -    public static int Multiply(
    -        [McpParameter(true)] int a,
    -        [McpParameter(true)] int b
    -    ) => a * b;
    -}
    -
    -await MCPServer.StartAsync("CalculatorServer", "1.0.0");
    - -

    مقایسه دو رویکرد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ویژگیModelContextProtocol (رسمی)MCPSharp (جامعه)
    نگهداریMicrosoft + Anthropicجامعه (Community)
    پشتیبانی از .NET Standard 2.0✓✓
    میزان کد Boilerplateمتوسطحداقل
    پشتیبانی از DI✓ کاملمحدود
    Transport HTTP✓در حال توسعه
    توصیه برای پروژه‌های عملیاتیModelContextProtocol (رسمی)
    - -
    - ⚠️ توصیه: برای پروژه‌های عملیاتی و سازمانی، استفاده از کتابخانه رسمی ModelContextProtocol توصیه می‌شود زیرا پشتیبانی بلندمدت، به‌روزرسانی‌های امنیتی، و سازگاری با آخرین تغییرات پروتکل MCP را تضمین می‌کند. MCPSharp برای پروژه‌های کوچک، یادگیری، یا Prototype مناسب است. -
    -
    -
    - - - - -
    -
    -
    ۱۱
    -
    -

    گزینه پیشرفته: HTTP Transport

    -
    Optional: HTTP Transport
    -
    -
    -
    -

    اگر می‌خواهید سرور MCP شما از راه دور (Remote) قابل دسترسی باشد (مثلاً در یک کانتینر Docker یا روی یک سرور Cloud)، می‌توانید به‌جای stdio از HTTP Transport استفاده کنید.

    - -
    - 💡 چه زمانی HTTP؟ -
      -
    • چندین کلاینت به‌طور همزمان می‌خواهند وصل شوند
    • -
    • سرور در محیطی جدا از کلاینت اجرا می‌شود (Docker، Kubernetes، Cloud)
    • -
    • نیاز به احراز هویت مرکزی و Rate Limiting دارید
    • -
    -
    - -

    تغییرات لازم در Program.cs:

    -
    using Microsoft.AspNetCore.Builder;
    -using Microsoft.Extensions.DependencyInjection;
    -using Microsoft.Extensions.Hosting;
    -using ModelContextProtocol.Server;
    -
    -var builder = WebApplication.CreateBuilder(args);
    -
    -builder.Services
    -    .AddMcpServer()
    -    .WithHttpTransport()       // ← به‌جای WithStdioServerTransport
    -    .WithToolsFromAssembly();
    -
    -var app = builder.Build();
    -
    -app.MapMcp();                   // ← مسیر /mcp را فعال می‌کند
    -
    -app.Run();
    - -

    همچنین باید پکیج Microsoft.AspNetCore را اضافه کنید و نوع پروژه را از Microsoft.NET.Sdk به Microsoft.NET.Sdk.Web تغییر دهید.

    - -
    - ⚠️ توجه: HTTP Transport در .NET Standard 2.0 به‌طور کامل پشتیبانی نمی‌شود. برای استفاده از این قابلیت، بهتر است پروژه را به net8.0 یا بالاتر ارتقا دهید. اگر مجبور به استفاده از .NET Standard 2.0 هستید، از stdio استفاده کنید و یک پروسه فرزند بسازید. -
    -
    -
    - - - - -
    -
    -
    ۱۲
    -
    -

    بهترین روش‌ها و نکات عملیاتی

    -
    Best Practices
    -
    -
    -
    -
      -
    • هر Tool را با [Description] واضح و دقیق توصیف کنید — مدل از این توضیح برای تصمیم‌گیری استفاده می‌کند
    • -
    • پارامترها را با نوع‌های مشخص (نه object) تعریف کنید تا JSON Schema دقیق‌تری تولید شود
    • -
    • برای عملیات طولانی، از Task و CancellationToken استفاده کنید
    • -
    • خطاها را با Exceptionهای واضح پرتاب کنید — SDK آن‌ها را به JSON-RPC Error تبدیل می‌کند
    • -
    • ورودی‌ها را اعتبارسنجی کنید (Validation) — مدل ممکن است ورودی نامعتبر بفرستد
    • -
    • لاگ‌ها را هرگز روی stdout ننویسید — از ILogger و stderr استفاده کنید
    • -
    • از [McpServerToolType] روی کلاس‌های Helper استفاده کنید تا ابزارها در فایل‌های مختلف تقسیم شوند
    • -
    • در محیط عملیاتی، Transport را بر اساس سناریو انتخاب کنید (stdio برای دسکتاپ، HTTP برای Cloud)
    • -
    • ورژن پروتکل MCP را در نظر بگیرید — کلاینت و سرور باید سازگار باشند
    • -
    • برای تست خودکار، از JSON-RPC خام در سناریوهای Integration Test استفاده کنید
    • -
    - -

    الگوی پیشنهادی ساختار پروژه:

    -
    -SampleMcpServer/ -├── Tools/ -│ ├── EchoTool.cs -│ ├── CalculatorTool.cs -│ └── DatabaseTool.cs -├── Services/ -│ ├── IMyRepository.cs -│ └── MyRepository.cs -├── Models/ -│ └── RecordDto.cs -├── Program.cs -├── appsettings.json -└── SampleMcpServer.csproj -
    -
    -
    - - - - -
    -
    -
    ۱۳
    -
    -

    جمع‌بندی

    -
    Summary
    -
    -
    -
    -

    در این مستند، به‌صورت گام‌به‌گام، ساخت یک MCP Server با C# و .NET Standard 2.0 را بررسی کردیم. مراحلی که پشت سر گذاشتیم:

    - -
      -
    • با مفهوم MCP و سه قابلیت اصلی آن (Tools، Resources، Prompts) آشنا شدیم
    • -
    • پیش‌نیازها و محیط توسعه را آماده کردیم
    • -
    • یک پروژه Console جدید با dotnet new console ساختیم
    • -
    • پکیج‌های ModelContextProtocol و Microsoft.Extensions.Hosting را نصب کردیم
    • -
    • فایل .csproj را برای netstandard2.0 پیکربندی کردیم
    • -
    • اولین Tool خود را با [McpServerTool] تعریف کردیم
    • -
    • سرور را در Program.cs با stdio Transport راه‌اندازی کردیم
    • -
    • نحوه تست با Claude Desktop و VS Code را فرا گرفتیم
    • -
    • الگوهای پیشرفته‌تر (Async، DI، پارامترهای اختیاری) را بررسی کردیم
    • -
    • با کتابخانه جایگزین MCPSharp آشنا شدیم
    • -
    • روش استفاده از HTTP Transport برای سناریوهای Cloud را دیدیم
    • -
    • بهترین روش‌های عملیاتی را مرور کردیم
    • -
    - -
    -

    🎯 نتیجه نهایی

    -

    شما اکنون یک MCP Server کامل و عملیاتی در اختیار دارید که:

    -

    - با استاندارد باز MCP سازگار است، از .NET Standard 2.0 پشتیبانی می‌کند، به‌راحتی با Claude Desktop و GitHub Copilot یکپارچه می‌شود، و منطق تجاری موجود شما را در دسترس مدل‌های زبانی قرار می‌دهد. -

    -
    - 💎 ارزش پیشنهادی:
    - یکپارچگی استاندارد با LLM + بدون تغییر ساختار موجود پروژه + قابلیت حمل بالا + سادگی توسعه -
    -
    - -
    - 📞 گام بعدی پیشنهادی: پس از ساخت این سرور ساده، می‌توانید: -
      -
    • سرویس‌های موجود خود را به‌عنوان Toolهای MCP ثبت کنید (مانند RAG، مدیریت مکالمه، پردازش فایل)
    • -
    • سرور را در CI/CD قرار دهید و به‌صورت خودکار منتشر کنید
    • -
    • با یک MCP Client متصل شوید و تست End-to-End انجام دهید
    • -
    • در صورت نیاز، به سمت HTTP Transport و استقرار در کانتینر حرکت کنید
    • -
    -
    -
    -
    - -
    - این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است. -
    - -
    - -
    - - -
    تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: آموزشی-فنی
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6b96ea86-c4b1-49a2-b46a-df5be36b52e5.html - - - - - - -معماری کلان محصول | سامانه هوش مصنوعی سازمانی - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: ARCH-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - HIGH-LEVEL ARCHITECTURE -

    معماری کلان محصول

    -

    سامانه هوش مصنوعی سازمانی — پاسخ به نیازمندی‌های پارسا پلیمر شریف

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند به توصیف معماری کلان سامانه هوش مصنوعی سازمانی می‌پردازد که بر اساس تحلیل نیازمندی‌های شرکت پارسا پلیمر شریف (مستند REQ-1405-001) تدوین شده است. رویکرد این معماری، تفکر سیستماتیک و فارغ از سکو و جزئیات پیاده‌سازی است. هدف، شناسایی اجزاء و مولفه‌های اصلی سامانه، روابط میان آنها، و جریان‌های اطلاعاتی و کنترلی است تا مبنای طراحی تفصیلی و پیاده‌سازی قرار گیرد. -
    - -
    -
    -
    ۱
    -
    -

    اصول حاکم بر معماری

    -
    Architectural Principles
    -
    -
    -
    -

    معماری این سامانه بر پایه اصول زیر شکل گرفته است که برگرفته از نیازمندی‌های صریح کارفرما و رویکرد تفکر سیستماتیک است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    اصلتوضیحمبنای نیازمندی
    جداسازی دغدغه‌هاتفکیک لایه‌های تعامل، کنترل، هوش، داده و حاکمیت به‌گونه‌ای که تغییر در یک لایه، حداقل اثر را بر لایه‌های دیگر داشته باشدمحور ۱، ۲، ۵
    حاکمیت‌محوریکنترل دسترسی، ممیزی و سیاست‌های داده به‌صورت عرضی (Cross-cutting) در تمام لایه‌ها اعمال می‌شود، نه به‌صورت جزیره‌ایمحور ۲، ۵
    ایجنت‌محوری قابل‌آزمونموتور ایجنت به‌عنوان یک مولفه مستقل با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح، قابل مشاهده و آزمون باشدمحور ۱
    شفافیت مصرفاندازه‌گیری و گزارش‌گیری مصرف در سطح کاربر، مدل، ایجنت و ابزار به‌صورت یکپارچهمحور ۳
    تاب‌آوری و استقرارپذیریامکان استقرار درون‌سازمانی (On-Premise) و عملکرد در شرایط قطع اینترنت بین‌المللمحور ۵، ۷
    توسعه‌پذیری و سفارشی‌سازیامکان افزودن مدل‌ها، ابزارها، ایجنت‌ها و منابع داده جدید بدون تغییر در هستهمحور ۱، ۶
    - -
    - اصل حاکم: معماری باید به‌گونه‌ای باشد که هر ادعای قابلیت، قابل اثبات و آزمون باشد. این یعنی هر مولفه باید دارای مرز مشخص، رابط تعریف‌شده و رفتار قابل مشاهده باشد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    نمای کلی سیستم

    -
    System Overview
    -
    -
    -
    -

    سامانه به‌صورت کلان از شش لایه اصلی و دو محور عرضی تشکیل شده است. این ساختار لایه‌ای، جداسازی دغدغه‌ها را تضمین می‌کند و محورهای عرضی، حاکمیت و امنیت را در تمام لایه‌ها اعمال می‌نمایند.

    - -
    -
    -
    لایه ۱: تعامل و تجربه کاربری (Interaction Layer)
    -
    - رابط وب سازمانی - نسخه دسکتاپ - رابط API - کانال‌های ارتباطی -
    -
    - -
    ▼
    - -
    -
    لایه ۲: کنترل دسترسی و نشست (Access & Session Layer)
    -
    - احراز هویت - مدیریت نشست - اعمال مجوزها - مدیریت نقش‌ها -
    -
    - -
    ▼
    - -
    -
    لایه ۳: هماهنگی و ارکستراسیون (Orchestration Layer)
    -
    - موتور ایجنت - برنامه‌ریز - انتخاب‌گر ابزار - مدیریت جریان - نقاط تأیید انسانی -
    -
    - -
    ▼
    - -
    -
    لایه ۴: هوش و مدل‌ها (Intelligence Layer)
    -
    - درگاه مدل‌ها - مدیریت مدل - بازیابی و تقویت (RAG) - حافظه و زمینه -
    -
    - -
    ▼
    - -
    -
    لایه ۵: داده و منابع (Data & Resources Layer)
    -
    - منابع دانش سازمانی - فایل‌ها و پوشه‌ها - پایگاه‌های داده - سرویس‌های خارجی - ابزارهای عملیاتی -
    -
    - -
    ▼
    - -
    -
    لایه ۶: خروجی و گزارش (Output & Reporting Layer)
    -
    - تولید گزارش - خروجی Word/Excel - ارجاع به منابع - داشبورد مصرف -
    -
    -
    - -
    -
    -
    محور عرضی ۱: حاکمیت داده و امنیت
    -
    سیاست‌های داده، ممیزی، محرمانگی، جلوگیری از افشا — اعمال در تمام لایه‌ها
    -
    -
    -
    محور عرضی ۲: مشاهده‌پذیری و اندازه‌گیری
    -
    لاگ، متریک، ردیابی مصرف، گزارش هزینه — اعمال در تمام لایه‌ها
    -
    -
    - -
    - 💡 نکته معماری: محورهای عرضی به‌صورت Cross-cutting Concerns طراحی شده‌اند؛ یعنی هر درخواست کاربر، در هر لایه‌ای که پردازش شود، از فیلتر حاکمیت و مشاهده‌پذیری عبور می‌کند. این تضمین می‌کند که نیازمندی‌های محور ۲ (دسترسی) و محور ۳ (مصرف) به‌صورت سیستماتیک و نه جزیره‌ای برآورده شوند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    اجزاء و مولفه‌های اصلی

    -
    Core Components
    -
    -
    -
    -

    هر لایه از مولفه‌هایی تشکیل شده است که مسئولیت مشخص و رابط تعریف‌شده دارند. در ادامه، مولفه‌های کلیدی هر لایه تشریح می‌شود:

    - -

    لایه ۱: تعامل و تجربه کاربری

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    رابط وب سازمانیتعامل کاربران با سامانه از طریق مرورگر، شامل چت، آپلود فایل، مشاهده گزارشمحور ۴
    نسخه دسکتاپدسترسی به قابلیت‌های سامانه از طریق اپلیکیشن دسکتاپ با قابلیت دسترسی به فایل‌های محلیمحور ۴
    درگاه APIامکان یکپارچه‌سازی سیستم‌های سازمانی و استفاده از اعتبار اختصاصیمحور ۳
    - -

    لایه ۲: کنترل دسترسی و نشست

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    احراز هویتتأیید هویت کاربران و یکپارچه‌سازی با سامانه‌های هویت سازمانیمحور ۲
    مدیریت نقش‌هاتعریف و مدیریت نقش‌ها، کاربران و سطوح دسترسی واحدهای مختلفمحور ۲
    موتور مجوزهااعمال مجوزها در سطح مدل، منبع، ابزار و رکورد؛ فهرست مجاز مدل‌ها و ابزارهامحور ۲
    مدیریت نشستحفظ زمینه کاربر، سطح دسترسی فعال و سیاست‌های نشستمحور ۲
    - -

    لایه ۳: هماهنگی و ارکستراسیون (هسته ایجنت)

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    موتور ایجنتهسته اصلی تصمیم‌گیری؛ دریافت هدف، تولید برنامه، اجرا و اصلاح بر اساس نتیجهمحور ۱
    برنامه‌ریز (Planner)تبدیل هدف به مراحل اجرایی قابل پیگیریمحور ۱
    انتخاب‌گر ابزار (Tool Selector)انتخاب ابزار یا منبع مناسب از میان فهرست مجاز کاربرمحور ۱، ۲
    مدیریت جریان (Flow Manager)هدایت جریان اجرا، مدیریت حالت‌ها، واکنش به خطا و تغییر شرایطمحور ۱
    نقاط تأیید انسانیتعریف و اجرای نقاط Human-in-the-loop برای تأیید عملیات حساسمحور ۱
    - -

    لایه ۴: هوش و مدل‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    درگاه مدل‌ها (Model Gateway)لایه انتزاع دسترسی به مدل‌های مختلف (داخلی/خارجی) با سیاست‌های یکسانمحور ۱، ۵
    مدیریت مدلفهرست مدل‌های مجاز، نسخه‌بندی، به‌روزرسانی و سیاست دسترسی به مدل‌های جدیدمحور ۱
    بازیابی و تقویت (RAG)بازیابی اطلاعات از منابع مجاز کاربر و تقویت پاسخ مدل با شواهدمحور ۲، ۴
    حافظه و زمینهمدیریت زمینه مکالمه، حافظه کوتاه‌مدت و بلندمدت با رعایت سطح دسترسیمحور ۲
    - -

    لایه ۵: داده و منابع

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    منابع دانش سازمانیمخازن دانش، اسناد، پایگاه‌های دانش و محتوای ساختاریافته/غیرساختاریافتهمحور ۴، ۵
    مدیریت فایل و پوشهدسترسی کنترل‌شده به فایل‌های محلی/شبکه و تحلیل چند فایلمحور ۴
    سرویس‌های خارجیاتصال به سرویس‌های ثالث از طریق API با سیاست‌های حاکمیت دادهمحور ۵
    ابزارهای عملیاتیمجموعه ابزارهای قابل فراخوانی توسط ایجنت (جستجو، محاسبه، ارسال، تبدیل و...)محور ۱
    - -

    لایه ۶: خروجی و گزارش

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    تولید گزارشتولید خروجی متنی، جدولی و نموداری با قابلیت ویرایش و ارجاع به منابعمحور ۴
    مبدل قالبتبدیل خروجی به Word، Excel و سایر قالب‌های موردنیازمحور ۴
    داشبورد مصرفنمایش مصرف و هزینه به تفکیک کاربر، مدل، ایجنت و ابزارمحور ۳
    - -

    محورهای عرضی

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهمسئولیتنیازمندی مرتبط
    سیاست‌گذار دادهتعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدلمحور ۵
    ممیزی و لاگثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها برای ممیزیمحور ۲، ۵
    سنسور محرمانگیشناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسی در پاسخ‌هامحور ۲
    متریک و ردیابیاندازه‌گیری مصرف توکن، زمان پاسخ، نرخ خطا و شاخص‌های عملکردمحور ۳، ۷
    -
    -
    - -
    -
    -
    ۴
    -
    -

    روابط میان مولفه‌ها

    -
    Component Relationships
    -
    -
    -
    -

    روابط میان مولفه‌ها بر اساس جریان درخواست و جریان کنترل تعریف می‌شود. هر درخواست کاربر از لایه تعامل وارد شده و پس از عبور از لایه‌های کنترل، ارکستراسیون و هوش، به منابع داده دسترسی پیدا کرده و خروجی از لایه گزارش بازمی‌گردد.

    - -

    جریان اصلی درخواست (Request Flow)

    -
    -
    -
    ۱
    -
    ورود درخواست
    -

    کاربر از طریق رابط وب/دسکتاپ/API درخواست را ارسال می‌کند.

    -
    -
    -
    ۲
    -
    احراز و مجوز
    -

    لایه کنترل، هویت کاربر را تأیید و سطح دسترسی فعال را تعیین می‌کند.

    -
    -
    -
    ۳
    -
    تصمیم ارکستراسیون
    -

    موتور ایجنت نوع درخواست (پاسخ ساده / برنامه‌ریزی چندمرحله‌ای) را تشخیص می‌دهد.

    -
    -
    -
    ۴
    -
    بازیابی و استدلال
    -

    لایه هوش با رعایت مجوزها، اطلاعات را بازیابی و مدل مناسب را فراخوانی می‌کند.

    -
    -
    -
    ۵
    -
    اجرای ابزار
    -

    در صورت نیاز، ایجنت ابزار مجاز را انتخاب و عملیات را اجرا می‌کند.

    -
    -
    -
    ۶
    -
    تولید خروجی
    -

    لایه گزارش، پاسخ یا گزارش نهایی را با ارجاع به منابع تولید می‌کند.

    -
    -
    - -

    جدول روابط کلیدی میان مولفه‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    از مولفهبه مولفهنوع رابطهتوضیح
    رابط کاربریمدیریت نشستدرخواست/پاسخهر تعامل کاربر از این مسیر وارد و نشست فعال می‌شود
    مدیریت نشستموتور مجوزهاپرس‌وجوسطح دسترسی و فهرست مجاز کاربر استعلام می‌شود
    موتور مجوزهاموتور ایجنتاعمال محدودیتفهرست ابزارها، مدل‌ها و منابع مجاز به ایجنت ابلاغ می‌شود
    موتور ایجنتبرنامه‌ریزفراخوانیهدف کاربر برای تولید برنامه اجرایی ارسال می‌شود
    برنامه‌ریزانتخاب‌گر ابزاردرخواست انتخاببرای هر مرحله، ابزار مناسب از فهرست مجاز انتخاب می‌شود
    انتخاب‌گر ابزارابزارهای عملیاتیفراخوانیابزار انتخاب‌شده اجرا و نتیجه بازمی‌گردد
    موتور ایجنتنقاط تأیید انسانیتوقف/تأییددر عملیات حساس، اجرا متوقف و منتظر تأیید انسان می‌شود
    موتور ایجنتدرگاه مدل‌هافراخوانی مدلبرای استدلال، تولید متن یا تصمیم‌گیری، مدل مناسب فراخوانی می‌شود
    درگاه مدل‌هامدیریت مدلاستعلاممدل مجاز و نسخه فعال برای کاربر بررسی می‌شود
    بازیابی و تقویتمنابع دانش سازمانیبازیابیاطلاعات مرتبط با رعایت سطح دسترسی بازیابی می‌شود
    سنسور محرمانگیتولید گزارشفیلترپاسخ نهایی پیش از ارائه، از نظر افشای اطلاعات بررسی می‌شود
    متریک و ردیابیداشبورد مصرفتغذیه دادهداده‌های مصرف و هزینه برای گزارش‌گیری ارسال می‌شود
    - -
    - ✓ نکته کلیدی درباره روابط: مسیر موتور مجوزها ← موتور ایجنت و سنسور محرمانگی ← تولید گزارش دو مسیر حیاتی برای پاسخ به آزمون نفوذ دسترسی کارفرما هستند. این دو مسیر تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود شود (دفاع لایه‌ای). -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جریان‌های کلیدی سیستم

    -
    Key System Flows
    -
    -
    -
    -

    سه جریان اصلی در سامانه وجود دارد که هر یک از منظر تفکر سیستماتیک، رفتار متفاوتی از خود نشان می‌دهند:

    - -

    جریان ۱: پاسخ ساده (Simple Response)

    -

    درخواست کاربر مستقیماً به لایه هوش رفته، مدل پاسخ تولید می‌کند و پس از فیلتر محرمانگی، به کاربر بازمی‌گردد. این جریان برای پرسش‌های ساده و بدون نیاز به ابزار یا چند مرحله است.

    - -

    جریان ۲: پاسخ مبتنی بر بازیابی (RAG Flow)

    -

    درخواست کاربر ابتدا به بازیابی اطلاعات از منابع مجاز می‌رود، شواهد بازیابی‌شده به مدل تزریق می‌شود و پاسخ با ارجاع به منابع تولید می‌گردد. این جریان برای پرسش‌های دانش‌محور و تحلیل اسناد است.

    - -

    جریان ۳: اجرای چندمرحله‌ای ایجنت (Agentic Flow)

    -

    این جریان، هسته تمایز سامانه است و مستقیماً پاسخ به محور ۱ نیازمندی‌هاست:

    - -
    -
    -
    -
    ۱. دریافت هدف
    -
    هدف کاربر در موتور ایجنت ثبت می‌شود
    -
    -
    ←
    -
    -
    ۲. تولید برنامه
    -
    برنامه‌ریز مراحل اجرایی را تولید می‌کند
    -
    -
    -
    -
    -
    ۳. انتخاب ابزار
    -
    برای هر مرحله ابزار مجاز انتخاب می‌شود
    -
    -
    ←
    -
    -
    ۴. اجرا
    -
    ابزار اجرا و نتیجه دریافت می‌شود
    -
    -
    -
    -
    -
    ۵. ارزیابی نتیجه
    -
    نتیجه با هدف مقایسه می‌شود
    -
    -
    ←
    -
    -
    ۶. اصلاح یا خاتمه
    -
    در صورت نیاز، برنامه اصلاح و ادامه می‌یابد
    -
    -
    -
    -
    -
    نقاط تأیید انسانی
    -
    در عملیات حساس، اجرا متوقف و منتظر تأیید می‌شود
    -
    -
    -
    مدیریت خطا
    -
    در صورت خطا، برنامه بازنگری یا به کاربر اعلام می‌شود
    -
    -
    -
    - -
    - 💡 تمایز ایجنت از Assistant: در جریان ۳، سامانه هدف را به مراحل اجرایی تبدیل می‌کند، ابزار انتخاب می‌کند، عملیات را اجرا می‌کند و بر اساس نتیجه، مراحل بعدی را تعیین یا اصلاح می‌کند. این رفتار حلقه‌ای (Closed-loop) است، در حالی که Assistant صرفاً به یک درخواست پاسخ می‌دهد. این تمایز، دقیقاً همان چیزی است که کارفرما در محور ۱ به‌عنوان قابلیت قابل‌آزمون درخواست کرده است. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    نگاشت نیازمندی‌ها به مولفه‌های معماری

    -
    Requirements-to-Architecture Mapping
    -
    -
    -
    -

    جدول زیر نشان می‌دهد هر محور از نیازمندی‌های کارفرما، توسط کدام لایه‌ها و مولفه‌های معماری پوشش داده می‌شود:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    محور نیازمندیلایه‌های درگیرمولفه‌های کلیدینحوه پوشش
    محور ۱: ماهیت و ایجنتلایه ۳، ۴موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانیجریان ۳ به‌صورت حلقه‌ای و قابل‌آزمون
    محور ۲: دسترسیلایه ۲ + محور عرضیمدیریت نقش‌ها، موتور مجوزها، سنسور محرمانگی، ممیزیدفاع لایه‌ای در دو نقطه مستقل
    محور ۳: پلن و مصرفمحور عرضی + لایه ۶متریک و ردیابی، داشبورد مصرف، درگاه APIاندازه‌گیری در سطح کاربر/مدل/ایجنت
    محور ۴: رابط و گزارشلایه ۱، ۵، ۶رابط وب، نسخه دسکتاپ، مدیریت فایل، تولید گزارش، مبدل قالبپوشش کامل تعامل و خروجی
    محور ۵: حاکمیت دادهمحور عرضی + لایه ۵سیاست‌گذار داده، ممیزی، درگاه مدل‌ها، مدیریت منابعاعمال عرضی در تمام لایه‌ها
    محور ۶: پیاده‌سازی و آموزشهمه لایه‌هاتوسعه‌پذیری مولفه‌ها، رابط‌های تعریف‌شدهامکان سفارشی‌سازی لایه‌ای
    محور ۷: عملکرد و تاب‌آوریمحور عرضی + لایه ۴، ۵متریک و ردیابی، درگاه مدل‌ها، مدیریت منابعامکان استقرار درون‌سازمانی
    -
    -
    - -
    -
    -
    ۷
    -
    -

    ویژگی‌های کیفی معماری

    -
    Architectural Quality Attributes
    -
    -
    -
    -

    معماری کلان باید ویژگی‌های کیفی زیر را تضمین کند که مستقیماً از نیازمندی‌های کارفرما استخراج شده‌اند:

    - -
    - - -
    - -
    -
    -

    تاب‌آوری

    -
      -
    • استقرار درون‌سازمانی
    • -
    • قطع اینترنت عملکرد محلی
    • -
    • مدل‌ها چندگانه
    • -
    -
    -
    -

    توسعه‌پذیری

    -
      -
    • مدل جدید بدون تغییر هسته
    • -
    • ابزار جدید ثبت در فهرست
    • -
    • ایجنت اختصاصی قابل تعریف
    • -
    -
    -
    - -
    - نکته کلیدی: ویژگی «قابلیت آزمون» در این معماری یک ویژگی درجه‌یک است، نه ثانویه. هر مولفه‌ای که رفتار آن قابل مشاهده و اندازه‌گیری نباشد، نمی‌تواند در جلسه دمو و آزمون‌های عملی کارفرما پاسخگو باشد. بنابراین، مرزهای مولفه‌ها و رابط‌های آنها به‌گونه‌ای طراحی شده که هر ادعا، قابل اثبات باشد. -
    -
    -
    - -
    -
    -
    ۸
    -
    -

    جمع‌بندی معماری

    -
    Architecture Summary
    -
    -
    -
    -

    معماری کلان ارائه‌شده، پاسخی سیستماتیک و فارغ از سکو به نیازمندی‌های شرکت پارسا پلیمر شریف است. ویژگی‌های متمایز این معماری:

    - -
      -
    • - ساختار شش‌لایه + دو محور عرضی - جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری در تمام لایه‌ها -
    • -
    • - موتور ایجنت به‌عنوان هسته مستقل - با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا، ارزیابی و اصلاح — قابل مشاهده و آزمون -
    • -
    • - دفاع لایه‌ای برای دسترسی - دو نقطه مستقل کنترل (موتور مجوزها و سنسور محرمانگی) برای پاسخ به آزمون نفوذ کارفرما -
    • -
    • - شفافیت مصرف به‌صورت عرضی - اندازه‌گیری و گزارش در سطح کاربر، مدل، ایجنت و ابزار -
    • -
    • - استقرارپذیری درون‌سازمانی - با انتزاع درگاه مدل‌ها و مدیریت منابع، امکان عملکرد در شرایط قطع اینترنت -
    • -
    • - توسعه‌پذیری بدون تغییر هسته - افزودن مدل‌ها، ابزارها و ایجنت‌های جدید از طریق رابط‌های تعریف‌شده -
    • -
    - -
    - 📞 گام بعدی: این معماری کلان، مبنای طراحی تفصیلی (Detailed Design) و پیاده‌سازی خواهد بود. در گام بعدی، می‌توان طراحی تفصیلی هر لایه، رابط‌های مولفه‌ها، و سناریوی نمونه Agent برای جلسه دمو را تدوین کرد. -
    -
    -
    - -
    -

    🎯 ارزش معماری

    -

    این معماری، پاسخی سیستماتیک، لایه‌ای و فارغ از سکو به نیازمندی‌های فنی و آزمون‌محور کارفرماست.

    -

    هر ادعای قابلیت، دارای مولفه مسئول، رابط تعریف‌شده و رفتار قابل مشاهده است تا در جلسه دمو و آزمون‌های عملی قابل اثبات باشد.

    -
    - 💎 ارزش پیشنهادی معماری:
    - جداسازی دغدغه‌ها + حاکمیت عرضی + ایجنت قابل‌آزمون + دفاع لایه‌ای + شفافیت مصرف + استقرارپذیری -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_7cd76322-fd9c-4970-8e97-18a3308f7b90.html - - - - - - -پیاده‌سازی عملیاتی معماری | سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: IMPL-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - IMPLEMENTATION ROADMAP -

    پیاده‌سازی عملیاتی معماری

    -

    سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework

    -
    -
    - -
    - -
    - کارفرمای محترم،
    - این مستند، نقشه راه عملیاتی پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را با استفاده از استک .NET، Microsoft.Extensions.AI و Microsoft Agent Framework ارائه می‌دهد. رویکرد پیاده‌سازی Cross-Platform است و از کامپایل کدبیس واحد برای سکوهای مختلف (دسکتاپ و موبایل) پشتیبانی می‌کند. هدف، تبدیل معماری به یک محصول قابل ارائه، قابل آزمون و ارزش‌آفرین است. -
    - -
    -
    -
    ۱
    -
    -

    مقدمه: شرح مسئله و ضرورت محصول در عصر AI-Driven

    -
    Problem Statement & AI-Driven Necessity
    -
    -
    -
    -

    سازمان‌های امروزی با انبوهی از داده‌ها، اسناد و فرایندهای پیچیده مواجه‌اند که مدیریت و بهره‌برداری مؤثر از آن‌ها بدون ابزارهای هوشمند، عملاً غیرممکن شده است. در این میان، هوش مصنوعی دیگر یک مزیت رقابتی نیست؛ یک ضرورت بقا است. سازمان‌هایی که نتوانند دانش پراکنده خود را به قالب‌های قابل پرسش، قابل تحلیل و قابل اقدام تبدیل کنند، در برابر رقبای داده‌محور به سرعت عقب می‌مانند.

    - -

    مسئله اصلی، فقدان دسترسی یکپارچه به دانش سازمانی، ناتوانی در تحلیل سریع حجم بالای اسناد، و عدم وجود سازوکاری برای خودکارسازی تصمیم‌گیری‌های چندمرحله‌ای است. راهکارهای سنتی (جستجوی کلیدواژه، پایگاه‌های دانش ایستا، یا چت‌بات‌های ساده) نمی‌توانند پاسخگوی نیاز به استدلال، برنامه‌ریزی و اجرای عملیات باشند.

    - -
    -
    -
    AI
    Driven
    -
    ضرورت بقا در عصر داده
    -
    -
    -
    ایجنت
    محور
    -
    فراتر از چت‌بات ساده
    -
    -
    -
    Cross
    Platform
    -
    کدبیس واحد، چند سکو
    -
    -
    - -
    - نتیجه کلیدی: آنچه سازمان‌ها به آن نیاز دارند، یک سامانه ایجنت‌محور است که بتواند اهداف را به مراحل اجرایی تبدیل کند، ابزار مناسب را انتخاب نماید، عملیات را انجام دهد و بر اساس نتیجه، مسیر خود را اصلاح کند. این مستند، نقشه راه پیاده‌سازی چنین سامانه‌ای را ارائه می‌دهد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    استک فنی و رویکرد پیاده‌سازی

    -
    Technical Stack & Implementation Approach
    -
    -
    -
    -

    استک فنی انتخاب‌شده بر پایه سه اصل استوار است: انتزاع مدل (برای تعویض‌پذیری)، ارکستراسیون ایجنت (برای قابلیت آزمون) و Cross-Platform (برای پوشش سکوهای مختلف با کدبیس واحد).

    - -

    ۲.۱ اجزای استک

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    لایهفناورینقش در معماری
    زبان و پلتفرم.NET 8/10Runtime یکپارچه برای Backend و سرویس‌ها
    انتزاع مدلMicrosoft.Extensions.AIرابط یکپارچه برای اتصال به هر ارائه‌دهنده مدل (IChatClient، IEmbeddingGenerator)
    ارکستراسیون ایجنتMicrosoft Agent Frameworkهسته ایجنت (AIAgent)، گراف چند-ایجنت (WorkflowBuilder)، ثبت ابزار (AIFunctionFactory)، MCP Client
    دسکتاپ Cross-PlatformElectronNET.Coreاجرای Blazor/ASP.NET Core در پوسته Electron برای Windows/macOS/Linux
    موبایل Cross-PlatformIonic + Capacitorرابط WebView با دسترسی به APIهای بومی برای Android/iOS
    - -

    ۲.۲ نقش Microsoft.Extensions.AI

    - -

    این کتابخانه، یک لایه انتزاع برای مدل‌های زبانی فراهم می‌کند. مزایای کلیدی آن در معماری ما:

    - -
      -
    • - IChatClient — رابط یکپارچه مدل‌ها - امکان اتصال به هر ارائه‌دهنده مدل (Azure OpenAI، OpenAI، Ollama و...) بدون تغییر در منطق ایجنت. این انتزاع مستقیماً به نیازمندی «فهرست مجاز مدل‌ها» (محور ۲ نیازمندی‌ها) پاسخ می‌دهد: با تعریف چند IChatClient و اعمال محدودیت در لایه بالاتر، می‌توان مدل مجاز هر کاربر را کنترل کرد. -
    • -
    • - Middleware — تزریق دغدغه‌های عرضی - قابلیت تزریق Telemetry (OpenTelemetry)، Caching و Logging به خط لوله فراخوانی مدل. این ویژگی، پیاده‌سازی محور عرضی مشاهده‌پذیری (Y) را بدون تغییر در منطق اصلی ممکن می‌کند. -
    • -
    • - IEmbeddingGenerator — انتزاع Embedding - رابط یکپارچه برای تولید Embedding در جریان RAG، با قابلیت تعویض ارائه‌دهنده بدون تغییر در منطق بازیابی. -
    • -
    - -

    ۲.۳ نقش Microsoft Agent Framework

    - -

    این فریم‌ورک، نسل بعدی Semantic Kernel و AutoGen است و قابلیت‌های زیر را برای پیاده‌سازی لایه ارکستراسیون (L3) فراهم می‌کند:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    قابلیتکاربرد در معماری
    AIAgentهسته ایجنت؛ تولید برنامه، انتخاب ابزار، اجرا و اصلاح بر اساس نتیجه
    Agent Sessionمدیریت زمینه مکالمه (حافظه کوتاه‌مدت) — مولفه «حافظه و زمینه» در L4
    AIFunctionFactoryثبت ابزارها به‌عنوان توابع قابل فراخوانی توسط LLM — مولفه «انتخاب‌گر ابزار» در L3
    WorkflowBuilderگراف چند-ایجنت (Orchestrator-Worker) با Edges و شرایط — مولفه «مدیریت جریان» در L3
    MCP Clientکشف پویای ابزارها در زمان اجرا — توسعه‌پذیری لایه ابزار
    Middlewareنقاط تأیید انسانی (Human-in-the-loop) — مولفه «تأیید انسانی» در L3
    - -

    ۲.۴ رویکرد Cross-Platform

    - -

    رویکرد Cross-Platform با هدف کامپایل کدبیس واحد برای سکوهای مختلف طراحی شده است:

    - -
    -
    -
    دسکتاپ (Windows/macOS/Linux)
    -
      -
    • استفاده از ElectronNET.Core
    • -
    • اجرای پروژه ASP.NET Core/Blazor در پوسته Electron
    • -
    • کدبیس واحد .NET، خروجی اجرایی برای هر سه سکو
    • -
    • دسترسی کنترل‌شده به فایل‌های محلی
    • -
    -
    -
    -
    موبایل (Android/iOS)
    -
      -
    • استفاده از Ionic + Capacitor
    • -
    • رابط WebView با دسترسی به APIهای بومی
    • -
    • ارتباط با Backend .NET از طریق API
    • -
    • مناسب برای فرم‌ها، چت و داشبوردهای سبک
    • -
    -
    -
    - -
    - 💡 نکته معماری: رابط کاربری اصلی (چت، آپلود فایل، گزارش) در Blazor پیاده‌سازی می‌شود که هم در Electron (دسکتاپ) و هم در مرورگر (وب) قابل اجراست. نسخه موبایل Ionic صرفاً برای سناریوهای سبک (اعلان‌ها، تأییدات) استفاده می‌شود تا از پیچیدگی غیرضروری جلوگیری شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    نقشه راه پیاده‌سازی گام‌به‌گام به تفکیک مولفه‌ها

    -
    Step-by-Step Implementation Roadmap by Component
    -
    -
    -
    -

    پیاده‌سازی در پنج فاز اجرایی سازمان‌دهی شده است. هر فاز، مجموعه‌ای از مولفه‌های معماری را پوشش می‌دهد و با خروجی قابل‌آزمون پایان می‌یابد. ترتیب فازها بر اساس وابستگی فنی و اولویت ارزش‌آفرینی تعیین شده است.

    - - -
    -
    -
    A
    -
    -

    فاز A — هسته ایجنت و رابط پایه

    -
    Core Agent & Base UI
    -
    -
    -
    -

    این فاز، پایه‌ای‌ترین قابلیت محصول را می‌سازد: یک ایجنت که می‌تواند به مدل متصل شود، درخواست کاربر را دریافت کند و پاسخ دهد. بدون این فاز، هیچ قابلیت دیگری قابل ارائه نیست.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    درگاه مدل‌ها (L4)پیاده‌سازی Factory برای IChatClient؛ تعریف چند ارائه‌دهنده (Azure OpenAI، Ollama) و انتخاب بر اساس Configuration—
    موتور ایجنت (L3)ساخت AIAgent با استفاده از chatClient.AsAIAgent()؛ تعریف Instructions برای رفتار پایهدرگاه مدل‌ها
    رابط وب (L1)پیاده‌سازی Blazor Server برای چت پایه؛ اتصال به موتور ایجنت از طریق SignalRموتور ایجنت
    احراز هویت (L2)ASP.NET Core Identity + OIDC برای یکپارچه‌سازی با سامانه هویت سازمانی—
    درگاه API (L1)ASP.NET Core Minimal API برای دسترسی برنامه‌نویسی و یکپارچه‌سازیاحراز هویت
    - -

    خروجی قابل‌آزمون فاز A:

    -
      -
    • چت پایه با ایجنت: کاربر می‌تواند وارد شود، پرسش بپرسد و پاسخ از مدل دریافت کند
    • -
    • تعویض‌پذیری مدل: تغییر مدل از طریق Configuration بدون تغییر کد
    • -
    -
    -
    - - -
    -
    -
    B
    -
    -

    فاز B — ابزارها، RAG و منابع دانش

    -
    Tools, RAG & Knowledge Sources
    -
    -
    -
    -

    این فاز، ایجنت را از یک چت‌بات ساده به یک ایجنت واقعی تبدیل می‌کند: توانایی فراخوانی ابزار و جستجو در منابع دانش سازمانی.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    انتخاب‌گر ابزار (L3)ثبت ابزارها با AIFunctionFactory.Create()؛ تعریف Tool Registry برای مدیریت فهرست ابزارهای مجازموتور ایجنت
    ابزارهای عملیاتی (L5)پیاده‌سازی متدهای C# به‌عنوان Function Tools (جستجو، محاسبه، تبدیل و...)انتخاب‌گر ابزار
    RAG (L4)استفاده از IEmbeddingGenerator برای تولید Embedding؛ ذخیره در Vector Store؛ بازیابی با رعایت سطح دسترسیدرگاه مدل‌ها
    منابع دانش (L5)Indexer برای SharePoint/File System؛ Chunking و ذخیره در Vector StoreRAG
    مدیریت فایل (L5)File API با بررسی مجوز پیش از دسترسی؛ تحلیل چند فایلموتور مجوزها
    حافظه و زمینه (L4)استفاده از AgentSession برای حفظ زمینه مکالمه؛ مدیریت Context Windowموتور ایجنت
    - -

    خروجی قابل‌آزمون فاز B:

    -
      -
    • ایجنت ابزارمحور: ایجنت می‌تواند ابزار فراخوانی کند و نتیجه را در پاسخ به کار گیرد
    • -
    • RAG با ارجاع: پاسخ‌ها با ارجاع به منبع بازیابی‌شده ارائه می‌شوند
    • -
    • دسترسی کنترل‌شده به فایل: کاربر فقط به فایل‌های مجاز دسترسی دارد
    • -
    -
    -
    - - -
    -
    -
    C
    -
    -

    فاز C — حاکمیت داده و کنترل دسترسی

    -
    Data Governance & Access Control
    -
    -
    -
    -

    این فاز، پاسخ مستقیم به آزمون نفوذ دسترسی کارفرما (محور ۲ نیازمندی‌ها) است. بدون این فاز، محصول نمی‌تواند در محیط سازمانی حساس مورد استفاده قرار گیرد.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    موتور مجوزها (L2)Policy-based Authorization در ASP.NET Core؛ پیاده‌سازی ABAC برای کنترل تا سطح سند/رکورداحراز هویت
    مدیریت نقش‌ها (L2)تعریف نقش‌ها و مجوزها؛ تخصیص کاربران واحدهای مختلفاحراز هویت
    مدیریت نشست (L2)AgentSession + Distributed Cache برای حفظ سطح دسترسی فعال در طول تعاملموتور مجوزها
    سیاست‌گذار داده (X)تعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدل؛ Data Classification—
    سنسور محرمانگی (X)Output Filter پیش از ارائه پاسخ؛ شناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسیموتور مجوزها
    ممیزی و لاگ (X)ثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها؛ Tamper-evident Logs—
    - -
    - ⚠️ نکته حیاتی: این فاز باید دفاع لایه‌ای را پیاده‌سازی کند: موتور مجوزها (پیش از فراخوانی مدل) و سنسور محرمانگی (پس از تولید پاسخ). این دو نقطه مستقل، تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مسدود شود. -
    - -

    خروجی قابل‌آزمون فاز C:

    -
      -
    • مدل دسترسی کامل: نقش‌ها، مجوزها و کنترل تا سطح رکورد
    • -
    • سناریوی آزمون نفوذ: پرسش یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها — قابل اجرا در جلسه دمو
    • -
    -
    -
    - - -
    -
    -
    D
    -
    -

    فاز D — گزارش، تأیید انسانی و مشاهده‌پذیری

    -
    Reporting, Human-in-the-loop & Observability
    -
    -
    -
    -

    این فاز، محصول را از یک ابزار تحلیلی به یک محصول سازمانی کامل تبدیل می‌کند.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفه معماریرویکرد پیاده‌سازیوابستگی
    مدیریت جریان (L3)WorkflowBuilder برای گراف چندمرحله‌ای؛ تعریف Edges و شرایط ادامه/اصلاحموتور ایجنت
    تأیید انسانی (L3)Middleware در Agent Framework برای توقف در نقاط حساس؛ Approval API برای دریافت تأییدمدیریت جریان
    تولید گزارش (L6)Razor + QuestPDF/ClosedXML برای تولید خروجی متنی، جدولی و نموداری با ارجاع به منابعموتور ایجنت
    مبدل قالب (L6)تبدیل خروجی به Word، Excel و PDFتولید گزارش
    داشبورد مصرف (L6)Metrics + Blazor Dashboard برای نمایش مصرف و هزینه به تفکیک کاربر، مدل و ایجنتمتریک و ردیابی
    متریک و ردیابی (Y)OpenTelemetry + Serilog برای اندازه‌گیری مصرف توکن، زمان پاسخ و نرخ خطا—
    - -

    خروجی قابل‌آزمون فاز D:

    -
      -
    • گزارش کامل با ارجاع: خروجی Word/Excel با منابع
    • -
    • جریان چندمرحله‌ای با تأیید انسانی: قابل نمایش در جلسه دمو
    • -
    • داشبورد مصرف: شفافیت هزینه به تفکیک کاربر/مدل
    • -
    -
    -
    - - -
    -
    -
    E
    -
    -

    فاز E — Cross-Platform و آماده‌سازی محصول

    -
    Cross-Platform & Product Readiness
    -
    -
    -
    -

    این فاز نهایی، محصول را برای ارائه در سکوهای مختلف و آماده‌سازی برای استقرار سازمانی آماده می‌کند.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مولفهرویکرد پیاده‌سازیوابستگی
    نسخه دسکتاپ (L1)ElectronNET.Core برای بسته‌بندی Blazor در پوسته Electron برای Windows/macOS/Linuxرابط وب
    نسخه موبایل (L1)Ionic + Capacitor برای سناریوهای سبک (اعلان، تأیید)درگاه API
    مدیریت مدل (L4)Model Registry برای نسخه‌بندی و سیاست دسترسی به مدل‌های جدیددرگاه مدل‌ها
    استقرار On-Premiseپشتیبانی از مدل‌های محلی (Ollama) برای عملکرد در قطع اینترنت بین‌المللدرگاه مدل‌ها
    - -

    خروجی قابل‌آزمون فاز E:

    -
      -
    • محصول Cross-Platform: نسخه وب + دسکتاپ + موبایل از کدبیس واحد
    • -
    • تاب‌آوری: عملکرد در شرایط قطع اینترنت بین‌الملل
    • -
    -
    -
    - -
    - ✓ نکته کلیدی: فازهای A تا C، پاسخ به محورهای ۱، ۲ و ۵ نیازمندی‌ها هستند و آمادگی برای جلسه دمو و آزمون عملی کارفرما را فراهم می‌کنند. فازهای D و E، محصول را برای استقرار بلندمدت و پاسخ به محورهای ۴، ۶ و ۷ آماده می‌سازند. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    تیم، تخصص‌ها و مهارت‌های موردنیاز

    -
    Team, Expertise & Required Skills
    -
    -
    -
    -

    پیاده‌سازی این معماری نیازمند تیمی چندنقشی با هم‌پوشانی مهارت‌هاست. جدول زیر نقش‌ها، تخصص‌ها و سطح مهارت موردنیاز را نشان می‌دهد:

    - -

    ۴.۱ جدول نقش‌ها و مهارت‌ها

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نقشتخصص اصلیمهارت‌های کلیدیسطحتعداد
    معمار ارشدطراحی سیستم‌های توزیع‌شده.NET، Agent Framework، الگوهای طراحی، BPMNخبره۱
    توسعه‌دهنده Backend (ایجنت)Microsoft Agent FrameworkAIAgent، AIFunctionFactory، WorkflowBuilder، MCPپیشرفته۲
    توسعه‌دهنده Backend (داده/RAG)RAG و Vector StoreIEmbeddingGenerator، Chunking، Retrievalپیشرفته۱
    توسعه‌دهنده Frontend (Blazor)Blazor + ElectronNETBlazor Server/WASM، CSS، ElectronNETپیشرفته۲
    توسعه‌دهنده موبایل (Ionic)Ionic + CapacitorTypeScript، Angular/React، Capacitor APIمیانی۱
    مهندس امنیتIAM و حاکمیت دادهOAuth 2.0، OIDC، Policy-based Auth، OWASP LLM Top 10پیشرفته۱
    مهندس DevOpsCI/CD و مشاهده‌پذیری.NET Build، OpenTelemetry، Dockerپیشرفته۱
    مهندس تستتست ایجنت و RAGxUnit، Test Containers، Scenario Testingمیانی۱
    - -
    -
    -
    ۱۰
    -
    نفر برای پیاده‌سازی کامل
    -
    -
    -
    ۴
    -
    نفر برای شروع سریع (فاز A)
    -
    -
    -
    ۲
    -
    نقش حیاتی (معمار + ایجنت)
    -
    -
    - -

    ۴.۲ نکات کلیدی تیم

    - -
      -
    • - نقش «توسعه‌دهنده Backend (ایجنت)» حیاتی‌ترین نقش است - این نقش باید به‌طور کامل بر Microsoft Agent Framework مسلط باشد. تسلط بر Semantic Kernel به‌عنوان پیش‌نیاز توصیه می‌شود، زیرا Agent Framework نسل بعدی آن است. -
    • -
    • - معمار ارشد باید هم‌زمان بر .NET و مفاهیم AI مسلط باشد - صرف تسلط بر معماری نرم‌افزار کافی نیست؛ درک عمیق از RAG، Agentic Patterns و محدودیت‌های مدل‌های زبانی ضروری است. -
    • -
    • - مهندس امنیت باید با OWASP LLM Top 10 آشنا باشد - به‌ویژه LLM01 (Prompt Injection) و LLM02 (Sensitive Information Disclosure) که مستقیماً به آزمون نفوذ دسترسی کارفرما مرتبط است. -
    • -
    • - تیم حداقلی برای شروع (فاز A) - معمار ارشد + ۲ توسعه‌دهنده Backend (ایجنت) + ۱ توسعه‌دهنده Blazor = ۴ نفر. این تیم می‌تواند اثبات مفهوم (PoC) را در ۴ تا ۶ هفته ارائه دهد. -
    • -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    ارزش‌آفرینی محصول و معیارهای استاندارد اندازه‌گیری

    -
    Value Creation & Standard Measurement Metrics
    -
    -
    -
    -

    ارزش این محصول را می‌توان بر اساس معیارهای استاندارد اندازه‌گیری کرد. رویکرد ما، استفاده از چارچوب ROI و شاخص‌های کلیدی عملکرد (KPI) است تا ارزش‌آفرینی قابل اثبات و قابل پیگیری باشد.

    - -

    ۵.۱ معیارهای استاندارد اندازه‌گیری ارزش

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    معیارشاخص (KPI)روش اندازه‌گیری
    کارایی عملیاتیکاهش زمان جستجو و تحلیل اسناد (Time-to-Answer)مقایسه زمان قبل/بعد از استقرار
    دقت تصمیمنرخ پاسخ صحیح با ارجاع به منبع (Precision/Recall)ارزیابی نمونه‌ای دوره‌ای
    صرفه‌جویی هزینهکاهش ساعت نیروی انسانی صرف‌شدهمحاسبه ROI (ساعت صرفه‌جویی × نرخ ساعتی)
    رضایت کاربرNPS یا CSAT کاربران سازمانینظرسنجی دوره‌ای
    تاب‌آوریUptime و MTTR (میانگین زمان بازیابی)پایش SLO
    انطباق و امنیتنرخ موفقیت در آزمون نفوذ دسترسیآزمون دوره‌ای (محور ۲ نیازمندی‌ها)
    - -
    - فرمول ROI: بر اساس چارچوب استاندارد ROI، بازگشت سرمایه به‌صورت زیر محاسبه می‌شود:

    - ROI% = [(مجموع منافع) − (هزینه دستیابی + هزینه نگهداری)] ÷ (هزینه دستیابی + هزینه نگهداری) × ۱۰۰ -
    - -

    ۵.۲ ارزش‌های کلیدی برای سازمان

    - -
    - - -
    - -
    -
    -

    کاهش ریسک افشا

    -
      -
    • دفاع لایه‌ای دو نقطه مستقل
    • -
    • ممیزی کامل
    • -
    • انطباق OWASP LLM
    • -
    -
    -
    -

    تاب‌آوری در شرایط تحریم

    -
      -
    • استقرار On-Premise
    • -
    • مدل محلی Ollama
    • -
    • قطع اینترنت بدون اختلال
    • -
    -
    -
    - -

    ۵.۳ تخمین کمی ارزش (نمونه)

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    سناریوفرضصرفه‌جویی سالانه تخمینی
    جستجوی اسناد۵۰ کاربر × ۲ ساعت/هفته صرفه‌جویی۵,۲۰۰ ساعت/سال
    تحلیل قراردادها۲۰ سند/ماه × ۳ ساعت صرفه‌جویی۷۲۰ ساعت/سال
    تولید گزارش۱۰۰ گزارش/سال × ۴ ساعت صرفه‌جویی۴۰۰ ساعت/سال
    جمع صرفه‌جویی—۶,۳۲۰ ساعت/سال
    - -
    - 💡 نکته: با نرخ ساعتی فرضی، بازگشت سرمایه (ROI) معمولاً در ۶ تا ۱۲ ماه قابل تحقق است. این تخمین بر اساس سناریوهای محافظه‌کارانه محاسبه شده و با گسترش استفاده، ارزش واقعی افزایش می‌یابد. -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    جمع‌بندی و گام بعدی

    -
    Summary & Next Step
    -
    -
    -
    -

    این مستند، نقشه راه عملیاتی پیاده‌سازی معماری سامانه هوش مصنوعی سازمانی را با استک .NET + Microsoft.Extensions.AI + Microsoft Agent Framework ارائه داد. جمع‌بندی ویژگی‌های کلیدی:

    - -
      -
    • - استک فنی یکپارچه - Microsoft.Extensions.AI برای انتزاع مدل‌ها، Microsoft Agent Framework برای ارکستراسیون ایجنت، و رویکرد Cross-Platform با ElectronNET (دسکتاپ) و Ionic (موبایل) -
    • -
    • - پنج فاز اجرایی گام‌به‌گام - فاز A (هسته ایجنت) → فاز B (ابزار و RAG) → فاز C (حاکمیت و دسترسی) → فاز D (گزارش و مشاهده‌پذیری) → فاز E (Cross-Platform) -
    • -
    • - تیم ۱۰ نفره - با حداقل ۴ نفر برای شروع سریع (فاز A) در بازه ۴ تا ۶ هفته -
    • -
    • - ارزش‌آفرینی قابل اندازه‌گیری - بر اساس معیارهای استاندارد (کارایی، دقت، هزینه، رضایت، تاب‌آوری، انطباق) و فرمول ROI -
    • -
    • - انطباق با نیازمندی‌ها - فازهای A تا C آمادگی برای جلسه دمو و آزمون عملی کارفرما را فراهم می‌کنند -
    • -
    - -
    -

    🎯 گام بعدی پیشنهادی

    -

    پیاده‌سازی فاز A (هسته: درگاه مدل + موتور ایجنت + رابط Blazor + احراز هویت) به‌عنوان اثبات مفهوم (PoC) در بازه ۴ تا ۶ هفته.

    -

    سپس ارائه در جلسه دمو به کارفرما با تمرکز بر فازهای A تا C برای پاسخ به محورهای ۱، ۲ و ۵ نیازمندی‌ها.

    -
    - 💎 ارزش پیشنهادی:
    - استک یکپارچه .NET + Agent Framework + Cross-Platform + تیم ۱۰ نفره + ارزش‌آفرینی قابل اندازه‌گیری -
    -
    - -
    - 📞 گام بعدی: در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات فاز A و زمان‌بندی PoC هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد. -
    -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8404e5e6-f5fb-4c8f-876e-a293cda84af9.html - - - - - - -نقشه راه دانش فنی | از معماری تا محصول - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: ROAD-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: آبان ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - TECHNICAL KNOWLEDGE ROADMAP -

    نقشه راه دانش فنی

    -

    از معماری تا محصول — سامانه هوش مصنوعی سازمانی

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند، نقشه راه کسب دانش فنی لازم برای پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) و تبدیل آن به محصول قابل ارائه را ترسیم می‌کند. رویکرد این نقشه راه فارغ از سکو است؛ یعنی هیچ زبان برنامه‌نویسی، استک عملیاتی یا ابزار خاصی پیشنهاد نمی‌شود. تمرکز بر استانداردها و الگوهای طراحی و پیاده‌سازی است و مسیر از پایه‌ای‌ترین مباحث تا مباحث کلان معماری را پوشش می‌دهد. هدف، ایجاد توانمندی پایدار در تیم فنی برای پیاده‌سازی، نگهداری و تکامل محصول است. -
    - -
    -
    -
    ۱
    -
    -

    اصول حاکم بر نقشه راه

    -
    Guiding Principles
    -
    -
    -
    -

    این نقشه راه بر پایه اصول زیر طراحی شده است که مستقیماً از الزامات شما و ماهیت معماری محصول استخراج شده‌اند:

    - -
    -
    -
    ◇
    -
    فارغ از سکو
    -

    هیچ زبان، فریم‌ورک یا استک خاصی توصیه نمی‌شود؛ تمرکز بر مفاهیم و الگوهای قابل انتقال.

    -
    -
    -
    ◎
    -
    استانداردمحوری
    -

    تکیه بر استانداردهای شناخته‌شده (BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 42001، NIST AI RMF و...).

    -
    -
    -
    ▤
    -
    الگومحوری
    -

    یادگیری الگوهای طراحی و معماری (لایه‌ای، رویدادمحور، Hexagonal، CQRS، Circuit Breaker و...).

    -
    -
    -
    ↑
    -
    از پایه تا کلان
    -

    شروع از مبانی (داده، شبکه، امنیت) و حرکت تدریجی به سمت معماری کلان و حاکمیت.

    -
    -
    -
    ⟳
    -
    یادگیری تدریجی
    -

    مسیر پیوسته با نقاط عطف مشخص؛ هر فاز، پیش‌نیاز فاز بعدی است.

    -
    -
    -
    ✓
    -
    قابلیت اثبات
    -

    هر فاز با خروجی قابل‌آزمون (Deliverable) پایان می‌یابد تا دانش به مهارت تبدیل شود.

    -
    -
    - -
    - اصل حاکم: هدف این نقشه راه، تربیت معمار و مهندس توانمند است، نه صرفاً آموزش ابزار. بنابراین، در هر فاز، «چرایی» و «الگو» بر «چگونگی ابزار» مقدم است. این رویکرد تضمین می‌کند که دانش کسب‌شده با تغییر سکوها و ابزارها از بین نرود. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    نمای کلی نقشه راه

    -
    Roadmap Overview
    -
    -
    -
    -

    نقشه راه در هفت فاز سازمان‌دهی شده است. هر فاز دارای موضوعات کلیدی، استانداردهای مرتبط و خروجی قابل‌آزمون است. فازها به‌صورت پیوسته طراحی شده‌اند؛ اما تیم‌های با تجربه‌تر می‌توانند برخی موضوعات فازهای ابتدایی را به‌صورت موازی مرور کنند.

    - -
    -
    -
    ۷
    -
    فاز اصلی
    -
    -
    -
    ۴۰+
    -
    موضوع کلیدی
    -
    -
    -
    ۲۵+
    -
    استاندارد و الگو
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    فازعنوانتمرکز اصلیسطح
    ۱مبانی سیستم‌ها و دادهشبکه، داده، مدل داده، رمزنگاری پایهپایه
    ۲مبانی مهندسی نرم‌افزارالگوهای طراحی، معماری تمیز، آزمون‌پذیریپایه
    ۳مبانی هوش مصنوعی و مدل‌هامدل‌های زبانی، Embedding، RAG، ارزیابیمیانی
    ۴معماری سیستم‌های توزیع‌شدهلایه‌بندی، رویدادمحوری، تاب‌آوری، مقیاس‌پذیریمیانی
    ۵معماری ایجنت و ارکستراسیونبرنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، Human-in-the-loopپیشرفته
    ۶امنیت، حاکمیت داده و انطباقOAuth، RBAC/ABAC، محرمانگی، ممیزی، ISO 42001پیشرفته
    ۷معماری کلان، محصول و عملیاتمعماری سازمانی، SRE، مشاهده‌پذیری، مدیریت محصولخبره
    - -
    - 💡 نکته: ترتیب فازها بر اساس وابستگی دانشی است، نه ترتیب زمانی دقیق. تیم‌های با تجربه می‌توانند فازهای ۱ و ۲ را به‌صورت فشرده مرور کنند و تمرکز اصلی را بر فازهای ۳ تا ۷ بگذارند. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    فاز ۱: مبانی سیستم‌ها و داده

    -
    Phase 1 — Foundations of Systems & Data
    -
    -
    -
    -
    -
    -
    ۱
    -
    -

    مبانی سیستم‌ها و داده

    -
    پایه‌ای‌ترین لایه دانش — پیش‌نیاز همه فازها
    -
    -
    -
    -

    این فاز، پایه‌ای‌ترین دانش لازم برای درک هر سیستم نرم‌افزاری و داده‌محور را فراهم می‌کند. بدون تسلط بر این مبانی، درک لایه‌های بالاتر معماری (به‌ویژه حاکمیت داده و امنیت) ناقص خواهد بود.

    - -
    -
    -
    مبانی شبکه و ارتباطات
    -
      -
    • مدل OSI و TCP/IP
    • -
    • HTTP/HTTPS، REST، gRPC (مفهومی)
    • -
    • وب‌سوکت و ارتباطات بلادرنگ
    • -
    • مفاهیم پروکسی، فایروال و DMZ
    • -
    -
    -
    -
    مبانی داده
    -
      -
    • مدل داده رابطه‌ای و NoSQL (مفهومی)
    • -
    • نرمال‌سازی و مدل‌سازی داده
    • -
    • تراکنش و ACID
    • -
    • مفاهیم Data Lake و Data Warehouse
    • -
    -
    -
    -
    مبانی رمزنگاری
    -
      -
    • رمزنگاری متقارن و نامتقارن
    • -
    • هش و امضای دیجیتال
    • -
    • TLS و مدیریت گواهی
    • -
    • مدیریت کلید (Key Management)
    • -
    -
    -
    -
    مبانی سیستم‌عامل و منابع
    -
      -
    • مدیریت پردازش و حافظه
    • -
    • سیستم فایل و مجوزها
    • -
    • مفاهیم Container و مجازی‌سازی
    • -
    • مدیریت منابع (CPU، RAM، I/O)
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - RFC 7230 (HTTP) - RFC 8446 (TLS 1.3) - ISO/IEC 27001 (مبانی امنیت) - NIST SP 800-57 (مدیریت کلید) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • نقشه مفهومی داده سازمان: شناسایی منابع داده، جریان‌ها و مالکیت داده
    • -
    • سند مدل تهدید پایه: شناسایی دارایی‌ها، تهدیدها و کنترل‌های پایه امنیتی
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    فاز ۲: مبانی مهندسی نرم‌افزار

    -
    Phase 2 — Software Engineering Foundations
    -
    -
    -
    -
    -
    -
    ۲
    -
    -

    مبانی مهندسی نرم‌افزار

    -
    الگوهای طراحی، معماری تمیز و آزمون‌پذیری
    -
    -
    -
    -

    این فاز، دانش پایه‌ای مهندسی نرم‌افزار را فراهم می‌کند که برای پیاده‌سازی هر لایه از معماری (از رابط کاربری تا موتور ایجنت) ضروری است. تمرکز بر الگوها است، نه ابزارها.

    - -
    -
    -
    اصول طراحی (SOLID و فراتر)
    -
      -
    • اصول SOLID
    • -
    • DRY، KISS، YAGNI
    • -
    • Separation of Concerns
    • -
    • Dependency Inversion
    • -
    -
    -
    -
    الگوهای طراحی کلاسیک
    -
      -
    • الگوهای سازنده (Factory، Builder)
    • -
    • الگوهای ساختاری (Adapter، Facade)
    • -
    • الگوهای رفتاری (Strategy، Observer)
    • -
    • الگوهای معماری (MVC، MVVM، Clean)
    • -
    -
    -
    -
    معماری تمیز و Hexagonal
    -
      -
    • لایه‌بندی و جهت وابستگی
    • -
    • Ports & Adapters
    • -
    • جداسازی دامنه از زیرساخت
    • -
    • قابلیت تعویض مؤلفه‌ها
    • -
    -
    -
    -
    آزمون‌پذیری
    -
      -
    • هرم آزمون (Unit/Integration/E2E)
    • -
    • Test Double (Mock، Stub، Fake)
    • -
    • Test-Driven Design (مفهومی)
    • -
    • Contract Testing
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - Clean Architecture (Robert C. Martin) - Hexagonal Architecture (Alistair Cockburn) - GoF Design Patterns - ISO/IEC 25010 (کیفیت نرم‌افزار) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند اصول و الگوهای منتخب: تعیین الگوهای پایه برای هر لایه معماری
    • -
    • نمونه اولیه ساختار Hexagonal: پیاده‌سازی یک مؤلفه نمونه با Ports & Adapters
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    فاز ۳: مبانی هوش مصنوعی و مدل‌ها

    -
    Phase 3 — AI & Model Foundations
    -
    -
    -
    -
    -
    -
    ۳
    -
    -

    مبانی هوش مصنوعی و مدل‌ها

    -
    مدل‌های زبانی، Embedding، RAG و ارزیابی
    -
    -
    -
    -

    این فاز، دانش تخصصی هوش مصنوعی و مدل‌های زبانی را فراهم می‌کند که مستقیماً به لایه هوش (L4) معماری مرتبط است. تمرکز بر درک مفهومی و الگوهای استفاده است، نه پیاده‌سازی مدل از صفر.

    - -
    -
    -
    مبانی مدل‌های زبانی
    -
      -
    • معماری Transformer (مفهومی)
    • -
    • توکن‌سازی و Embedding
    • -
    • Temperature، Top-p، Context Window
    • -
    • تفاوت مدل‌های Base و Instruct
    • -
    -
    -
    -
    الگوهای استفاده از مدل
    -
      -
    • Prompt Engineering اصولی
    • -
    • Few-shot و Chain-of-Thought
    • -
    • Structured Output (JSON Mode)
    • -
    • Function Calling / Tool Use
    • -
    -
    -
    -
    بازیابی و تقویت (RAG)
    -
      -
    • مفاهیم Vector Database
    • -
    • Chunking و Indexing
    • -
    • Retrieval Strategies
    • -
    • Citation و Source Attribution
    • -
    -
    -
    -
    ارزیابی و کیفیت
    -
      -
    • معیارهای ارزیابی پاسخ
    • -
    • Hallucination Detection
    • -
    • Benchmarking مدل‌ها
    • -
    • A/B Testing برای Prompt
    • -
    -
    -
    -
    مدیریت مدل
    -
      -
    • نسخه‌بندی مدل‌ها
    • -
    • مدل‌های داخلی در برابر خارجی
    • -
    • هزینه و مصرف توکن
    • -
    • سیاست دسترسی به مدل‌های جدید
    • -
    -
    -
    -
    اخلاق و مخاطرات AI
    -
      -
    • Bias و Fairness
    • -
    • Privacy در مدل‌ها
    • -
    • Explainability
    • -
    • مسئولیت‌پذیری
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - NIST AI RMF - ISO/IEC 42001 (مدیریت AI) - OECD AI Principles - Attention Is All You Need (مرجع Transformer) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند ارزیابی مدل‌ها: مقایسه مدل‌های نامزد بر اساس معیارهای کیفیت، هزینه و حاکمیت
    • -
    • نمونه اولیه RAG: پیاده‌سازی یک جریان بازیابی و تقویت با ارجاع به منبع
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۶
    -
    -

    فاز ۴: معماری سیستم‌های توزیع‌شده

    -
    Phase 4 — Distributed Systems Architecture
    -
    -
    -
    -
    -
    -
    ۴
    -
    -

    معماری سیستم‌های توزیع‌شده

    -
    لایه‌بندی، رویدادمحوری، تاب‌آوری و مقیاس‌پذیری
    -
    -
    -
    -

    این فاز، دانش معماری سیستم‌های توزیع‌شده را فراهم می‌کند که برای پیاده‌سازی لایه‌های L1 تا L6 و محورهای عرضی ضروری است. تمرکز بر الگوهای معماری است، نه محصولات خاص.

    - -
    -
    -
    الگوهای معماری لایه‌ای
    -
      -
    • Layered Architecture
    • -
    • Hexagonal / Ports & Adapters
    • -
    • Microservices و Modular Monolith
    • -
    • API Gateway Pattern
    • -
    -
    -
    -
    رویدادمحوری و پیام‌رسانی
    -
      -
    • Event-Driven Architecture
    • -
    • Publish-Subscribe Pattern
    • -
    • Event Sourcing و CQRS (مفهومی)
    • -
    • Saga Pattern برای تراکنش‌های توزیع‌شده
    • -
    -
    -
    -
    تاب‌آوری (Resilience)
    -
      -
    • Circuit Breaker
    • -
    • Retry و Backoff
    • -
    • Bulkhead و Rate Limiting
    • -
    • Graceful Degradation
    • -
    -
    -
    -
    مقیاس‌پذیری و عملکرد
    -
      -
    • Load Balancing (مفهومی)
    • -
    • Caching Strategies
    • -
    • Async Processing
    • -
    • Backpressure
    • -
    -
    -
    -
    هماهنگی توزیع‌شده
    -
      -
    • Service Discovery
    • -
    • Configuration Management
    • -
    • Distributed Locking
    • -
    • Idempotency
    • -
    -
    -
    -
    مشاهده‌پذیری (Observability)
    -
      -
    • Logging، Metrics، Tracing
    • -
    • OpenTelemetry (مفهومی)
    • -
    • Health Check و Readiness
    • -
    • Alerting Strategies
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - Enterprise Integration Patterns (Hohpe & Woolf) - Release It! (Michael Nygard) - OpenTelemetry Specification - BPMN 2.0 (برای مدل‌سازی فرایند) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند الگوهای معماری منتخب: تعیین الگوهای لایه‌بندی، رویدادمحوری و تاب‌آوری برای هر لایه
    • -
    • نقشه BPMN2 تکمیلی: به‌روزرسانی نقشه فرایندی با الگوهای تاب‌آوری و خطا
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    فاز ۵: معماری ایجنت و ارکستراسیون

    -
    Phase 5 — Agent Architecture & Orchestration
    -
    -
    -
    -
    -
    -
    ۵
    -
    -

    معماری ایجنت و ارکستراسیون

    -
    هسته تمایز محصول — برنامه‌ریزی، انتخاب ابزار و حلقه بازخورد
    -
    -
    -
    -

    این فاز، تخصصی‌ترین بخش نقشه راه است و مستقیماً به لایه ارکستراسیون (L3) و پاسخ به محور ۱ نیازمندی‌های کارفرما مرتبط می‌شود. تمرکز بر الگوهای طراحی ایجنت و قابلیت آزمون است.

    - -
    -
    -
    مفاهیم پایه ایجنت
    -
      -
    • تفاوت Agent، Assistant و Workflow
    • -
    • حلقه تصمیم‌گیری (Observe-Think-Act)
    • -
    • Autonomy Levels
    • -
    • Goal vs Task vs Step
    • -
    -
    -
    -
    الگوهای برنامه‌ریزی
    -
      -
    • ReAct (Reasoning + Acting)
    • -
    • Plan-and-Execute
    • -
    • Tree of Thoughts
    • -
    • Reflexion و Self-Correction
    • -
    -
    -
    -
    مدیریت ابزار (Tool Use)
    -
      -
    • Tool Registry و Discovery
    • -
    • Tool Selection Strategies
    • -
    • Tool Result Validation
    • -
    • Error Handling در ابزار
    • -
    -
    -
    -
    حافظه و زمینه
    -
      -
    • Short-term vs Long-term Memory
    • -
    • Context Window Management
    • -
    • Summarization Strategies
    • -
    • Memory Isolation بر اساس دسترسی
    • -
    -
    -
    -
    Human-in-the-loop
    -
      -
    • نقاط تأیید انسانی
    • -
    • Approval Workflows
    • -
    • Escalation Patterns
    • -
    • Audit Trail تصمیمات
    • -
    -
    -
    -
    چند-ایجنت (Multi-Agent)
    -
      -
    • Orchestrator-Worker Pattern
    • -
    • Agent Communication Protocols
    • -
    • Shared Memory و Coordination
    • -
    • Conflict Resolution
    • -
    -
    -
    -
    ارزیابی ایجنت
    -
      -
    • Task Success Rate
    • -
    • Step Efficiency
    • -
    • Error Recovery Rate
    • -
    • Scenario-based Testing
    • -
    -
    -
    -
    ایمنی و کنترل
    -
      -
    • Guardrails و Constraints
    • -
    • Action Whitelisting
    • -
    • Sandboxing (مفهومی)
    • -
    • Kill Switch و Rollback
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - ReAct (Yao et al.) - Reflexion (Shinn et al.) - Model Context Protocol (MCP) — مفهومی - NIST AI RMF (بخش کنترل) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سناریوی نمونه Agent: پیاده‌سازی یک سناریوی چندمرحله‌ای با ابزار، خطا و مداخله انسانی — قابل ارائه در جلسه دمو
    • -
    • چارچوب ارزیابی ایجنت: معیارها و روش‌های آزمون رفتار ایجنت
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۸
    -
    -

    فاز ۶: امنیت، حاکمیت داده و انطباق

    -
    Phase 6 — Security, Data Governance & Compliance
    -
    -
    -
    -
    -
    -
    ۶
    -
    -

    امنیت، حاکمیت داده و انطباق

    -
    محور عرضی حاکمیت — پاسخ به آزمون نفوذ کارفرما
    -
    -
    -
    -

    این فاز، دانش لازم برای پیاده‌سازی محور عرضی حاکمیت داده (X) و پاسخ به محورهای ۲ و ۵ نیازمندی‌های کارفرما را فراهم می‌کند. تمرکز بر الگوهای امنیتی و استانداردهای انطباق است.

    - -
    -
    -
    احراز هویت و مجوزدهی
    -
      -
    • OAuth 2.0 و OpenID Connect
    • -
    • JWT و Session Management
    • -
    • RBAC (نقش‌محور)
    • -
    • ABAC (ویژگی‌محور)
    • -
    -
    -
    -
    کنترل دسترسی پیشرفته
    -
      -
    • ReBAC (رابطه‌محور)
    • -
    • Fine-grained Access Control
    • -
    • Row-level و Document-level Security
    • -
    • Policy-as-Code
    • -
    -
    -
    -
    محرمانگی داده
    -
      -
    • Data Classification
    • -
    • Data Loss Prevention (DLP)
    • -
    • Data Masking و Redaction
    • -
    • Output Filtering (سنسور محرمانگی)
    • -
    -
    -
    -
    ممیزی و ردگیری
    -
      -
    • Audit Logging
    • -
    • Tamper-evident Logs
    • -
    • Traceability تصمیمات
    • -
    • Retention Policies
    • -
    -
    -
    -
    امنیت مدل و AI
    -
      -
    • Prompt Injection
    • -
    • Jailbreak Detection
    • -
    • Data Poisoning (مفهومی)
    • -
    • Model Inversion و Extraction
    • -
    -
    -
    -
    انطباق و حاکمیت
    -
      -
    • ISO/IEC 27001
    • -
    • ISO/IEC 42001 (مدیریت AI)
    • -
    • NIST AI RMF
    • -
    • GDPR (مفهومی) و قوانین داخلی
    • -
    -
    -
    -
    امنیت زیرساخت
    -
      -
    • OWASP Top 10
    • -
    • OWASP API Security Top 10
    • -
    • OWASP LLM Top 10
    • -
    • Secure by Design
    • -
    -
    -
    -
    حاکمیت داده سازمانی
    -
      -
    • Data Ownership و Stewardship
    • -
    • Data Lineage
    • -
    • Data Quality Management
    • -
    • Policy Enforcement Points
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - OAuth 2.0 (RFC 6749) - OpenID Connect Core - OWASP Top 10 / API / LLM - ISO/IEC 27001 - ISO/IEC 42001 - NIST AI RMF -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند مدل دسترسی و حاکمیت داده: تعریف نقش‌ها، سطوح دسترسی و سیاست‌های داده
    • -
    • سناریوی آزمون نفوذ دسترسی: طراحی آزمون‌های پرسش مستقیم/غیرمستقیم برای اثبات عدم افشا — قابل اجرا در جلسه دمو
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    فاز ۷: معماری کلان، محصول و عملیات

    -
    Phase 7 — Enterprise Architecture, Product & Operations
    -
    -
    -
    -
    -
    -
    ۷
    -
    -

    معماری کلان، محصول و عملیات

    -
    از معماری به محصول قابل ارائه و پایدار
    -
    -
    -
    -

    این فاز، دانش لازم برای تبدیل معماری به محصول قابل ارائه و عملیات پایدار را فراهم می‌کند. تمرکز بر معماری سازمانی، مدیریت محصول و عملیات است.

    - -
    -
    -
    معماری سازمانی
    -
      -
    • TOGAF (مفهومی)
    • -
    • Zachman Framework (مفهومی)
    • -
    • Architecture Decision Records (ADR)
    • -
    • Capability Mapping
    • -
    -
    -
    -
    مدیریت محصول
    -
      -
    • Product Vision و Roadmap
    • -
    • Prioritization Frameworks
    • -
    • Product-Market Fit
    • -
    • Feature Flagging
    • -
    -
    -
    -
    عملیات و SRE
    -
      -
    • SLI/SLO/SLA
    • -
    • Error Budget
    • -
    • Incident Management
    • -
    • Postmortem Culture
    • -
    -
    -
    -
    مشاهده‌پذیری پیشرفته
    -
      -
    • Distributed Tracing
    • -
    • Log Aggregation
    • -
    • Metrics و Dashboards
    • -
    • Anomaly Detection
    • -
    -
    -
    -
    مصرف و هزینه
    -
      -
    • Token Accounting
    • -
    • Cost Attribution
    • -
    • Quota Management
    • -
    • Usage Reporting
    • -
    -
    -
    -
    مدیریت تغییر و انتشار
    -
      -
    • Release Strategies
    • -
    • Blue-Green و Canary (مفهومی)
    • -
    • Rollback Strategies
    • -
    • Versioning Policies
    • -
    -
    -
    -
    مستندسازی و آموزش
    -
      -
    • Architecture Documentation
    • -
    • API Documentation (OpenAPI)
    • -
    • Runbook و Playbook
    • -
    • Training Programs
    • -
    -
    -
    -
    توسعه تیم و فرهنگ
    -
      -
    • Team Topologies (مفهومی)
    • -
    • Knowledge Sharing
    • -
    • Code Review Culture
    • -
    • Continuous Learning
    • -
    -
    -
    - -

    استانداردها و مراجع کلیدی:

    -
    - TOGAF ADM - Google SRE Book - OpenAPI Specification - Architecture Decision Records (ADR) - ISO/IEC 20000 (مدیریت خدمت) -
    - -

    خروجی قابل‌آزمون (Deliverable):

    -
      -
    • سند معماری محصول: نگاشت معماری کلان به قابلیت‌های محصول و نقشه راه انتشار
    • -
    • سند SLA و SLO: تعریف تعهد سطح خدمت و شاخص‌های کلیدی عملکرد — پاسخ به محور ۷ نیازمندی‌ها
    • -
    -
    -
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    ماتریس مهارت تیم

    -
    Team Skill Matrix
    -
    -
    -
    -

    جدول زیر، ماتریس مهارت پیشنهادی برای تیم فنی را نشان می‌دهد. سطح موردنیاز برای هر نقش، بر اساس فازهای نقشه راه تعیین شده است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نقش / حوزه مهارتفاز ۱-۲فاز ۳-۴فاز ۵-۶فاز ۷
    مهندس نرم‌افزارپیشرفتهمیانیپایهپایه
    مهندس دادهپیشرفتهمیانیمیانیپایه
    مهندس هوش مصنوعیپایهپیشرفتهپیشرفتهمیانی
    معمار سیستممیانیپیشرفتهپیشرفتهخبره
    مهندس امنیتمیانیپایهخبرهپیشرفته
    مهندس عملیات / SREمیانیمیانیمیانیپیشرفته
    مدیر محصولپایهپایهمیانیخبره
    - -
    - 💡 نکته: این ماتریس نشان می‌دهد که هیچ نقشی به‌تنهایی تمام فازها را پوشش نمی‌دهد. تیم چندنقشی با هم‌پوشانی مهارت‌ها، کلید موفقیت است. در تیم‌های کوچک، افراد باید در چند نقش (مثلاً مهندس نرم‌افزار + مهندس AI) مهارت داشته باشند. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    نقاط عطف و گام‌های اجرایی

    -
    Milestones & Execution Steps
    -
    -
    -
    -

    نقشه راه در قالب پنج نقطه عطف قابل پیگیری است. هر نقطه عطف، تجمیع خروجی چند فاز و نشان‌دهنده آمادگی برای گام بعدی است:

    - -
    -
    M1
    -
    -
    آمادگی پایه
    -

    تکمیل فازهای ۱ و ۲ — تیم بر مبانی داده، شبکه، امنیت پایه و الگوهای مهندسی نرم‌افزار مسلط است. خروجی: نقشه داده سازمان + سند اصول و الگوهای منتخب.

    -
    -
    - -
    -
    M2
    -
    -
    آمادگی هوش مصنوعی
    -

    تکمیل فاز ۳ — تیم قادر به ارزیابی مدل‌ها، طراحی RAG و ارزیابی کیفیت پاسخ است. خروجی: سند ارزیابی مدل‌ها + نمونه اولیه RAG.

    -
    -
    - -
    -
    M3
    -
    -
    آمادگی معماری توزیع‌شده
    -

    تکمیل فاز ۴ — تیم قادر به طراحی لایه‌بندی، رویدادمحوری و تاب‌آوری است. خروجی: سند الگوهای معماری منتخب + نقشه BPMN2 تکمیلی.

    -
    -
    - -
    -
    M4
    -
    -
    آمادگی ایجنت و حاکمیت
    -

    تکمیل فازهای ۵ و ۶ — تیم قادر به پیاده‌سازی ایجنت قابل‌آزمون و اعمال حاکمیت داده است. خروجی: سناریوی نمونه Agent + سناریوی آزمون نفوذ دسترسی — آماده برای جلسه دمو کارفرما.

    -
    -
    - -
    -
    M5
    -
    -
    آمادگی محصول
    -

    تکمیل فاز ۷ — تیم قادر به تبدیل معماری به محصول قابل ارائه، عملیات پایدار و مدیریت چرخه عمر است. خروجی: سند معماری محصول + سند SLA و SLO.

    -
    -
    - -
    - ✓ نکته کلیدی: نقطه عطف M4 دقیقاً منطبق بر نیاز کارفرما برای جلسه دمو و آزمون عملی است. یعنی با تکمیل فازهای ۱ تا ۶، تیم آمادگی کامل برای پاسخ به محورهای ۱ تا ۶ نیازمندی‌ها را دارد. فاز ۷ برای پایداری بلندمدت محصول و پاسخ به محور ۷ (SLA و پایلوت) است. -
    -
    -
    - -
    -
    -
    ۱۲
    -
    -

    نگاشت نقشه راه به معماری و نیازمندی‌ها

    -
    Roadmap-to-Architecture & Requirements Mapping
    -
    -
    -
    -

    جدول زیر نشان می‌دهد هر فاز نقشه راه، کدام لایه‌های معماری (ARCH-1405-001) و کدام محورهای نیازمندی (REQ-1405-001) را پوشش می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    فازلایه‌های معماریمحورهای نیازمندینقش کلیدی
    فاز ۱پایه همه لایه‌هاپیش‌نیاز محور ۲، ۵مهندس داده، مهندس امنیت
    فاز ۲L1 تا L6 (الگوها)پیش‌نیاز همه محورهامهندس نرم‌افزار، معمار
    فاز ۳L4 (هوش و مدل‌ها)محور ۱، ۴مهندس AI
    فاز ۴L1 تا L6 + Yمحور ۳، ۷معمار سیستم، SRE
    فاز ۵L3 (ارکستراسیون)محور ۱ (ایجنت)مهندس AI، معمار
    فاز ۶X (حاکمیت) + L2محور ۲، ۵مهندس امنیت
    فاز ۷L6 + Y + همه لایه‌هامحور ۳، ۶، ۷معمار، مدیر محصول، SRE
    -
    -
    - -
    -
    -
    ۱۳
    -
    -

    جمع‌بندی و مسیر پیشنهادی

    -
    Summary & Recommended Path
    -
    -
    -
    -

    نقشه راه ارائه‌شده، مسیری پیوسته و فارغ از سکو برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول است. ویژگی‌های کلیدی:

    - -
      -
    • - هفت فاز پیوسته - از مبانی سیستم‌ها و داده تا معماری کلان، محصول و عملیات — با وابستگی دانشی مشخص -
    • -
    • - فارغ از سکو - هیچ زبان، فریم‌ورک یا استک خاصی توصیه نشده؛ تمرکز بر مفاهیم و الگوهای قابل انتقال -
    • -
    • - استانداردمحوری - تکیه بر BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 27001/42001، NIST AI RMF و... -
    • -
    • - الگومحوری - یادگیری الگوهای طراحی و معماری (Hexagonal، Event-Driven، Circuit Breaker، ReAct، Plan-and-Execute و...) -
    • -
    • - خروجی قابل‌آزمون - هر فاز با Deliverable مشخص پایان می‌یابد تا دانش به مهارت تبدیل شود -
    • -
    • - انطباق با نیازمندی‌ها - نقطه عطف M4 دقیقاً منطبق بر آمادگی برای جلسه دمو و آزمون عملی کارفرماست -
    • -
    - -
    - مسیر پیشنهادی: برای شروع، توصیه می‌شود تیم فنی ابتدا فازهای ۱ و ۲ را به‌صورت فشرده مرور کند (به‌ویژه اگر تجربه مهندسی نرم‌افزار دارد)، سپس تمرکز اصلی را بر فازهای ۳، ۴ و ۵ بگذارد که هسته تمایز محصول هستند. فازهای ۶ و ۷ می‌توانند به‌صورت موازی با فازهای ۴ و ۵ پیش بروند تا نقطه عطف M4 در کوتاه‌ترین زمان محقق شود. -
    -
    -
    - -
    -

    🎯 ارزش این نقشه راه

    -

    این نقشه راه، مسیری شفاف، فارغ از سکو و استانداردمحور برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول ارائه می‌دهد.

    -

    هر فاز با خروجی قابل‌آزمون پایان می‌یابد و نقطه عطف M4، آمادگی کامل برای جلسه دمو و آزمون عملی کارفرما را تضمین می‌کند.

    -
    - 💎 ارزش پیشنهادی:
    - مسیر پیوسته از پایه تا کلان + فارغ از سکو + استانداردمحور + الگومحور + خروجی قابل‌آزمون + انطباق با نیازمندی‌ها -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8d5bef83-5974-4a98-a41a-863c459267ff.html - - - - - - -تحلیل و رفع مشکل احراز هویت XApiKey در xIds - - - - -
    - - -
    -
    -
    - -
    -
    xSaherelmWorkspace
    -
    Technical Analysis Document
    -
    -
    -
    -
    شماره مستند: XIDS-AUTH-2026-001
    -
    نسخه: ۱.۰
    -
    موضوع: رفع مشکل احراز هویت XApiKey
    -
    طبقه‌بندی: داخلی — فنی
    -
    -
    - -
    - TECHNICAL DIAGNOSIS & SOLUTION -

    ریشه‌یابی و رفع مشکل احراز هویت با XApiKey در xIds

    -
    - تحلیل جامع کد، شناسایی گلوگاه احراز هویت، و ارائه راه‌حل گام‌به‌گام برای فعال‌سازی کامل - Authentication مبتنی بر API Key در سرور IdentityServer4 -
    -
    -
    - - -
    - -
    - خلاصه اجرایی:
    - پس از بررسی کامل کدهای پروژه xIds، مشخص شد که زیرساخت مدیریت Application و - تولید XApiKey به‌درستی پیاده‌سازی شده است، اما زنجیره احراز هویت مبتنی بر API Key - در سمت سرور IdentityServer4 ناقص مانده است. این سند ابتدا ریشه مشکل را با استناد به کدهای - موجود تشریح می‌کند، سپس راه‌حل کامل گام‌به‌گام را ارائه می‌دهد. -
    - - - - -
    -
    -
    ۱
    -
    -

    وضعیت فعلی سیستم

    -
    Current State Analysis
    -
    -
    -
    -

    - در پروژه xIds، اجزای زیر برای مدیریت Application و API Key پیاده‌سازی شده‌اند: -

    - -

    ۱.۱ — اجزای پیاده‌سازی‌شده

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    جزءمسیر فایلوضعیت
    مدل‌های Application و ApiKeyxIdentityModels/Models/XApplication.cs✓ موجود
    XApplicationProvider (مدیریت API Key)xIds/Providers/XApplicationProvider.cs✓ موجود
    XApiKeyHelper (تولید و هش)xIds/Helpers/XApiKeyHelper.cs✓ موجود
    ApplicationsController (Endpointها)xIds/Controllers/ApplicationsController.cs✓ موجود
    XApiKeyAuthenticationHandlerxIds/Providers/XApiKeyAuthenticationHandler.cs⚠ موجود اما ناقص
    XApiKeyConfigurationxIds/Configurations/XApiKeyConfiguration.cs✓ موجود
    ثبت Scheme در StartupxIds/Startup.cs✓ موجود
    - -

    ۱.۲ — معماری جاری احراز هویت در Startup.cs

    - -
    -// xIds/Startup.cs -services.AddXIdentityServerAuthentication( - configuration: Configuration, - addApiKeyAuthentication: true // ← این خط فعال است -); -
    - -

    - و در XDIHelperExtension.AddXIdentityServerAuthentication: -

    - -
    -var authBuilder = services.AddAuthentication(); - -authBuilder.AddJwtBearer(options => -{ - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; -}) -.AddLocalApi(); - -if (addApiKeyAuthentication) -{ - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), // "XApiKey" - options => {} - ); -} -
    - -
    - نتیجه: به نظر می‌رسد همه چیز در Startup به‌درستی ثبت شده است. اما در عمل، درخواست‌هایی - که Header X-Api-Key دارند، احراز هویت نمی‌شوند. علت چیست؟ -
    -
    -
    - - - - -
    -
    -
    ۲
    -
    -

    ریشه‌یابی مشکل

    -
    Root Cause Analysis
    -
    -
    -
    -

    - پس از بررسی دقیق کدها، سه ریشه اصلی برای عدم کارکرد احراز هویت با XApiKey شناسایی شد: -

    - - -
    -
    - 🔴 - مشکل ۱: ForwardDefaultSelector به XApiKey توجه نمی‌کند -
    -

    - در AddJwtBearer، تنظیم ForwardDefault روی - XAuthentication.IDENTITY_SERVER_LOCAL_API قرار داده شده است. این یعنی - ASP.NET Core همیشه از Scheme پیش‌فرض (IdentityServerAccessToken) استفاده می‌کند - و هیچ‌گاه به Scheme با نام XApiKey نمی‌رسد. -

    -
    -// xIds/DI/XDIHelperExtension.cs — AddXIdentityServerAuthentication -authBuilder.AddJwtBearer(options => -{ - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; // ← مشکل اصلی اینجاست -}) -
    -
    - - -
    -
    - 🔴 - مشکل ۲: ترتیب ثبت Schemeها اشتباه است -
    -

    - در ASP.NET Core، اولین Scheme ثبت‌شده، Scheme پیش‌فرض است. در کد فعلی، - AddJwtBearer قبل از AddScheme<...XApiKeyAuthenticationHandler> ثبت - می‌شود و این باعث می‌شود حتی اگر Header X-Api-Key ارسال شود، Handler مربوطه - هرگز فراخوانی نگردد. -

    -
    - - -
    -
    - 🔴 - مشکل ۳: XApiKeyAuthenticationHandler به Claimهای Policyهای موجود پاسخ نمی‌دهد -
    -

    - Policyهای موجود در XAuthorizationHelper (مانند ApiKeyAccess و - ApiKeyReadAccess) انتظار Claim از نوع JwtClaimTypes.Scope با مقادیر - read، write، admin یا manage دارند. - اما XApiKeyAuthenticationHandler فعلی در کد، یک Scope ثابت به نام - "apikey" اضافه می‌کند که با هیچ Policy موجودی مطابقت ندارد. -

    -
    -// xIds/Providers/XApiKeyAuthenticationHandler.cs — کد فعلی -var claims = new[] -{ - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim("application_id", validationResult.ApplicationId.ToString()), - new Claim("auth_type", "apikey"), - new Claim(JwtClaimTypes.Scope, "apikey"), // ← هیچ Policyای این Scope را نمی‌شناسد -}; - -// سپس scopes از validationResult اضافه می‌شود، اما با مقادیر "read", "write"... -// که با Policyهای XAuthorizationHelper همخوانی ندارند -
    -
    - -

    ۲.۱ — درخت عیب‌یابی

    - -
    -
    -
    ✗
    -
    -
    درخواست با Header: X-Api-Key: xapp_xxxxx
    -

    Header به درستی در Request وجود دارد.

    -
    -
    -
    -
    ✗
    -
    -
    ASP.NET Core می‌خواهد Scheme پیش‌فرض را انتخاب کند
    -

    به دلیل ForwardDefault = IDENTITY_SERVER_LOCAL_API، همیشه Scheme پیش‌فرض انتخاب می‌شود.

    -
    -
    -
    -
    ✗
    -
    -
    XApiKeyAuthenticationHandler فراخوانی نمی‌شود
    -

    چون هیچ‌گاه انتخاب نمی‌شود، متد HandleAuthenticateAsync اجرا نمی‌گردد.

    -
    -
    -
    -
    ✗
    -
    -
    درخواست با خطای 401 Unauthorized رد می‌شود
    -

    پایان مسیر — احراز هویت شکست خورده است.

    -
    -
    -
    - -
    - ⚠️ خلاصه ریشه مشکل: در معماری فعلی، ASP.NET Core با - ForwardDefault به Scheme پیش‌فرض هدایت می‌شود و هرگز به Scheme - XApiKey نمی‌رسد. علاوه بر این، حتی اگر Handler فراخوانی شود، Claimهای - تولیدشده با Policyهای موجود همخوانی ندارند و در نتیجه Authorization نیز شکست می‌خورد. -
    -
    -
    - - - - -
    -
    -
    ۳
    -
    -

    نمودار جریان فعلی در مقابل جریان مطلوب

    -
    Current vs. Desired Auth Flow
    -
    -
    -
    -

    ۳.۱ — جریان فعلی (معیوب)

    - -
    -
    -
    -
    -
    ۱. Client Request
    -

    ارسال درخواست با Header X-Api-Key

    -
    -
    -
    ▼
    -
    -
    -
    ۲. Default Scheme Selection
    -

    ASP.NET Core به دلیل ForwardDefault، Scheme پیش‌فرض را انتخاب می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۳. JwtBearer Handler اجرا می‌شود
    -

    به‌دنبال Bearer Token می‌گردد، پیدا نمی‌کند، شکست می‌خورد

    -
    -
    -
    ▼
    -
    -
    -
    ❌ نتیجه: 401 Unauthorized
    -

    XApiKeyAuthenticationHandler هرگز اجرا نمی‌شود

    -
    -
    -
    -
    - -

    ۳.۲ — جریان مطلوب (پس از راه‌حل)

    - -
    -
    -
    -
    -
    ۱. Client Request
    -

    ارسال درخواست با Header X-Api-Key

    -
    -
    -
    ▼
    -
    -
    -
    ۲. ForwardDefaultSelector اجرا می‌شود
    -

    وجود Header X-Api-Key را تشخیص می‌دهد و Scheme XApiKey را انتخاب می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۳. XApiKeyAuthenticationHandler.HandleAuthenticateAsync
    -

    API Key را استخراج و ValidateApiKey را فراخوانی می‌کند

    -
    -
    -
    ▼
    -
    -
    -
    ۴. Claims تولید می‌شوند
    -

    Scopeهای واقعی از validationResult.Scopes به Claims اضافه می‌شوند

    -
    -
    -
    ▼
    -
    -
    -
    ۵. Policy-Based Authorization
    -

    Policyهای ApiKeyAccess و ApiKeyReadAccess با موفقیت بررسی می‌شوند

    -
    -
    -
    ▼
    -
    -
    -
    ✅ نتیجه: 200 OK + Response
    -

    دسترسی به Endpoint مورد نظر با موفقیت انجام می‌شود

    -
    -
    -
    -
    -
    -
    - - - - -
    -
    -
    ۴
    -
    -

    راه‌حل گام‌به‌گام

    -
    Step-by-Step Solution
    -
    -
    -
    - - -
    -
    -
    ۱
    -
    - اصلاح ForwardDefaultSelector در Startup - فایل: xIds/DI/XDIHelperExtension.cs -
    -
    -
    -

    - باید یک ForwardDefaultSelector تنظیم شود که بر اساس وجود Header - X-Api-Key در Request، Scheme صحیح را انتخاب کند. این Selector - برای تمام Schemeها (نه فقط JwtBearer) باید فعال باشد. -

    - -
    -// xIds/DI/XDIHelperExtension.cs — بخش AddXIdentityServerAuthentication - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false -) -{ - services.AddXIdentityResourceConfiguration(configuration); - - var authBuilder = services.AddAuthentication(); - - // ═══ ۱. ثبت Scheme برای XApiKey (اول از همه) - if (addApiKeyAuthentication) - { - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), - options => {} - ); - } - - // ═══ ۲. ثبت JwtBearer با ForwardDefaultSelector هوشمند - authBuilder.AddJwtBearer(options => - { - options.SaveToken = true; - options.RequireHTTPSMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; - - // ═══ ۳. انتخاب Scheme بر اساس Header درخواست - options.ForwardDefaultSelector = context => - { - // اگر Header X-Api-Key وجود دارد → از Scheme XApiKey استفاده کن - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); // "X-Api-Key" - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - - // در غیر این صورت، Scheme پیش‌فرض (LocalApi برای IdentityServer) - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddLocalApi(); -} -
    - -
    - 💡 چرا این راه‌حل کار می‌کند؟ ForwardDefaultSelector - یک delegate است که ASP.NET Core در هر درخواست فراخوانی می‌کند تا Scheme مناسب را - تعیین کند. با بررسی وجود Header، ما به‌صورت پویا Scheme را انتخاب می‌کنیم. -
    -
    -
    - - -
    -
    -
    ۲
    -
    - اصلاح XApiKeyAuthenticationHandler برای تولید Claims صحیح - فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs -
    -
    -
    -

    - Handler فعلی Scope ثابت "apikey" را اضافه می‌کند که با هیچ Policyای - همخوانی ندارد. باید Scopeهای واقعی از validationResult.Scopes - که در XApplicationProvider.ValidateApiKey استخراج شده‌اند، به Claims - اضافه شوند. -

    - -
    -// xIds/Providers/XApiKeyAuthenticationHandler.cs — نسخه اصلاح‌شده - -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ۱. استخراج API Key از Header - var apiKeyHeader = Options.HeaderName ?? XHeader.ApiKey.GetStringValue(); - if (!Request.Headers.ContainsKey(apiKeyHeader)) - { - return AuthenticateResult.NoResult(); - } - - var apiKey = Request.Headers[apiKeyHeader].ToString(); - if (string.IsNullOrEmpty(apiKey)) - { - return AuthenticateResult.NoResult(); - } - - // ۲. استخراج Client IP - var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - - // ۳. اعتبارسنجی API Key از طریق Provider - var validationResult = await applicationProvider.ValidateApiKey( - apiKey: apiKey, - clientIP: clientIP - ); - - if (validationResult.Errors.HasChild()) - { - var message = validationResult.Errors.ToListString('\n'); - return AuthenticateResult.Fail(message); - } - - // ═══ ۴. ساخت Claims — نکته کلیدی ═══ - var claims = new List<Claim> - { - // شناسه کاربر مالک API Key - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim(JwtClaimTypes.Subject, validationResult.OwnerId), - - // شناسه Application - new Claim("application_id", validationResult.ApplicationId.ToString()), - - // نوع احراز هویت برای تشخیص - new Claim("auth_type", "apikey"), - }; - - // ═══ ۵. اضافه کردن Scopeهای واقعی ═══ - // این Scopeها توسط XApplicationProvider از AllowedScopes استخراج شده‌اند - // و با Policyهای XAuthorizationHelper (read, write, admin, manage) همخوانی دارند - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - // ۶. ساخت Principal و Ticket - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -} -
    - -
    - ✅ نکته کلیدی: validationResult.Scopes مقادیری مانند - read، write، admin، manage دارد که - مستقیماً با Policyهای تعریف‌شده در XAuthorizationHelper مطابقت می‌کند. -
    -
    -
    - - -
    -
    -
    ۳
    -
    - اطمینان از همخوانی Policyها با Scopeهای API Key - فایل: xIdentityHelper/XAuthorizationHelper.cs -
    -
    -
    -

    - در XAuthorizationHelper، Policyهای مربوط به ApiKey تعریف شده‌اند. - این Policyها باید با مقادیر XApiKeyScope در - xIdentityModels/Constants/XApiKeyScope.cs همخوانی داشته باشند. -

    - -
    -// xIdentityModels/Constants/XApiKeyScope.cs -public enum XApiKeyScope -{ - [StringValue("read")] - Read, - - [StringValue("write")] - Write, - - [StringValue("admin")] - Admin, - - [StringValue("manage")] - Manage -} -
    - -

    - و در XAuthorizationHelper: -

    - -
    -// xIdentityHelper/XAuthorizationHelper.cs — Policyهای موجود ApiKey - -// ApiKey Access Policy — دسترسی به هر یک از Scopeها -result.Add(XPolicies.ApiKeyAccess, - new AuthorizationPolicyBuilder() - .RequireClaim( - JwtClaimTypes.Scope, - XApiKeyScope.Read.GetStringValue(), // "read" - XApiKeyScope.Write.GetStringValue(), // "write" - XApiKeyScope.Manage.GetStringValue() // "manage" - ) - .Build() -); - -// ApiKey Read Access Policy -result.Add(XPolicies.ApiKeyReadAccess, - new AuthorizationPolicyBuilder() - .RequireClaim(JwtClaimTypes.Scope, XApiKeyScope.Read.GetStringValue()) - .Build() -); -
    - -
    - 💡 نتیجه: اگر در گام ۲، Scopeهای واقعی از validationResult.Scopes - به Claims اضافه شوند، این Policyها به‌صورت خودکار با موفقیت بررسی می‌شوند و دسترسی - به Endpointهای محافظت‌شده امکان‌پذیر می‌گردد. -
    -
    -
    - - -
    -
    -
    ۴
    -
    - استفاده صحیح در Controllerها - نمونه استفاده صحیح -
    -
    -
    -

    - پس از اصلاحات بالا، برای محافظت از Endpointها با API Key، باید از Policyهای - مربوطه استفاده کنید: -

    - -
    -// نمونه Endpoint محافظت‌شده با API Key -[RequireXPowered] -[HttpPost("ApiKeys/Validate")] -[Authorize(Policy = XPolicies.ApiKeyAccess)] // ← Policy مخصوص API Key -public async Task<ActionResult<XApiKeyValidationResult>> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default -) -{ - // پیاده‌سازی -} -
    - -
    - ⚠️ توجه مهم: از آنجایی که Policyهای ApiKey بر اساس Scope - تعریف شده‌اند، نباید از Policyهای مبتنی بر Role مانند XPolicies.User - یا XPolicies.EnabledUser استفاده کنید. این Policyها انتظار Role Claim دارند - که API Key ندارد. -
    -
    -
    - - -
    -
    -
    ۵
    -
    - تست و اعتبارسنجی - Validation & Testing -
    -
    -
    -

    - پس از اعمال تغییرات، مسیر تست زیر را دنبال کنید: -

    - -

    گام ۵.۱ — ساخت یک API Key جدید

    -
    -# Request: ساخت API Key جدید برای Application -POST /Applications/{applicationId}/ApiKeys/Create -Content-Type: application/json -Authorization: Bearer {access_token} - -{ - "scopes": ["read", "write"], - "rateLimit": 60, - "expirationMinutes": 43200, - "allowedIPs": ["127.0.0.1"] -} -
    - -

    - پاسخ باید شامل شیء XApiKeyDto باشد. نکته مهم: کلید اصلی (plainKey) فقط - یک‌بار در پاسخ اولیه برگردانده می‌شود و باید آن را در جای امن ذخیره کنید. -

    - -

    گام ۵.۲ — تست Endpoint با API Key

    -
    -# Request: تست Endpoint محافظت‌شده با API Key -GET /Account/Test/HiApiKeyAccess -X-Api-Key: xapp_xxxxxxxxxxxxxxxxxxxxxxxx -X-PoweredBy: {xPoweredValue} -
    - -

    گام ۵.۳ — بررسی نتیجه

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    حالتپاسخ مورد انتظارتشخیص
    API Key معتبر + Scope کافی200 OK✓ صحیح
    API Key نامعتبر401 Unauthorized با پیام «ApiKey not found»✓ صحیح
    API Key منقضی‌شده401 با پیام «ApiKey is Expired»✓ صحیح
    Scope ناکافی403 Forbidden✓ صحیح
    IP غیرمجاز401 با پیام «Client IP not Allowed»✓ صحیح
    Rate Limit رد شده401 با پیام «ApiKey Rate Limit Reached»✓ صحیح
    -
    -
    - - -
    -
    -
    ۶
    -
    - به‌روزرسانی Endpoint «Validate API Key» - اصلاح کنترلر موجود -
    -
    -
    -

    - در ApplicationsController+Custom.cs، متد ValidateApiKey - فعلی از GetUserInfo() استفاده می‌کند که نیازمند احراز هویت با - Bearer Token است. برای پیاده‌سازی درست، باید این Endpoint - خودش با API Key احراز هویت شود (سناریوی self-validation): -

    - -
    -// xIds/Controllers/Applications/ApplicationsController+Custom.cs - -// نسخه اصلاح‌شده — با Policy API Key -[HttpPost("ApiKeys/Validate")] -[AllowAnonymous] // ← چون خودش API Key را در Body می‌فرستد -public async Task<ActionResult<XApiKeyValidationResult>> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default -) -{ - try - { - // اعتبارسنجی ورودی - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotEmpty(request.ApiKey) - .ValidateGroupAsync(); - - // استخراج ClientIP از Connection واقعی - var clientIP = HttpContext.Connection.RemoteIpAddress?.ToString(); - - // اعتبارسنجی مستقیم - var result = await provider.ValidateApiKey( - apiKey: request.ApiKey, - clientIP: clientIP, - requiredScope: request.RequiredScope, - userInfo: null, // ← userInfo دیگر نیاز نیست - cancellationToken: cancellationToken - ); - - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } -} -
    - -
    - 💡 چرا AllowAnonymous؟ چون این Endpoint خودش نقش «اعتبارسنج API Key» را - دارد و نباید قبل از رسیدن به آن، احراز هویت شود. منطق اعتبارسنجی درون خودش انجام می‌شود. -
    -
    -
    - -
    -
    - - - - -
    -
    -
    ۵
    -
    -

    خلاصه تغییرات

    -
    Summary of Changes
    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    #فایلتغییراولویت
    ۱xIds/DI/XDIHelperExtension.csافزودن ForwardDefaultSelector برای انتخاب پویا بین JwtBearer و XApiKeyحیاتی
    ۲xIds/Providers/XApiKeyAuthenticationHandler.csحذف Scope ثابت «apikey» و افزودن Scopeهای واقعی از validationResult.Scopesحیاتی
    ۳xIds/Startup.csاطمینان از ترتیب صحیح ثبت Schemeها (نیاز به تغییر مستقیم ندارد اگر از Extension استفاده شود)متوسط
    ۴xIds/Controllers/Applications/ApplicationsController+Custom.csاصلاح ValidateApiKey برای کارکرد مستقلمتوسط
    ۵xIds/Controllers/Account/AccountController+Test.csافزودن تست‌های احراز هویت با API Key (اختیاری، برای تست)توصیه‌شده
    - -
    - ✅ نتیجه نهایی: با اعمال گام‌های ۱ و ۲ (که حیاتی هستند)، مشکل احراز هویت - با XApiKey به‌طور کامل حل می‌شود. گام‌های ۳ تا ۵ برای بهبود و تکمیل توصیه می‌شوند. -
    -
    -
    - - - - -
    -
    -
    ۶
    -
    -

    بهترین شیوه‌ها و توصیه‌های تکمیلی

    -
    Best Practices & Additional Recommendations
    -
    -
    -
    - -

    ۶.۱ — مدیریت صحیح Scopeها در سطح API Key

    -

    - هنگام ساخت API Key، از مقادیر XApiKeyScope استفاده کنید: -

    - -
    -// نمونه ساخت API Key با Scopeهای صحیح -var result = await provider.CreateApiKey( - applicationId: applicationId, - scopes: new[] { "read", "write" }, // ← مطابق XApiKeyScope - allowedIPs: new[] { "192.168.1.100" }, - rateLimit: 60, - expiration: TimeSpan.FromDays(30), - userInfo: userInfo -); -
    - -

    ۶.۲ — تفکیک Policyهای مبتنی بر API Key از Policyهای مبتنی بر Role

    -

    - Policyهای موجود در XPolicies دو دسته هستند: -

    -
      -
    • Policyهای مبتنی بر Scope (مثل ApiKeyAccess, ReadAccess) — برای API Key و Bearer Token
    • -
    • Policyهای مبتنی بر Role (مثل User, Admin) — فقط برای Bearer Token
    • -
    - -
    - ⚠️ توجه: هرگز از Policyهای Role-based برای Endpointهایی که قرار است با - API Key محافظت شوند استفاده نکنید. این Policyها انتظار Claim از نوع role دارند - که API Key ندارد. -
    - -

    ۶.۳ — ذخیره امن Plain Key

    -

    - کلید اصلی (plain key) فقط در لحظه ساخت برگردانده می‌شود. باید در جای امن ذخیره شود. - در صورتی که کاربر آن را گم کند، باید کلید قبلی revoke شده و کلید جدید ساخته شود. -

    - -

    ۶.۴ — Rate Limit و Audit Log

    -

    - در XApiKeyConfiguration، ویژگی‌های زیر فعال هستند: -

    -
      -
    • DefaultRateLimit — محدودیت نرخ پیش‌فرض
    • -
    • EnableAuditLog — برای ثبت استفاده از API Keyها
    • -
    - -

    - توصیه می‌شود در ValidateApiKey پس از اعتبارسنجی موفق، یک رکورد - XApiKeyUsage ثبت کنید تا تاریخچه استفاده قابل ردیابی باشد. -

    - -

    ۶.۵ — Endpointهای توصیه‌شده برای تست

    -

    - برای اطمینان از کارکرد صحیح، این Endpointها را در AccountController+Test.cs - اضافه کنید: -

    - -
    -[RequireXPowered] -[HttpGet("Test/HiApiKeyReadAccess")] -[Authorize(Policy = XPolicies.ApiKeyReadAccess)] -public ActionResult<string> HiApiKeyReadAccess() -{ - return Ok("API Key Read Access Passed ..."); -} - -[RequireXPowered] -[HttpPost("Test/HiApiKeyWriteAccess")] -[Authorize(Policy = XPolicies.ApiKeyWriteAccess)] -public ActionResult<string> HiApiKeyWriteAccess() -{ - return Ok("API Key Write Access Passed ..."); -} -
    -
    -
    - - - - -
    -
    -
    ۷
    -
    -

    جمع‌بندی

    -
    Conclusion
    -
    -
    -
    -

    - مشکل عدم احراز هویت با XApiKey در xIds ریشه در دو نقطه کد کلیدی - دارد که هر دو در این سند شناسایی و راه‌حل آن‌ها ارائه شد: -

    - -
      -
    1. - عدم انتخاب صحیح Scheme در Startup — که با افزودن - ForwardDefaultSelector در AddJwtBearer حل می‌شود. -
    2. -
    3. - عدم تطابق Claims تولیدشده با Policyها — که با افزودن Scopeهای - واقعی از validationResult.Scopes در XApiKeyAuthenticationHandler - حل می‌شود. -
    4. -
    - -

    - با اعمال این دو تغییر ساده اما حیاتی، سیستم احراز هویت مبتنی بر API Key به‌طور کامل فعال - می‌شود و Endpointهای محافظت‌شده با Policyهای ApiKeyAccess، - ApiKeyReadAccess، ApiKeyWriteAccess و - ApiKeyAdminAccess به درستی کار می‌کنند. -

    - -
    - ✅ کلید موفقیت: زیرساخت موجود در xIds برای مدیریت API Key بسیار - کامل و حرفه‌ای است. تنها دو نقطه اتصال کوچک در لایه احراز هویت نیاز به اصلاح داشتند - که در این سند به‌طور کامل تشریح شدند. -
    -
    -
    - -
    - این مستند فنی محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. -
    - -
    - - -
    - - -
    - تحلیل و مستندسازی: تیم فنی xSaherelmWorkspace  |  نسخه: ۱.۰  |  - مهر ۱۴۰۵ -
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_91592543-a30d-4cd3-8f73-4660ff1c06d1.html - - - - - - -تحلیل نیازمندی‌ها | درخواست شرکت پارسا پلیمر شریف - - - - -
    - -
    -
    -
    - -
    -
    -
    شماره مستند: REQ-1405-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: مهر ۱۴۰۵
    -
    طبقه‌بندی: محرمانه
    -
    -
    - -
    - REQUIREMENTS ANALYSIS -

    تحلیل نیازمندی‌ها

    -

    درخواست شرکت پارسا پلیمر شریف برای راهکار هوش مصنوعی سازمانی

    -
    -
    - -
    - -
    - خلاصه مدیریتی،
    - این مستند به تحلیل دقیق و شفاف درخواست رسمی شرکت پارسا پلیمر شریف (نخستین شرکت دانش‌بنیان ایران، فعال در صنعت تولید کامپاندهای پلیمری) می‌پردازد. هدف درخواست‌کننده، بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف سازمان و ارزیابی محصولات و خدمات ارائه‌دهندگان این حوزه است. در این مستند، هفت محور اصلی درخواست، الزامات آزمون عملی، و انتظارات کلیدی کارفرما به‌صورت دسته‌بندی‌شده تشریح می‌شود تا مبنای تهیه پیشنهاد فنی و تجاری قرار گیرد. -
    - -
    -
    -
    ۱
    -
    -

    شناخت کلی درخواست

    -
    Context & Overview
    -
    -
    -
    -

    شرکت پارسا پلیمر شریف با هدف بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف، از ارائه‌دهندگان راهکارهای هوش مصنوعی درخواست کرده است تا اطلاعات محصولات و خدمات خود را به‌صورت مکتوب ارائه دهند. این درخواست در قالب یک RFP (درخواست پیشنهاد) با رویکردی فنی، دقیق و آزمون‌محور تنظیم شده است.

    - -
    -
    -
    ۷
    -
    محور اصلی درخواست
    -
    -
    -
    آزمون
    عملی
    -
    الزام جلسه دمو
    -
    -
    -
    شفافیت
    کامل
    -
    در قیمت و قابلیت‌ها
    -
    -
    - -
    - نکته کلیدی: لحن و ساختار درخواست نشان می‌دهد تیم فنی/فناوری اطلاعات کارفرما با مفاهیم روز هوش مصنوعی (Agent، Assistant، RAG، مدیریت دسترسی، حاکمیت داده) کاملاً آشناست و به دنبال پاسخ‌های سطحی یا بازاریابی نیست. بنابراین، پیشنهاد ارائه‌شده باید مستند، قابل‌آزمون و شفاف باشد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    محور ۱: ماهیت راهکار، مدل‌ها و قابلیت‌های ایجنت

    -
    Solution Nature, Models & Agent Capabilities
    -
    -
    -
    -

    کارفرما خواستار شفاف‌سازی دقیق ماهیت راهکار و تمایز آن از گردش‌کارهای از پیش تعریف‌شده است. نیازمندی‌های صریح این محور به شرح زیر است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام آزمون/اثبات
    ۱-۱مشخص کردن قالب راهکار: چت‌بات، دستیار هوشمند (Assistant)، ایجنت (Agent) یا ترکیبی از آن‌ها و قابلیت‌های هر بخشتوضیح مکتوب + نمایش عملی
    ۱-۲ارائه تعریف دقیق و قابل‌آزمون از Agent و تمایز آن با Assistant یا گردش‌کار از پیش تعریف‌شدهسناریوی چندمرحله‌ای در محیط آزمایشی
    ۱-۳توانایی تبدیل هدف به مراحل اجرایی، انتخاب ابزار مناسب، انجام عملیات و اصلاح مراحل بعدی بر اساس نتیجهاجرای عملی در جلسه دمو
    ۱-۴مشخص کردن نقاط نیازمند دستور یا تأیید انسان (Human-in-the-loop)مستندسازی + نمایش در سناریو
    ۱-۵اعلام مدل‌های قابل استفاده در هر پلن و امکان طراحی دستیار/ایجنت اختصاصی متناسب با فرایندهای سازمانجدول مدل‌ها به تفکیک پلن
    ۱-۶پشتیبانی از به‌روزترین مدل‌های منتشرشده و اعلام بازه زمانی دسترسی سازمانی پس از عرضه مدل/نسخه جدیدتعهد زمان‌بندی مشخص
    - -
    - ⚠️ نکته حساس: کارفرما در جلسه دمو خواستار ارائه یک سناریوی چندمرحله‌ای در محیط آزمایشی است تا نحوه برنامه‌ریزی مراحل، انتخاب و استفاده از ابزارها، اجرای عملیات، واکنش به خطا یا تغییر شرایط، و موارد نیازمند مداخله انسانی به‌صورت قابل مشاهده ارزیابی شود. ادعاهای مکتوب بدون قابلیت نمایش عملی، پذیرفته نخواهد شد. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    محور ۲: مدیریت کاربران و سطوح دسترسی

    -
    User Management & Access Control
    -
    -
    -
    -

    این محور از حساس‌ترین بخش‌های درخواست است، زیرا کارفرما قصد دارد آزمون نفوذ عملی برای سطوح دسترسی انجام دهد. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام آزمون/اثبات
    ۲-۱سازوکار ایجاد کاربران، تعریف نقش‌ها و مدیریت کاربران واحدهای مختلف سازماننمایش عملی + مستندات
    ۲-۲امکان تعیین فهرست مجاز مدل‌ها، منابع و ابزارها و محدودسازی دسترسی تا سطح سند یا رکوردآزمون با حساب‌های متفاوت
    ۲-۳نحوه اعمال مجوزها در بازیابی اطلاعات، پاسخ‌گویی مدل و اجرای عملیات ایجنتآزمون پرسش یکسان با مجوزهای متفاوت
    ۲-۴سازوکار جلوگیری از افشای اطلاعات خارج از سطح دسترسیآزمون نفوذ (پرسش مستقیم/غیرمستقیم، خلاصه‌سازی، ایجنت)
    - -
    - ⚠️ آزمون نفوذ دسترسی: کارفرما صراحتاً اعلام کرده است که در ارزیابی، پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت مطرح خواهد شد تا اطمینان حاصل شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین بررسی خواهد شد که کاربران فاقد مجوز نتوانند از طریق پرسش مستقیم یا غیرمستقیم، درخواست خلاصه‌سازی یا استفاده از ایجنت، به اطلاعات خارج از سطح دسترسی خود دست یابند. این یعنی راهکار باید در برابر حملات مبتنی بر مهندسی اجتماعی و دور زدن مجوزها مقاوم باشد. -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    محور ۳: پلن‌ها، مصرف، تعرفه‌ها و API

    -
    Plans, Usage, Pricing & API
    -
    -
    -
    -

    کارفرما روی شفافیت کامل قیمت‌گذاری و مبنای محاسبه تأکید ویژه دارد. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۳-۱تفاوت پلن‌های سازمانی و شخصی و مبنای محاسبه هزینه (اشتراک هر کاربر یا اعتبار مصرفی)جدول مقایسه‌ای شفاف
    ۳-۲نحوه تعیین سهمیه درخواست‌ها، سقف مصرف و مدیریت اتمام سهمیهمستندات + مثال عددی
    ۳-۳هزینه یک درخواست معمول با مدل GPT5.6 Sol و مبنای محاسبه آنعدد دقیق + فرمول محاسبه
    ۳-۴گزارش مصرف و هزینه به تفکیک کاربر، مدل و ایجنت و قابلیت‌های بهینه‌سازی مصرفنمایش نمونه گزارش
    ۳-۵با فرض استفاده انحصاری از GPT5.6 Sol، تعداد توکن ماهانه تخصیصی به کل شرکت در هر پلنعدد دقیق به تفکیک پلن
    ۳-۶در صورت اعتباری‌بودن پلن، ظرفیت معادل مصرف ماهانه با این مدل همراه با فرض و مبنای محاسبهسناریوی محاسبه شفاف
    ۳-۷امکان تهیه API و استفاده از حساب/اعتبار اختصاصی سازمان و اینکه تعرفه آن با اشتراک کاربران مشترک است یا مستقلتوضیح مکتوب + شرایط
    - -
    - 💡 نکته کلیدی: اشاره صریح کارفرما به مدل «GPT5.6 Sol» نشان می‌دهد که انتظار دارند ارائه‌دهنده از جدیدترین مدل‌ها پشتیبانی کند و پاسخ دقیق و عددی (نه کلی) بدهد. پاسخ‌های مبهم یا بدون مبنای محاسبه، در ارزیابی رد خواهند شد. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    محور ۴: رابط کاربری، فایل‌ها و گزارش‌ها

    -
    UI, Files & Reports
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۴-۱ارائه رابط کاربری اختصاصی سازمان و نسخه دسکتاپ و امکانات هرکدامنمایش عملی + مستندات
    ۴-۲دسترسی مستقیم و کنترل‌شده به فایل‌ها و پوشه‌های محلی یا شبکه سازمانآزمون عملی دسترسی
    ۴-۳تحلیل ارتباط میان چند فایلسناریوی عملی
    ۴-۴خروجی‌های متنی، جدولی و نمودارینمونه خروجی
    ۴-۵قابلیت ویرایش گزارش‌ها، ارجاع به منابع و دریافت در قالب‌های Word و Excelنمایش عملی + فایل نمونه
    -
    -
    - -
    -
    -
    ۶
    -
    -

    محور ۵: حاکمیت داده، محرمانگی و معماری استقرار

    -
    Data Governance, Confidentiality & Deployment Architecture
    -
    -
    -
    -

    این محور برای یک شرکت دانش‌بنیان تولیدی (با اطلاعات حساس فرمولاسیون، مشتریان و فرایندها) بسیار حیاتی است. نیازمندی‌های صریح:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۵-۱محل ذخیره و پردازش اطلاعات سازمان و اینکه چه محتوایی به سرویس‌های ثالث منتقل می‌شودمستندات معماری + دیاگرام
    ۵-۲سیاست استفاده از داده‌ها و مکالمات برای آموزش یا بهبود مدل‌هاسیاست مکتوب و شفاف
    ۵-۳امکان نگهداری داده‌ها و رابط کاربری در زیرساخت شرکت (On-Premise) و استفاده از مدل‌ها/ایجنت‌های خارجی از طریق APIتوضیح معماری + شرایط
    ۵-۴در این ساختار، مالکیت، مجوزهای دسترسی و مسئولیت هر بخش چگونه تعیین می‌شودمستند حقوقی/فنی
    - -
    - ⚠️ حساسیت بالا: انتظار استقرار درون‌سازمانی (On-Premise) و کنترل کامل داده وجود دارد. ارائه‌دهندگانی که فقط راهکار ابری ارائه می‌دهند، باید بتوانند سیاست‌های حاکمیت داده و عدم استفاده از داده برای آموزش مدل را به‌صورت مکتوب و قابل استناد تضمین کنند. -
    -
    -
    - -
    -
    -
    ۷
    -
    -

    محور ۶: پیاده‌سازی، اختصاصی‌سازی، آموزش و پشتیبانی

    -
    Implementation, Customization, Training & Support
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۶-۱حدود سفارشی‌سازی و امکان توسعه توسط تیم داخلی سازمانمستندات + مثال
    ۶-۲هزینه و زمان تهیه سامانه، استقرار و توسعه اختصاصی و نحوه محاسبه آنجدول زمان‌بندی و هزینه
    ۶-۳برنامه آموزش کاربران و مدیران، مستندات تحویلی و شرایط و هزینه پشتیبانیبرنامه مدون
    ۶-۴اینکه تیم سازمان پس از آموزش چه فعالیت‌هایی را می‌تواند مستقل انجام دهدفهرست شفاف
    -
    -
    - -
    -
    -
    ۸
    -
    -

    محور ۷: عملکرد، پایداری و ارزیابی عملی

    -
    Performance, Reliability & Practical Evaluation
    -
    -
    -
    -

    نیازمندی‌های صریح این محور:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفنیازمندیالزام ارائه
    ۷-۱زمان پاسخ‌گویی برای درخواست معمول، تحلیل فایل و اجرای ایجنتاعداد دقیق + شرایط اندازه‌گیری
    ۷-۲تعهد سطح خدمت (SLA)سند SLA
    ۷-۳وضعیت قابلیت‌های سامانه هنگام قطع اینترنت بین‌المللسناریوی تاب‌آوری
    ۷-۴شرایط ارائه دمو و اجرای پایلوت محدود (زمان، هزینه، پیش‌نیازها)پیشنهاد مدون پایلوت
    - -
    - 💡 نکته کلیدی: پرسش صریح درباره عملکرد هنگام قطع اینترنت بین‌الملل نشان‌دهنده نیاز به راهکار پایدار داخلی است. ارائه‌دهندگانی که راهکارشان کاملاً وابسته به سرویس‌های ابری خارجی است، باید محدودیت‌ها را شفاف اعلام کنند. -
    -
    -
    - -
    -
    -
    ۹
    -
    -

    الزامات فرایندی و قالب ارائه

    -
    Process Requirements & Submission Format
    -
    -
    -
    -

    علاوه بر محتوای فنی، کارفرما الزامات فرایندی زیر را نیز مشخص کرده است:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    الزامتوضیح
    قالب ارائهتوضیحات مکتوب، پیشنهاد فنی و تجاری، کاتالوگ یا مستندات موجود
    تفکیک قابلیت‌هاقابلیت‌های موجود / نیازمند سفارشی‌سازی / در برنامه توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها
    جلسه دموبررسی موردبه‌مورد تمام محورها همراه با توضیحات و مستندات
    آزمون عملیامکان اجرای آزمون‌های عملی برای قابلیت‌های اجرایی
    سناریوی Agentارائه یک سناریوی چندمرحله‌ای در محیط آزمایشی
    آزمون دسترسیپرسش‌های یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها
    زمان‌بندیاعلام زمان پیشنهادی برای جلسه معرفی و دمو
    -
    -
    - -
    -
    -
    ۱۰
    -
    -

    جمع‌بندی و ویژگی‌های متمایز درخواست

    -
    Summary & Distinctive Characteristics
    -
    -
    -
    -

    این درخواست یک RFP بالغ، فنی و آزمون‌محور است که چند ویژگی متمایز دارد:

    - -
    -
    -

    ویژگی ۱: اثبات عملی، نه ادعا

    -
      -
    • رویکرد سناریوی قابل‌آزمون
    • -
    • دمو عملی و تعاملی
    • -
    • دسترسی آزمون نفوذ
    • -
    -
    -
    -

    ویژگی ۲: حساسیت به حاکمیت داده

    -
      -
    • استقرار درون‌سازمانی
    • -
    • داده کنترل کامل
    • -
    • آموزش مدل شفافیت سیاست
    • -
    -
    -
    - -
    -
    -

    ویژگی ۳: شفافیت مالی

    -
      -
    • قیمت اعداد دقیق
    • -
    • مبنا فرمول محاسبه
    • -
    • گزارش تفکیک مصرف
    • -
    -
    - -
    - -
    - نتیجه کلیدی: تیم ارزیابی کارفرما از اصطلاحات دقیق (Agent در برابر Assistant، Human-in-the-loop، سطح دسترسی تا رکورد، فهرست مجاز مدل‌ها) استفاده می‌کند که نشان‌دهنده وجود تیم فنی قوی و آگاه در سمت کارفرماست. بنابراین، پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد. -
    -
    -
    - -
    -
    -
    ۱۱
    -
    -

    گام‌های بعدی پیشنهادی

    -
    Recommended Next Steps
    -
    -
    -
    -

    با توجه به تحلیل فوق، تهیه پیشنهاد فنی و تجاری نیازمند موارد زیر است:

    - -
      -
    • - پاسخ موردبه‌مورد، مستند و قابل‌آزمون به هر ۷ محور - همراه با شواهد و مستندات پشتیبان -
    • -
    • - جدول تفکیک قابلیت‌ها - موجود / سفارشی‌سازی / در توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها -
    • -
    • - سناریوی نمونه Agent - برای ارائه و اجرا در جلسه دمو (چندمرحله‌ای، با ابزارها، خطا و مداخله انسانی) -
    • -
    • - شفافیت کامل قیمت‌گذاری - با مبنای محاسبه، اعداد دقیق توکن و هزینه هر درخواست -
    • -
    • - برنامه پایلوت محدود - شامل زمان، هزینه، پیش‌نیازها و معیارهای ارزیابی موفقیت -
    • -
    • - زمان‌بندی جلسه معرفی و دمو - همراه با آمادگی برای آزمون‌های عملی -
    • -
    - -
    - 📞 گام بعدی: پس از تأیید این تحلیل نیازمندی‌ها، مستند پیشنهاد فنی و تجاری (شامل پاسخ به هر ۷ محور، جدول قابلیت‌ها، سناریوی Agent، قیمت‌گذاری شفاف و برنامه پایلوت) تهیه و ارائه خواهد شد. -
    -
    -
    - -
    -

    🎯 جمع‌بندی نهایی

    -

    درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است که بر شفافیت، اثبات عملی و حاکمیت داده تأکید دارد.

    -

    پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد و بتواند در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) پاسخگو باشد.

    -
    - 💎 ارزش پیشنهادی مورد انتظار:
    - شفافیت کامل + قابلیت اثبات عملی + حاکمیت داده + قیمت‌گذاری دقیق + آمادگی پایلوت -
    -
    - -
    - این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    - -
    - -
    - - -
    تاریخ تهیه: مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: محرمانه
    -
    - -
    - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_9e6b15de-b071-4dfe-bbc6-7ecb47d1dc50.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
    -
    -
    -
    - -
    -
    -
    شماره مستند: TECH-1405-002
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۸ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی / فنی
    -
    -
    -
    -TECHNICAL REVIEW & GUIDE -

    بررسی فنی و راهنمای جامع ابزار AirLLM

    -

    تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

    -
    -
    - -
    -
    -همکاران و ذینفعان محترم،
    -این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

    -
    -نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری و مکانیزم عملکرد

    -
    Architecture & Mechanism
    -
    -
    -
    -

    مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

    -
    -گام ۱: تجزیه و ذخیره‌سازی اولیه
    -در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

    -گام ۲: بارگذاری پویا در GPU
    -در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

    -گام ۳: محاسبه و انتقال حالت (State)
    -پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
    -
    -💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    مدل‌های پشتیبانی‌شده و مصرف حافظه

    -
    Supported Models & VRAM Consumption
    -
    -
    -
    -

    این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
    Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
    Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
    Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
    Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
    Llama 3.x 70B (full precision)70B~۴ گیگابایت
    DeepSeek-V3671B~۱۲ گیگابایت
    -
    -
    - -
    -
    -
    ۴
    -
    -

    راهنمای گام‌به‌گام پیاده‌سازی

    -
    Step-by-Step Implementation Guide
    -
    -
    -
    -

    برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

    -
    -پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
    -

    گام ۱: نصب کتابخانه

    -
    pip install airllm
    - -

    گام ۲: مقداردهی اولیه مدل

    -
    from airllm import AutoModel
    -
    -# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
    -model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
    -
    -# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
    -# model = AutoModel.from_pretrained("model-name", compression='4bit')
    -
    - -

    گام ۳: آماده‌سازی ورودی و اجرای استنتاج

    -
    MAX_LENGTH = 128
    -input_text = ['What is the capital of United States?']
    -
    -input_tokens = model.tokenizer(
    -    input_text,
    -    return_tensors="pt",
    -    return_attention_mask=False,
    -    truncation=True,
    -    max_length=MAX_LENGTH,
    -    padding=False
    -)
    -
    -generation_output = model.generate(
    -    input_tokens['input_ids'].cuda(),
    -    max_new_tokens=20,
    -    use_cache=True,
    -    return_dict_in_generate=True
    -)
    -
    -output = model.tokenizer.decode(generation_output.sequences[0])
    -print(output)
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جمع‌بندی و توصیه‌های فنی

    -
    Conclusion & Technical Recommendations
    -
    -
    -
    -

    با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
    مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
    نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
    سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
    ارزش خالص فنی—بسیار بالاتر
    - -
    -

    🎯 توصیه نهایی معماری

    -

    با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

    -

    این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

    -
    -💎 ارزش پیشنهادی:
    -حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
    -
    -
    -
    - -
    -این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    -
    - -
    - - -
    شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_b85c4c9b-e4d4-48df-97ff-eb50ee55f39b.html - - - - - - - مستندات فنی پیاده‌سازی احراز هویت XApiKey در xIds - - - -
    -
    -
    -
    -
    شماره مستند: TECH-XIDS-APIKEY-001
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۰ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی - فنی
    -
    -
    -
    -

    راهنمای جامع پیاده‌سازی و عیب‌یابی احراز هویت XApiKey

    -

    پروژه xIds (Identity Server) | ماژول مدیریت Application و API Key

    -
    -
    - -
    - -
    -
    -
    ۱
    -
    -

    مقدمه و بررسی وضعیت فعلی

    -
    -
    -
    -

    - در پروژه xIds، زیرساخت کاملی برای مدیریت XApplication و XApiKey پیاده‌سازی شده است. - کلاس‌های XApplicationProvider و XApiKeyHelper وظیفه تولید، هش کردن و اعتبارسنجی کلیدها را بر عهده دارند. - با این حال، چالش اصلی در لایه Authentication Middleware و نحوه اتصال آن به Policyهای موجود بود. -

    -
    - مشکل شناسایی شده: درخواست‌های ارسالی با هدر X-Api-Key توسط ASP.NET Core نادیده گرفته می‌شدند، زیرا Scheme پیش‌فرض روی JWT Bearer تنظیم شده بود و Handler مخصوص ApiKey فراخوانی نمی‌شد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    راه‌حل فنی: اصلاح زنجیره احراز هویت

    -
    -
    -
    -

    برای رفع مشکل، دو تغییر اساسی در فایل xIds/DI/XDIHelperExtension.cs اعمال شد:

    - -

    الف) ثبت Scheme اختصاصی برای XApiKey

    -

    قبل از ثبت JwtBearer، Scheme مربوط به ApiKey ثبت می‌شود تا در لیست Authentication Schemes وجود داشته باشد.

    - -

    ب) استفاده از ForwardDefaultSelector هوشمند

    -

    به جای استفاده ثابت از ForwardDefault، از یک Delegate استفاده می‌کنیم که Header درخواست را بررسی می‌کند.

    - -
    -// xIds/DI/XDIHelperExtension.cs - -public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration, - bool addApiKeyAuthentication = false) -{ - services.AddXIdentityResourceConfiguration(configuration); - var authBuilder = services.AddAuthentication(); - - // 1. ثبت Scheme برای XApiKey (اولویت اول) - if (addApiKeyAuthentication) - { - authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>( - XAuthenticationScheme.XApiKey.GetStringValue(), // "XApiKey" - options => { }); - } - - // 2. ثبت JwtBearer با Selector هوشمند - authBuilder.AddJwtBearer(options => - { - options.SaveToken = true; - options.RequireHttpsMetadata = false; - - // انتخاب دینامیک Scheme بر اساس هدر درخواست - options.ForwardDefaultSelector = context => - { - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); // "X-Api-Key" - if (context.Request.Headers.ContainsKey(apiKeyHeader)) - { - return XAuthenticationScheme.XApiKey.GetStringValue(); - } - // در غیر این صورت، از احراز هویت استاندارد IdentityServer استفاده کن - return XAuthentication.IDENTITY_SERVER_LOCAL_API; - }; - }) - .AddLocalApi(); -} -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    اصلاح Claims تولید شده در Handler

    -
    -
    -
    -

    - در فایل xIds/Providers/XApiKeyAuthenticationHandler.cs، متد HandleAuthenticateAsync باید Claimهای صحیح را تولید کند تا با Policyهای تعریف شده در XAuthorizationHelper همخوانی داشته باشد. -

    -
    - نکته مهم: Policyهای ApiKey بر اساس Scope (مانند read, write, admin) کار می‌کنند، نه Role. بنابراین Claim از نوع JwtClaimTypes.Scope ضروری است. -
    -
    -protected override async Task<AuthenticateResult> HandleAuthenticateAsync() -{ - // ... استخراج و اعتبارسنجی ApiKey ... - - var validationResult = await applicationProvider.ValidateApiKey(apiKey, clientIP); - - if (validationResult.Errors.HasChild()) - return AuthenticateResult.Fail(string.Join(", ", validationResult.Errors)); - - var claims = new List<Claim> - { - new Claim(ClaimTypes.Name, validationResult.OwnerId), - new Claim(JwtClaimTypes.Subject, validationResult.OwnerId), - new Claim("application_id", validationResult.ApplicationId.ToString()), - new Claim("auth_type", "apikey"), - }; - - // افزودن Scopeهای مجاز به Claims - if (validationResult.Scopes != null) - { - foreach (var scope in validationResult.Scopes) - { - claims.Add(new Claim(JwtClaimTypes.Scope, scope)); - } - } - - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return AuthenticateResult.Success(ticket); -} -
    -
    -
    - -
    -
    -
    ۴
    -
    -

    نحوه استفاده در Controllerها

    -
    -
    -
    -

    برای محافظت از Endpointها با ApiKey، از Attributeهای زیر استفاده کنید:

    -
    -[RequireXPowered] -[Authorize(Policy = XPolicies.ApiKeyAccess)] // دسترسی کلی -public async Task<ActionResult> MySecureAction() { ... } - -[Authorize(Policy = XPolicies.ApiKeyReadAccess)] // فقط خواندن -public async Task<ActionResult> GetItems() { ... } -
    -
    - تست موفقیت‌آمیز: اکنون با ارسال هدر X-Api-Key: xapp_... به Endpointهای فوق، احراز هویت انجام شده و دسترسی اعطا می‌شود. -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    چک‌لیست نهایی استقرار

    -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ردیفاقداموضعیت
    ۱بررسی ثبت AddXIdentityServerAuthentication در Startup با پارامتر true✅ انجام شد
    ۲اطمینان از وجود Policyهای ApiKeyAccess در XAuthorizationHelper✅ موجود است
    ۳تست ایجاد ApiKey جدید از طریق /Applications/{id}/ApiKeys/Create✅ تست شد
    ۴تست دسترسی به /Account/Test/HiApiKeyAccess با کلید معتبر✅ پاس شد
    -
    -
    - -
    - -
    - -
    تاریخ انتشار: ۲۰ مهر ۱۴۰۵
    -
    -
    - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_de98d2ce-3d9d-4990-a129-ea2bdd3b5216.html - - - - - - -بررسی فنی و راهنمای جامع ابزار AirLLM - - - -
    -
    -
    -
    - -
    -
    -
    شماره مستند: TECH-1405-002
    -
    نسخه: ۱.۰
    -
    تاریخ تهیه: ۲۸ مهر ۱۴۰۵
    -
    طبقه‌بندی: داخلی / فنی
    -
    -
    -
    -TECHNICAL REVIEW & GUIDE -

    بررسی فنی و راهنمای جامع ابزار AirLLM

    -

    تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود

    -
    -
    - -
    -
    -همکاران و ذینفعان محترم،
    -این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار AirLLM را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است. -
    - -
    -
    -
    ۱
    -
    -

    خلاصه اجرایی

    -
    Executive Summary
    -
    -
    -
    -

    ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.

    -
    -نتیجه کلیدی: با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد. -
    -
    -
    - -
    -
    -
    ۲
    -
    -

    معماری و مکانیزم عملکرد

    -
    Architecture & Mechanism
    -
    -
    -
    -

    مکانیزم اصلی AirLLM بر پایه تکنیک «بارگذاری لایه‌ای» (Layer-wise Loading) استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:

    -
    -گام ۱: تجزیه و ذخیره‌سازی اولیه
    -در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود. -

    -گام ۲: بارگذاری پویا در GPU
    -در حین فرآیند استنتاج، تنها یک لایه از مدل در هر لحظه روی GPU بارگذاری می‌شود. -

    -گام ۳: محاسبه و انتقال حالت (State)
    -پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود. -
    -
    -💡 نتیجه معماری: این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود. -
    -
    -
    - -
    -
    -
    ۳
    -
    -

    مدل‌های پشتیبانی‌شده و مصرف حافظه

    -
    Supported Models & VRAM Consumption
    -
    -
    -
    -

    این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    نام مدلاندازه تقریبیحداقل VRAM مورد نیاز
    Qwen3 / Mistral / Phi≈8B~۱ تا ۲ گیگابایت
    Qwen3-30B / Mixtral (MoE)30–47B~۱ تا ۳ گیگابایت
    Qwen3.8-27B (dense VL)27B~۳.۳۳ گیگابایت
    Qwen3.8-Flash-Next (MoE + PLE)~180B~۵.۹۵ گیگابایت
    Llama 3.x 70B (full precision)70B~۴ گیگابایت
    DeepSeek-V3671B~۱۲ گیگابایت
    -
    -
    - -
    -
    -
    ۴
    -
    -

    راهنمای گام‌به‌گام پیاده‌سازی

    -
    Step-by-Step Implementation Guide
    -
    -
    -
    -

    برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:

    -
    -پیش‌نیاز حیاتی: اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا. -
    -

    گام ۱: نصب کتابخانه

    -
    pip install airllm
    - -

    گام ۲: مقداردهی اولیه مدل

    -
    from airllm import AutoModel
    -
    -# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
    -model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
    -
    -# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
    -# model = AutoModel.from_pretrained("model-name", compression='4bit')
    -
    - -

    گام ۳: آماده‌سازی ورودی و اجرای استنتاج

    -
    MAX_LENGTH = 128
    -input_text = ['What is the capital of United States?']
    -
    -input_tokens = model.tokenizer(
    -    input_text,
    -    return_tensors="pt",
    -    return_attention_mask=False,
    -    truncation=True,
    -    max_length=MAX_LENGTH,
    -    padding=False
    -)
    -
    -generation_output = model.generate(
    -    input_tokens['input_ids'].cuda(),
    -    max_new_tokens=20,
    -    use_cache=True,
    -    return_dict_in_generate=True
    -)
    -
    -output = model.tokenizer.decode(generation_output.sequences[0])
    -print(output)
    -
    -
    -
    - -
    -
    -
    ۵
    -
    -

    جمع‌بندی و توصیه‌های فنی

    -
    Conclusion & Technical Recommendations
    -
    -
    -
    -

    با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    مزیتروش سنتی (بارگذاری کامل)روش AirLLM (لایه‌ای)
    مصرف VRAMبسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)بهینه و متناسب با اندازه لایه
    نیاز به کوانتیزاسیونالزامی برای کاهش مصرفغیرالزامی (حفظ دقت کامل)
    سرعت استنتاج (با فشرده‌سازی)پایهتا ۳ برابر سریع‌تر (با 4bit/8bit)
    ارزش خالص فنی—بسیار بالاتر
    - -
    -

    🎯 توصیه نهایی معماری

    -

    با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.

    -

    این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.

    -
    -💎 ارزش پیشنهادی:
    -حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face -
    -
    -
    -
    - -
    -این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. -
    -
    - -
    - - -
    شرکت: فن آوران ساحر علم  |  تاریخ تهیه: ۲۸ مهر ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: داخلی / فنی
    -
    -
    - - diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261109_152619.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261109_152619.txt deleted file mode 100644 index d10f261..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261109_152619.txt +++ /dev/null @@ -1,12301 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs - -using System; - -namespace xAiModels.Attributes -{ - /// - /// Decorate and Describe Specified MCP Tool to LLM ... - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] - public class XAiMcpToolAttribute : Attribute - { - /// - /// Tools Unique Name (Default: Method Name) ... - /// - /// - public string Name { get; } - - /// - /// Tools Description for LLM ... - /// - /// - public string Description { get; set; } - - /// - /// Specify it's Required to Authenticated or not ... - /// - /// - public bool RequiresAuthentication { get; set; } = false; - - /// - /// Authorization and Policiy ... - /// - /// - public string RequiredPolicy { get; set; } = string.Empty; - - public XAiMcpToolAttribute(string name = null) - { - Name = name; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolParamAttribute.cs - -using System; - -namespace xAiModels.Attributes -{ - /// - /// Describe Specific Tools Parameter Metadata ... - /// - [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] - public sealed class XAiMcpToolParamAttribute : Attribute - { - /// - /// Parameter Name in JSON (Default Parameter Name) ... - /// - /// - public string Name { get; } - - /// - /// Describe Parameter to LLM ... - /// - /// - public string Description { get; set; } - - /// - /// Specified this Parameter is Required or not (Default is true) ... - /// - /// - public bool Required { get; set; } = true; - - public XAiMcpToolParamAttribute(string name = null) - { - Name = name; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Attributes\XAiMcpToolTypeAttribute.cs - -using System; - -namespace xAiModels.Attributes -{ - /// - /// Decorate Tools Classes ... - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] - public class XAiMcpToolTypeAttribute : Attribute { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\XAiModelMappersProfile.cs - -using AutoMapper; -using xAiModels.Models.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Configurations -{ - public class XAiModelMappersProfile : Profile - { - public XAiModelMappersProfile() - { - // - // XAiMessage ... - CreateMap(); - - // - // XAiVector ... - CreateMap() - .ForMember(x => x.Embedding, opt => opt.Ignore()) - .ForMember(x => x.Metadata, opt => opt.Ignore()); - CreateMap() - .ForMember(x => x.Embedding, opt => opt.Ignore()) - .ForMember(x => x.Metadata, opt => opt.Ignore()); - - // - // XAiProject ... - CreateMap(); - - // - CreateMap(); - CreateMap(); - - // - // XAiConversation ... - CreateMap(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiConversationEntityConfiguration.cs - -using System; -using xAiModels.Constants; -using xDataService.Providers; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xAiModels.Configurations.Entities -{ - public class XAiConversationEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XAiModelsConstants.XAiConversationTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMcpServerEntityConfiguration .cs - -using System; -using xAiModels.Constants; -using xDataService.Providers; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xAiModels.Configurations.Entities -{ - public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XAiModelsConstants.XAiMcpServerTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMessageEntityConfiguration.cs - -using System; -using xAiModels.Constants; -using xDataService.Providers; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xAiModels.Configurations.Entities -{ - public class XAiMessageEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XAiModelsConstants.XAiMessageTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiProjectEntityConfiguration.cs - -using System; -using xAiModels.Constants; -using xDataService.Providers; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xAiModels.Configurations.Entities -{ - public class XAiProjectEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XAiModelsConstants.XAiProjectTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiVectorEntityConfiguration.cs - -using System; -using xAiModels.Constants; -using xDataService.Providers; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xAiModels.Configurations.Entities -{ - public class XAiVectorEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - // - builder.ToTable(XAiModelsConstants.XAiVectorTable); - - // - builder.Property(x => x.Type).HasMaxLength(100); - - // - // Indexes for Prefix Scoped Search and Type Filtering ... - builder.HasIndex(x => x.Identifier); - builder.HasIndex(x => x.Type); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\ConfigurationNodeNames.cs - -namespace xAiModels.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_API_NODE = "AiApiConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiChatRole.cs - -using xExceptions.Attributes; - -namespace xAiModels.Constants -{ - public struct XAiChatRoles - { - public const string None = "none"; - public const string User = "user"; - public const string Tool = "tool"; - public const string System = "system"; - public const string Assistant = "assistant"; - } - - public enum XAiChatRole - { - [StringValue(XAiChatRoles.None)] - None, - [StringValue(XAiChatRoles.User)] - User, - [StringValue(XAiChatRoles.Tool)] - Tool, - [StringValue(XAiChatRoles.System)] - System, - [StringValue(XAiChatRoles.Assistant)] - Assistant, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiDataProviderConstants.cs - -using xExceptions.Attributes; - -namespace xAiModels.Constants -{ - public struct XAiDataProviderConstants - { - public const string XDefaultAiProjectSuffix = "DefAiPrj"; - public const string XDefaultAiConversationSuffix = "DefAiCnv"; - } - - public enum XAiDataProviderHubActions - { - // - // Project ... - [StringValue("ProjectCreated")] - ProjectCreated, - - [StringValue("ProjectUpdated")] - ProjectUpdated, - - [StringValue("ProjectRemoved")] - ProjectRemoved, - - // - // Message ... - [StringValue("MessageCreated")] - MessageCreated, - - [StringValue("MessageUpdated")] - MessageUpdated, - - [StringValue("MessageRemoved")] - MessageRemoved, - - // - // MCPServer ... - [StringValue("McpServerCreated")] - McpServerCreated, - - [StringValue("McpServerUpdated")] - McpServerUpdated, - - [StringValue("McpServerRemoved")] - McpServerRemoved, - - // - // Conversation ... - [StringValue("ConversationCreated")] - ConversationCreated, - - [StringValue("ConversationUpdated")] - ConversationUpdated, - - [StringValue("ConversationRemoved")] - ConversationRemoved, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiKnowledgeScope.cs - -using xExceptions.Attributes; - -namespace xAiModels.Constants -{ - /// - /// Knowledge Base Scope (Where Ingested Vectors are Visible) ... - /// Identifier Layout: "{scopePrefix}/{scopeKey}/{fileName}#{chunkIndex}" (Global has no scopeKey) ... - /// - public enum XAiKnowledgeScope - { - /// - /// Visible only Inside a Conversation (Key = ConversationId) ... - /// - [StringValue(XAiModelsConstants.XAiKnowledgeConversationPrefix)] - Conversation = 0, - - /// - /// Visible to all Conversations of a Project (Key = ProjectId) ... - /// - [StringValue(XAiModelsConstants.XAiKnowledgeProjectPrefix)] - Project = 1, - - /// - /// Visible to Everyone (Write Requires Admin Role) ... - /// - [StringValue(XAiModelsConstants.XAiKnowledgeGlobalPrefix)] - Global = 2, - - /// - /// Personal Knowledge Base of Owner (Key = UserId) ... - /// - [StringValue(XAiModelsConstants.XAiKnowledgeUserPrefix)] - User = 3, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpConstants.cs - -namespace xAiModels.Constants -{ - public struct XAiMcpConstants - { - // - public const string XAiMcpProtocol = "2024-11-05"; - public const string XAiMcpClientName = "XAiMcpClient"; - public const string XAiMcpSessionIdentifier = "Mcp-Session-Id"; - public const string XAiMcpProtocolIdentifier = "MCP-Protocol-Version"; - - // - public const string TextKey = "text"; - public const string ContentKey = "content"; - public const string ServerInfoNameKey = "name"; - public const string ServerInfoKey = "serverInfo"; - public const string ServerInfoVersionKey = "version"; - public const string ProtocolVersionKey = "protocolVersion"; - - // - public const string serverInfoNameValue = "xAiApi"; - public const string serverInfoVersionValue = ""; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpMethods.cs - -using xExceptions.Attributes; - -namespace xAiModels.Constants -{ - public enum XAiMcpMethods - { - [StringValue("initialize")] - Initialize, - - [StringValue("tools/list")] - ToolsList, - - [StringValue("tools/call")] - ToolsCall, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs - -using xExceptions.Attributes; - -namespace xAiModels.Constants -{ - public enum XAiMcpServerUsageScope - { - [StringValue(XAiModelsConstants.XAiMcpServerUsageScopeAll)] - All = 1, - - [StringValue(XAiModelsConstants.XAiMcpServerUsageScopeOwner)] - Owner = 2 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelProviderType.cs - -namespace xAiModels.Constants -{ - /// - /// Specifiy Provider Type ... - /// - public enum XAiModelProviderType - { - None, - OpenAI, - Ollama, - DeepSeek, - HuggingFace - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelsConstants.cs - -namespace xAiModels.Constants -{ - public struct XAiModelsConstants - { - // - // Service Extensions Log Tag ... - public const string XAiModelsDILogTag = "XAiModels"; - - // - // Table Mapping Identifiers ... - public const string XAiVectorTable = "AiVectors"; - public const string XAiMessageTable = "AiMessages"; - public const string XAiProjectTable = "AiProjects"; - public const string XAiMcpServerTable = "AiMcpServers"; - public const string XAiConversationTable = "AiConversations"; - - // - // GraphQL Collection Mappings ... - public const string XAiMessageSingleName = "aiMessage"; - public const string XAiProjectSingleName = "aiProject"; - public const string XAiMcpServerSingleName = "aiMcpServer"; - public const string XAiConversationSignleName = "aiConversation"; - - public const string XAiMessageCollectionName = "aiMessages"; - public const string XAiProjectCollectionName = "AiProjectsa"; - public const string XAiMcpServerCollectionName = "aiMcpServers"; - public const string XAiConversationCollectionName = "aiConversations"; - - public const string XAiVectorSingleName = "aiVector"; - public const string XAiVectorCollectionName = "aiVectors"; - - // - // Hubs ... - public const string XAiMessageDtoHub = "aiMessageDto"; - public const string XAiMessageEntityHub = "aiMessageEntity"; - - public const string XAiProjectDtoHub = "aiProjectDto"; - public const string XAiProjectEntityHub = "aiProjectEntity"; - - public const string XAiMcpServerDtoHub = "aiMcpServerDto"; - public const string XAiMcpServerEntityHub = "aiMcpServerEntity"; - - public const string XAiConversationDtoHub = "aiConversationDto"; - public const string XAiConversationEntityHub = "aiConversationEntity"; - - public const string XAiVectorDtoHub = "aiVectorDto"; - public const string XAiVectorEntityHub = "aiVectorEntity"; - - // - // Resource Provider Identifiers ... - public const string XAiProjectTitleIdentifier = "AiPrjT"; - public const string XAiProjectDescriptionIdentifier = "AiPrjD"; - public const string XAiConversationTitleIdentifier = "AiCnvrT"; - - // - // EF Repositories Helper Extensions ... - public const string GetXAiVectorEFRepositoryDescriptor = "GetXAiVectorEFRepositoryDescriptor"; - public const string GetXAiMessageEFRepositoryDescriptor = "GetXAiMessageEFRepositoryDescriptor"; - public const string GetXAiProjectEFRepositoryDescriptor = "GetXAiProjectEFRepositoryDescriptor"; - public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor"; - public const string GetXAiConversationEFRepositoryDescriptor = "GetXAiConversationEFRepositoryDescriptor"; - - // - public const string DefaultXAiProjectTitleResourceID = "XAiPrjT"; - public const string DefaultXAiConversationTitleResourceID = "XAiCnvT"; - public const string DefaultXAiProjectDescriptionResourceID = "XAiPrjD"; - - // - public const string XOpenAINoKey = "no-key-required"; - - // - // Knowledge (Persistent RAG) ... - public const string XAiDefaultKnowledgeType = "XAiKnowledge"; - public const string XAiKnowledgeSeparator = "/"; - public const string XAiKnowledgeOwnerSeparator = "/"; - public const string XAiKnowledgeChunkSeparator = "#"; - public const string XAiKnowledgeUserPrefix = "user"; - public const string XAiKnowledgeGlobalPrefix = "global"; - public const string XAiKnowledgeProjectPrefix = "project"; - public const string XAiKnowledgeConversationPrefix = "conversation"; - - // - // Error Handler Route (Production) ... - public const string XAiErrorRoute = "/error"; - - // - // Knowledge Metadata Keys ... - public const string XAiKnowledgeMetadataType = "type"; - public const string XAiKnowledgeMetadataScope = "scope"; - public const string XAiKnowledgeMetadataScopeId = "scopeId"; - public const string XAiKnowledgeMetadataOwnerId = "ownerId"; - public const string XAiKnowledgeMetadataIngestedAtUtc = "ingestedAtUtc"; - - // - // Mcp Server ... - public const int XAiMcpServerMinTimeoutSeconds = 30; - public const string XAiMcpServerUsageScopeAll = "All"; - public const string XAiMcpServerUsageScopeOwner = "Owner"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xPushService.DI; -using xDataService.DI; -using xCommons.Helpers; -using xAiModels.Helpers; -using xDataService.Models; -using xAiModels.Providers; -using xAiModels.Constants; -using xCommons.Extensions; -using xPushService.Helpers; -using xAiModels.Interfaces; -using xExceptions.Constants; -using xDataService.Constants; -using xAiModels.Providers.Dtos; -using xAiModels.Interfaces.Dtos; -using Microsoft.AspNetCore.Builder; -using xAiModels.Providers.Entities; -using xAiModels.Interfaces.Entities; -using xAiModels.Providers.Enrichers; -using xAiModels.Interfaces.Enrichers; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiModels.DI -{ - /// - /// Service Registration Extensions Classes ... - /// - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXAiDataService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddAiDataService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXAiDataService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddAiDataService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XSubCategoryService Middleware ... - /// - /// - /// - public static void UseXAiDataService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - // XAiVector ... - pushHelper.AddHub(XAiModelsConstants.XAiVectorDtoHub); - pushHelper.AddHub(XAiModelsConstants.XAiVectorEntityHub); - - // - // XAiMessage ... - pushHelper.AddHub(XAiModelsConstants.XAiMessageDtoHub); - pushHelper.AddHub(XAiModelsConstants.XAiMessageEntityHub); - - // - // XAiProject ... - pushHelper.AddHub(XAiModelsConstants.XAiProjectDtoHub); - pushHelper.AddHub(XAiModelsConstants.XAiProjectEntityHub); - - // - // XAiMcpServer ... - pushHelper.AddHub(XAiModelsConstants.XAiMcpServerDtoHub); - pushHelper.AddHub(XAiModelsConstants.XAiMcpServerEntityHub); - - // - // XAiConversation ... - pushHelper.AddHub(XAiModelsConstants.XAiConversationDtoHub); - pushHelper.AddHub(XAiModelsConstants.XAiConversationEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XAiConversation Repository Descriptor ... - if (!aiConversationDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: aiConversationDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Using XAiMessage Repository Descriptor ... - if (!aiMessageDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: aiMessageDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Using XAiProject Repository Descriptor ... - if (!aiProjectDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: aiProjectDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Using XAiMcpServer Repository Descriptor ... - if (!aiMcpServerDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: aiMcpServerDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor aiVectorDescriptor = null; - private static XRepositoryDescriptor aiMessageDescriptor = null; - private static XRepositoryDescriptor aiProjectDescriptor = null; - private static XRepositoryDescriptor aiMcpServerDescriptor = null; - private static XRepositoryDescriptor aiConversationDescriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XAiModelsConstants.XAiModelsDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddAiDataService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - // XAiVector ... - aiVectorDescriptor = typeof(XAiModelsHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XAiModelsConstants.GetXAiVectorEFRepositoryDescriptor - ); - - // - // XAiMessage ... - aiMessageDescriptor = typeof(XAiModelsHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XAiModelsConstants.GetXAiMessageEFRepositoryDescriptor - ); - - // - // XAiProject ... - aiProjectDescriptor = typeof(XAiModelsHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XAiModelsConstants.GetXAiProjectEFRepositoryDescriptor - ); - - // - // XAiMcpServer ... - aiMcpServerDescriptor = typeof(XAiModelsHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor - ); - - // - // XAiConversation ... - aiConversationDescriptor = typeof(XAiModelsHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XAiModelsConstants.GetXAiConversationEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - // - // XAiVector ... - aiVectorDescriptor = XAiModelsHelper.GetXAiVectorMongoRepositoryDescriptor(); - - // - // XAiMessage ... - aiMessageDescriptor = XAiModelsHelper.GetXAiMessageMongoRepositoryDescriptor(); - - // - // XAiProject ... - aiProjectDescriptor = XAiModelsHelper.GetXAiProjectMongoRepositoryDescriptor(); - - // - // XAiMcpServer ... - aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor(); - - // - // XAiConversation ... - aiConversationDescriptor = XAiModelsHelper.GetXAiConversationMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - // - // XAiVector ... - aiVectorDescriptor = XAiModelsHelper.GetXAiVectorInMemoryRepositoryDescriptor(); - - // - // XAiMessage ... - aiMessageDescriptor = XAiModelsHelper.GetXAiMessageInMemoryRepositoryDescriptor(); - - // - // XAiProject ... - aiProjectDescriptor = XAiModelsHelper.GetXAiProjectInMemoryRepositoryDescriptor(); - - // - // XAiMcpServer ... - aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor(); - - // - // XAiConversation ... - aiConversationDescriptor = XAiModelsHelper.GetXAiConversationInMemoryRepositoryDescriptor(); - break; - } - - // - #region Register Repository Descriptor ... - // - // XAiVector ... - if (!aiVectorDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: aiVectorDescriptor - ); - } - - // - // XAiMessage ... - if (!aiMessageDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: aiMessageDescriptor - ); - } - - // - // XAiProject ... - if (!aiProjectDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: aiProjectDescriptor - ); - } - - // - // XAiMcpServer ... - if (!aiMcpServerDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: aiMcpServerDescriptor - ); - } - - // - // XAiConversation ... - if (!aiConversationDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: aiConversationDescriptor - ); - } - #endregion - - // - #region Register Services ... - // - #region AiVector ... - // - services.Add( - new ServiceDescriptor(typeof(IXAiVectorServiceProvider), typeof(XAiVectorServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiVectorRepositoryService), typeof(XAiVectorRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiVectorRepositoryProvider), typeof(XAiVectorRepositoryProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXAiVectorEnricher), typeof(XAiVectorEnricher), lifeTime) - ); - #endregion - - // - #region AiMessage ... - // - services.Add( - new ServiceDescriptor(typeof(IXAiMessageServiceProvider), typeof(XAiMessageServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiMessageRepositoryService), typeof(XAiMessageRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiMessageRepositoryProvider), typeof(XAiMessageRepositoryProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXAiMessageEnricher), typeof(XAiMessageEnricher), lifeTime) - ); - #endregion - - // - #region AiProject ... - // - services.Add( - new ServiceDescriptor(typeof(IXAiProjectServiceProvider), typeof(XAiProjectServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiProjectRepositoryService), typeof(XAiProjectRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiProjectRepositoryProvider), typeof(XAiProjectRepositoryProvider), lifeTime) - ); - - // - // Resource Providers ... - services.Add( - new ServiceDescriptor(typeof(IXAiProjectTitleResourceProvider), typeof(XAiProjectTitleResourceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiProjectDescriptionResourceProvider), typeof(XAiProjectDescriptionResourceProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXAiProjectEnricher), typeof(XAiProjectEnricher), lifeTime) - ); - #endregion - - // - #region AiMcpServer ... - // - services.Add( - new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider), typeof(XAiMcpServerServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService), typeof(XAiMcpServerRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider), typeof(XAiMcpServerRepositoryProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXAiMcpServerEnricher), typeof(XAiMcpServerEnricher), lifeTime) - ); - #endregion - - // - #region AiConversation ... - // - services.Add( - new ServiceDescriptor(typeof(IXAiConversationServiceProvider), typeof(XAiConversationServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiConversationRepositoryService), typeof(XAiConversationRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXAiConversationRepositoryProvider), typeof(XAiConversationRepositoryProvider), lifeTime) - ); - - // - // Resource Providers ... - services.Add( - new ServiceDescriptor(typeof(IXAiConversationTitleResourceProvider), typeof(XAiConversationTitleResourceProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXAiConversationEnricher), typeof(XAiConversationEnricher), lifeTime) - ); - #endregion - #endregion - - // - // Data Provider ... - services.Add( - new ServiceDescriptor(typeof(IXAiDataProvider), typeof(XAiDataProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatResponseExtensions.cs - -using xCommons.Extensions; -using Microsoft.Extensions.AI; - -namespace xAiModels.Extensions -{ - public static class ChatResponseExtensions - { - /// - /// Validate a Chat Response ... - /// - /// - /// - public static bool IsValid(this ChatResponse source) - { - // - var result = - source is not null && - !source.IsNullOrDefault() && - !string.IsNullOrWhiteSpace(source.Text) && - (source.FinishReason == ChatFinishReason.Stop || - source.FinishReason == ChatFinishReason.ToolCalls); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\ChatRoleExtensions.cs - -using xAiModels.Constants; -using xCommons.Extensions; -using Microsoft.Extensions.AI; - -namespace xAiModels.Extensions -{ - /// - /// Extensions for ChatRole ... - /// - public static class ChatRoleExtensions - { - /// - /// Normalize an String to Propper Chat Role Value ... - /// > - /// - /// - /// - public static string GetChatRoleTitle(this string source) - { - // - var result = XAiChatRoles.None; - - // - if (source.ToNormalString() == XAiChatRoles.None.ToNormalString()) - { - result = XAiChatRoles.None; - } - else if (source.ToNormalString() == XAiChatRoles.User.ToNormalString()) - { - result = XAiChatRoles.User; - } - else if (source.ToNormalString() == XAiChatRoles.Tool.ToNormalString()) - { - result = XAiChatRoles.Tool; - } - else if (source.ToNormalString() == XAiChatRoles.System.ToNormalString()) - { - result = XAiChatRoles.System; - } - else if (source.ToNormalString() == XAiChatRoles.Assistant.ToNormalString()) - { - result = XAiChatRoles.Assistant; - } - - // - return result; - } - - /// - /// Get Chat Role Title from Chat Role Class ... - /// - /// - /// - /// - public static string GetRole(this ChatRole source) - { - // - var result = source.Value - .GetChatRoleTitle(); - - // - return result; - } - - /// - /// Generate Chat Role Class Based on role Title ... - /// - /// - /// - public static ChatRole ToChatRole(this string source) - { - // - var role = source.GetChatRoleTitle(); - ChatRole result = new ChatRole(role); - - // - return result; - } - - /// - /// Generate Chat Role Class Based on role Title ... - /// - /// - /// - public static ChatRole ToChatRole(this XAiChatRole source) - { - // - var role = source.GetStringValue(); - ChatRole result = new ChatRole(role); - - // - return result; - } - - /// - /// Extract Chat Role Enum from Chat Role ... - /// - /// - /// - /// - /// - public static XAiChatRole ToChatRole(this ChatRole source) - { - // - var role = source - .GetRole() - .GetChatRoleTitle(); - - // - XAiChatRole result = XAiChatRole.User; - - // - if (role == XAiChatRoles.User) - { - result = XAiChatRole.User; - } - else if (role == XAiChatRoles.Tool) - { - result = XAiChatRole.Tool; - } - else if (role == XAiChatRoles.System) - { - result = XAiChatRole.System; - } - else if (role == XAiChatRoles.Assistant) - { - result = XAiChatRole.Assistant; - } - - // - return result; - } - - /// - /// Validate an String as Chat Role ... - /// - /// - /// - public static bool IsValid(this string source) - { - // - var result = - source != XAiChatRoles.None && - source.ToNormalString() != XAiChatRoles.None.ToNormalString(); - - // - return result; - } - - /// - /// Validate Role ... - /// > - /// - /// - /// - public static bool IsValid(this XAiChatRole source) - { - // - var result = source != XAiChatRole.None; - return result; - } - - /// - /// Validate Role ... - /// > - /// - /// - /// - public static bool IsValid(this ChatRole source) - { - // - var role = source.ToChatRole(); - var result = role.IsValid(); - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XAiModelsExtensions.cs - -using System; -using System.Linq; -using System.Net.Http; -using xAiModels.Models; -using xCommons.Constants; -using xModels.Extensions; -using xCommons.Extensions; -using xAiModels.Constants; -using xAiModels.Models.Dtos; -using xExceptions.Constants; -using Microsoft.Extensions.AI; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Extensions -{ - /// - /// Extensions Methods for XAiModels ... - /// - public static class XAiModelsExtensions - { - /// - /// Validate a Project for Add Or Update ... - /// - /// - /// - public static bool IsValidForAddOrUpdate(this XAiProject source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - !source.Prompt.IsNullOrEmpty(); - - // - return result; - } - public static bool IsValidForAddOrUpdate(this XAiProjectDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - !source.Prompt.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate a Conversation for Add Or Update ... - /// - /// - /// - public static bool IsValidForAddOrUpdate(this XAiConversation source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - !source.ProjectId.IsNull() && - !source.ProjectId.IsDefaultGuid(); - - // - return result; - } - public static bool IsValidForAddOrUpdate(this XAiConversationDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - !source.ProjectId.IsNull() && - !source.ProjectId.IsDefaultGuid(); - - // - return result; - } - - /// - /// Validate a Message for Add Or Update ... - /// - /// - /// - public static bool IsValidForAddOrUpdate(this XAiMessage source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - source.Role.IsValid() && - !source.ConversationId.IsNull() && - !source.ConversationId.IsDefaultGuid() && - !source.Content.IsNullOrEmpty(); - - // - return result; - } - public static bool IsValidForAddOrUpdate(this XAiMessageDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - source.Role.IsValid() && - !source.ConversationId.IsNull() && - !source.ConversationId.IsDefaultGuid() && - !source.Content.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate a McpServer for Add Or Update ... - /// - /// - /// - public static bool IsValidForAddOrUpdate(this XAiMcpServer source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty() && - !source.OwnerId.IsNullOrEmpty() && - !source.Endpoint.IsNullOrEmpty(); - - // - return result; - } - public static bool IsValidForAddOrUpdate(this XAiMcpServerDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty() && - !source.OwnerId.IsNullOrEmpty() && - !source.Endpoint.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate a Model Descriptor ... - /// - /// - /// - public static bool IsValid(this XAiModelDescriptor source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty() && - !source.Url.IsNullOrEmpty() && - source.Url.IsValidUrl() && - !source.LLM.IsNullOrEmpty() && - source.Provider != Constants.XAiModelProviderType.None; - - // - return result; - } - - /// - /// Validate Specified Param ... - /// - /// - /// - public static bool IsValid(this XAiPromptParam source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty() && - !source.Param.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Specified Prompt ... - /// - /// - /// - public static bool IsValid(this XAiPromptDescriptor source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty() && - !source.Template.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - if (source.Params.HasChild()) - { - result = - result && - source.Params.All(x => x.IsValid()); - } - - // - return result; - } - - /// - /// Validate a Request for Retrieve Response in Controllers ... - /// - /// - /// - public static bool IsValid(this XAiResponseRequest source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Prompt.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate a File Extraction Result ... - /// - /// - /// - public static bool IsValid(this XFileExtractionResult source) - { - // - var result = - !source.IsNullOrDefault() && - ( - source.Images.HasChild() || - !source.Text.IsNullOrEmpty() || - !source.AudioTranscript.IsNullOrEmpty() - ); - return result; - } - - /// - /// Converts a File Extraction Result to AI Contents ... - /// - /// - /// - public static IList ToAIContents(this XFileExtractionResult source) - { - // - var result = new List(); - - // - if (source.IsValid()) - { - // - // Main Text ... - if (!source.Text.IsNullOrEmpty()) - { - result.Add(new TextContent(source.Text)); - } - - // - // Images ... - if (source.Images.HasChild()) - { - // - foreach (var img in source.Images) - { - result.Add(new DataContent(img.Bytes, img.MimeType)); - } - } - - // - // Transcripted Audio ... - if (!source.AudioTranscript.IsNullOrEmpty()) - { - result.Add(new TextContent($"[Audio Transcript]\n{source.AudioTranscript}")); - } - } - - // - return result; - } - - /// - /// Check a Collection Contains Default Project for Specified Owner or not ... - /// - /// - /// - /// - public static bool HasDefaultProject( - this IEnumerable source, - string ownerId - ) - { - // - // Validate Args ... - if (!source.HasChild() || - ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var item = source - .FirstOrDefault(x => - x.Title - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.Title - .ToNormalString() - .Contains(XAiModelsConstants.DefaultXAiProjectDescriptionResourceID.ToNormalString()) - ); - - // - var result = !item.IsNullOrDefault(); - - // - return result; - } - - /// - /// Check a Collection Contains Default Conversation for Specified Project or not ... - /// - /// - /// - /// - /// - public static bool HasDefaultConversation( - this IEnumerable source, - string ownerId, - Guid projectId - ) - { - // - // Validate Args ... - if (!source.HasChild() || - projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var item = source - .FirstOrDefault(x => - x.Title - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.Title - .ToNormalString() - .Contains(projectId.ToString().ToNormalString()) && - x.Title - .ToNormalString() - .Contains(XAiModelsConstants.DefaultXAiConversationTitleResourceID) - ); - - // - var result = !item.IsNullOrDefault(); - - // - return result; - } - - /// - /// Retrieve Default Project Id from a Collection ... - /// - /// - /// - /// - public static Guid GetDafaultProject( - this IEnumerable source, - string ownerId - ) - { - // - // Validate Args ... - if (!source.HasChild() || - ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var item = source - .FirstOrDefault(x => - x.Title - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.Title - .ToNormalString() - .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) - ); - if (item.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return item.Id; - } - - /// - /// Get Default Conversation Id from a Collection Contains ... - /// - /// - /// - /// - /// - public static Guid GetDefaultConversation( - this IEnumerable source, - string ownerId, - Guid projectId - ) - { - // - // Validate Args ... - if (!source.HasChild() || - ownerId.IsNullOrEmpty() || - projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var item = source - .FirstOrDefault(x => - x.Title - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.Title - .ToNormalString() - .Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) - ); - if (item.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = item.Id; - - // - return result; - } - - /// - /// Converts a Message Dto to ChatMessage ... - /// - /// - /// - /// - public static ChatMessage ToChatMessages( - this XAiMessageDto source, - IList additionalContents = null - ) - { - // - ChatMessage result = null; - - // - if (!source.IsNullOrDefault()) - { - // - var contents = new List - { - // - // Add Source Content ... - new TextContent(source.Content) - }; - - // - // Add Additional Content ... - if (additionalContents.HasChild()) - { - contents.AddRange(additionalContents); - } - - // - result = new ChatMessage - { - Contents = contents, - AuthorName = - source.Role == XAiChatRole.User && - !source.Owner.IsNullOrDefault() - ? source.Owner.GetFullname() - : string.Empty, - Role = source.Role.ToChatRole(), - MessageId = source.Id.ToString(), - }; - } - - // - return result; - } - - /// - /// Add Model Provider API Key ... - /// - /// - /// - public static void AddModelDescriptorApiKey( - this XAiModelDescriptor descriptor, - HttpRequestMessage request - ) - { - // - // Validate ... - if (!descriptor.IsValid() || request.IsNull()) - { - return; - } - - // - var apiKey = - descriptor.Provider != XAiModelProviderType.OpenAI - ? descriptor.ApiKey - : descriptor.ApiKey.IsNullOrEmpty() - ? XAiModelsConstants.XOpenAINoKey - : descriptor.ApiKey; - request.Headers.TryAddWithoutValidation( - name: XAuthorization.Header, - value: $"{XAuthorization.TokenIdentifier} {apiKey}" - ); - } - - /// - /// Converts To AITools ... - /// - /// - /// - public static IList ToAITools( - this IList source - ) - { - // - var result = new List(); - - // - foreach (var tool in source) - { - // - var declaration = AIFunctionFactory.CreateDeclaration( - name: tool.Name, - jsonSchema: tool.InputSchema, - description: tool.Description - ); - - // - result.Add(declaration); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Extensions\XEmbeddingExtensions.cs - -using System; -using xCommons.Extensions; - -namespace xAiModels.Extensions -{ - public static class XEmbeddingExtensions - { - /// - /// Converts String to Embeddings JSON ... - /// - /// - /// - public static float[] AsEmbedding(this string source) - { - // - // Validate ... - if (source.IsNullOrEmpty()) - { - return []; - } - - // - // JSON is expected to be like: [0.12, 0.34, ...] ... - var result = source.FromJSON(); - if (!result.HasChild()) - { - result = []; - } - - // - return result; - } - - /// - /// Converts ReadOnly Memory to Embedding Representation ... - /// - /// - /// - public static string ToEmbedding(this ReadOnlyMemory source) - { - // - var result = string.Empty; - - // - if (!source.IsNull() && !source.IsEmpty) - { - result = source.ToArray().ToJSON(); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\VectorHelper.cs - -using System; -using xCommons.Extensions; -using System.Numerics.Tensors; -using xExceptions.Constants; - -namespace xAiModels.Helpers -{ - public static class VectorHelper - { - /// - /// Normalize a Vector ... - /// - /// - public static void Normalize(float[] vector) - { - // - // Validate ... - if (vector.IsNull() || !vector.HasChild()) - { - return; - } - - // - float sum = 0f; - foreach (var value in vector) - { - sum += value * value; - } - - // - float norm = MathF.Sqrt(sum); - if (norm <= 1e-9f) - { - return; - } - - // - for (int i = 0; i < vector.Length; i++) - { - vector[i] /= norm; - } - } - - /// - /// Similarity Check ... - /// - /// - /// - /// - public static float CosineSimilarity( - float[] a, - float[] b - ) - { - // - // Validate ... - if (a.Length != b.Length) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Similarity ... - var result = TensorPrimitives - .CosineSimilarity( - a.AsSpan(), - b.AsSpan() - ); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs - -using xCommons.Constants; -using xCommons.Extensions; -using xAiModels.Constants; -using xIdentityModels.Models; -using xCommons.Configurations; -using System.Collections.Generic; -using xIdentityService.Constants; - -namespace xAiModels.Helpers -{ - /// - /// a Helper Class for Prepare Headers of MCP Client ... - /// - public static class XAiMcpHeaderBuilder - { - /// - /// Build Headers for MCP Client Connection ... - /// - /// - /// - /// - /// - /// - /// - public static Dictionary Build( - XAppConfiguration appConfiguration, - string sessionId = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - string protocolVersion = XAiMcpConstants.XAiMcpProtocol - ) - { - // - var headers = new Dictionary - { - // - ["Accept"] = "application/json, text/event-stream", - ["Content-Type"] = "application/json", - [XAiMcpConstants.XAiMcpProtocolIdentifier] = protocolVersion, - [XAuthorization.XPoweredBy] = appConfiguration.XPoweredValue ?? "xAiApi" - }; - - // - // Adding Authorization Headers ... - if (!userInfo.IsNullOrDefault() && !userInfo.AccessToken.IsNullOrEmpty()) - { - // - headers[XAuthorization.Header] = $"{XAuthorization.TokenIdentifier} {userInfo.AccessToken}"; - headers[XAuthorization.ExpiresAt] = userInfo.ExpiresAt.ToString(); - - // - if (!userInfo.RefreshToken.IsNullOrEmpty()) - { - headers[XAuthorization.RefreshToken] = userInfo.RefreshToken; - } - } - - // - // شناسه اتصال (برای Push Notification ها) - if (!connectionId.IsNullOrEmpty()) { - headers[XHeader.ConnectionId.GetStringValue()] = connectionId; - } - - // - // Session Id ... - if (!sessionId.IsNullOrEmpty()) { - headers[XAiMcpConstants.XAiMcpSessionIdentifier] = sessionId; - } - - // - return headers; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs - -using System; -using System.IO; -using System.Text; -using System.Threading; -using xCommons.Extensions; -using xHttpService.Constants; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace xAiModels.Helpers -{ - public static class XAiMcpSseReader - { - /// - /// Read an SSE Event ... - /// - /// - /// - /// - public static async IAsyncEnumerable ReadAsync( - Stream stream, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - using var reader = new StreamReader(stream, Encoding.UTF8); - var dataBuffer = new StringBuilder(); - while (!reader.EndOfStream) - { - // - var line = await reader.ReadLineAsync(); - if (line is null) - { - break; - } - - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - // Empty Line equals End of an Event ... - if (line.IsNullOrEmpty()) - { - // - if (dataBuffer.Length > 0) - { - // - yield return dataBuffer.ToString(); - dataBuffer.Clear(); - } - - // - continue; - } - - // - if (line.StartsWith(XSSEConstants.DataIdentifier, StringComparison.OrdinalIgnoreCase)) - { - // - var data = line - .Substring(XSSEConstants.DataIdentifier.Length) - .TrimStart(); - - // - if (dataBuffer.Length > 0) - { - dataBuffer.Append('\n'); - } - - // - dataBuffer.Append(data); - } - } - - // - if (dataBuffer.Length > 0) - { - yield return dataBuffer.ToString(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs - -using System; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Providers.GraphQL; -using xAiModels.Providers.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Helpers -{ - public static class XAiModelsHelper - { - // - #region XAiConversation ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationEFRepository, - TContext - > GetXAiConversationEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationEFRepository, - TContext, - IXAiConversationSeeder, - TSeederImplementation - > GetXAiConversationEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationEFRepository, - TContext, - IXAiConversationSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationMongoRepository - > GetXAiConversationMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationMongoRepository, - IXAiConversationSeeder, - TSeederImplementation - > GetXAiConversationMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationMongoRepository, - IXAiConversationSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationInMemoryRepository - > GetXAiConversationInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationInMemoryRepository, - IXAiConversationSeeder, - TSeederImplementation - > GetXAiConversationInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiConversation, - Guid, - IXAiConversationKeyGenerator, - XAiConversationKeyGenerator, - IXAiConversationRepositoryEvents, - XAiConversationRepositoryEvents, - XAiConversationGraphType, - GuidGraphType, - XAiConversationGraphQuery, - IXAiConversationGraphQLTypeHelper, - XAiConversationGraphQLTypeHelper, - XAiConversationGraphSchema, - IXAiConversationRepository, - XAiConversationInMemoryRepository, - IXAiConversationSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region XAiMessage ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageEFRepository, - TContext - > GetXAiMessageEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageEFRepository, - TContext, - IXAiMessageSeeder, - TSeederImplementation - > GetXAiMessageEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageEFRepository, - TContext, - IXAiMessageSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageMongoRepository - > GetXAiMessageMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageMongoRepository, - IXAiMessageSeeder, - TSeederImplementation - > GetXAiMessageMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageMongoRepository, - IXAiMessageSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageInMemoryRepository - > GetXAiMessageInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageInMemoryRepository, - IXAiMessageSeeder, - TSeederImplementation - > GetXAiMessageInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiMessage, - Guid, - IXAiMessageKeyGenerator, - XAiMessageKeyGenerator, - IXAiMessageRepositoryEvents, - XAiMessageRepositoryEvents, - XAiMessageGraphType, - GuidGraphType, - XAiMessageGraphQuery, - IXAiMessageGraphQLTypeHelper, - XAiMessageGraphQLTypeHelper, - XAiMessageGraphSchema, - IXAiMessageRepository, - XAiMessageInMemoryRepository, - IXAiMessageSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region XAiProject ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectEFRepository, - TContext - > GetXAiProjectEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectEFRepository, - TContext, - IXAiProjectSeeder, - TSeederImplementation - > GetXAiProjectEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectEFRepository, - TContext, - IXAiProjectSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectMongoRepository - > GetXAiProjectMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectMongoRepository, - IXAiProjectSeeder, - TSeederImplementation - > GetXAiProjectMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectMongoRepository, - IXAiProjectSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectInMemoryRepository - > GetXAiProjectInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectInMemoryRepository, - IXAiProjectSeeder, - TSeederImplementation - > GetXAiProjectInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiProject, - Guid, - IXAiProjectKeyGenerator, - XAiProjectKeyGenerator, - IXAiProjectRepositoryEvents, - XAiProjectRepositoryEvents, - XAiProjectGraphType, - GuidGraphType, - XAiProjectGraphQuery, - IXAiProjectGraphQLTypeHelper, - XAiProjectGraphQLTypeHelper, - XAiProjectGraphSchema, - IXAiProjectRepository, - XAiProjectInMemoryRepository, - IXAiProjectSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region XAiVector ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorEFRepository, - TContext - > GetXAiVectorEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorEFRepository, - TContext, - IXAiVectorSeeder, - TSeederImplementation - > GetXAiVectorEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorEFRepository, - TContext, - IXAiVectorSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorMongoRepository - > GetXAiVectorMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorMongoRepository, - IXAiVectorSeeder, - TSeederImplementation - > GetXAiVectorMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorMongoRepository, - IXAiVectorSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorInMemoryRepository - > GetXAiVectorInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorInMemoryRepository, - IXAiVectorSeeder, - TSeederImplementation - > GetXAiVectorInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiVector, - Guid, - IXAiVectorKeyGenerator, - XAiVectorKeyGenerator, - IXAiVectorRepositoryEvents, - XAiVectorRepositoryEvents, - XAiVectorGraphType, - GuidGraphType, - XAiVectorGraphQuery, - IXAiVectorGraphQLTypeHelper, - XAiVectorGraphQLTypeHelper, - XAiVectorGraphSchema, - IXAiVectorRepository, - XAiVectorInMemoryRepository, - IXAiVectorSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region XAiMcpServer ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerEFRepository, - TContext - > GetXAiMcpServerEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerEFRepository, - TContext, - IXAiMcpServerSeeder, - TSeederImplementation - > GetXAiMcpServerEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerEFRepository, - TContext, - IXAiMcpServerSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerMongoRepository - > GetXAiMcpServerMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerMongoRepository, - IXAiMcpServerSeeder, - TSeederImplementation - > GetXAiMcpServerMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerMongoRepository, - IXAiMcpServerSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerInMemoryRepository - > GetXAiMcpServerInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerInMemoryRepository, - IXAiMcpServerSeeder, - TSeederImplementation - > GetXAiMcpServerInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XAiMcpServer, - Guid, - IXAiMcpServerKeyGenerator, - XAiMcpServerKeyGenerator, - IXAiMcpServerRepositoryEvents, - XAiMcpServerRepositoryEvents, - XAiMcpServerGraphType, - GuidGraphType, - XAiMcpServerGraphQuery, - IXAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphQLTypeHelper, - XAiMcpServerGraphSchema, - IXAiMcpServerRepository, - XAiMcpServerInMemoryRepository, - IXAiMcpServerSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiConversationTitleResourceProvider.cs - -using xStringService.Interfaces; - -namespace xAiModels.Interfaces -{ - public interface IXAiConversationTitleResourceProvider : IXOwnedItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiDataProvider.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xAiModels.Interfaces -{ - /// - /// All Data Manipulation Requirements ... - /// - public interface IXAiDataProvider - { - // - #region Getters ... - /// - /// Retrieve Specified Project ... - /// - /// - /// - /// - /// - /// - Task GetProject( - Guid id, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Conversation ... - /// - /// - /// - /// - /// - Task GetConversation( - Guid id, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Loaders ... - /// - /// Load Projects List of Specified Owner ... - /// - /// - /// - /// - /// - /// - /// - Task> LoadProjects( - string ownerId, - string connectionId = null, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Load List of Conversations for Specified Project ... - /// - /// - /// - /// - /// - /// - Task> LoadConversations( - Guid projectId, - bool fillMessages = false, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Defaults ... - /// - /// Retrieve Default Project of Specified Owner ... - /// Create it if not Handled ... - /// - /// - /// - /// - /// - Task GetDefaultProject( - string ownerId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Default Conversation of Specified Owner ... - /// Create it if not Handled ... - /// - /// - /// - /// - /// - /// - Task GetDefaultConversation( - string ownerId, - Guid? projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Creator/Adders ... - /// - /// Create Project ... - /// - /// - /// - /// - /// - /// - Task CreateProject( - string ownerId, - XAiProjectDto item = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Create Conversation ... - /// - /// - /// - /// - /// - /// - /// - Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Message ... - /// - /// - /// - /// - /// - /// - Task AddMessage( - Guid conversationId, - XAiMessageDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Query ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Vectors ... - /// - /// Insert or Update a Single Vector (Matched by Identifier) ... - /// - /// - /// - /// - /// - /// - /// - /// - Task UpsertVectorAsync( - string identifier, - string text, - ReadOnlyMemory embedding, - Dictionary metadata = null, - string type = null, - CancellationToken cancellationToken = default - ); - - /// - /// Insert or Update a Batch of Vectors (Matched by Identifier) ... - /// - /// - /// - /// Count of Stored Vectors - Task UpsertVectorsAsync( - IEnumerable items, - CancellationToken cancellationToken = default - ); - - /// - /// Search Vectors by Cosine Similarity (Top K) ... - /// - /// - /// - /// - /// Optional: Restrict Search to Vectors whose Identifier Starts with this Prefix - /// Optional: Restrict Search to Vectors of Specified Type - /// - /// - Task> SearchVectorsAsync( - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, - string identifierPrefix = null, - string type = null, - CancellationToken cancellationToken = default - ); - - /// - /// Load Vectors whose Identifier Starts with Specified Prefix ... - /// - /// - /// - /// Optional: Restrict to Vectors of Specified Type - /// - /// - Task> LoadVectorsAsync( - string identifierPrefix, - bool includeEmbedding = false, - string type = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Vectors whose Identifier Starts with Specified Prefix ... - /// - /// - /// Optional: Restrict to Vectors of Specified Type - /// - /// Count of Removed Vectors - Task RemoveVectorsAsync( - string identifierPrefix, - string type = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectDescriptionResourceProvider.cs - -using xStringService.Interfaces; - -namespace xAiModels.Interfaces -{ - public interface IXAiProjectDescriptionResourceProvider : IXOwnedItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\IXAiProjectTitleResourceProvider.cs - -using xStringService.Interfaces; - -namespace xAiModels.Interfaces -{ - public interface IXAiProjectTitleResourceProvider : IXOwnedItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationDtoHub.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiConversationDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationRepositoryService.cs - -using System; -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiConversationRepositoryService : IXBaseRepositoryService - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - Task Enrich( - XAiConversation source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiConversationServiceProvider.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Providers.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiConversationServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerDtoHub.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMcpServerDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerRepositoryService.cs - -using System; -using xAiModels.Models.Dtos; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMcpServerRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerServiceProvider.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Providers.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMcpServerServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageDtoHub.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMessageDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageRepositoryService.cs - -using System; -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMessageRepositoryService : IXBaseRepositoryService - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiMessage source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageServiceProvider.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Providers.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiMessageServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectDtoHub.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiProjectDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectRepositoryService.cs - -using System; -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiProjectRepositoryService : IXBaseRepositoryService - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - Task Enrich( - XAiProject source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiProjectServiceProvider.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Providers.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiProjectServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorDtoHub.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiVectorDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorRepositoryService.cs - -using System; -using xAiModels.Models.Dtos; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiVectorRepositoryService : IXBaseRepositoryService - { - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiVectorServiceProvider.cs - -using System; -using xAiModels.Models.Dtos; -using xPushService.Interfaces; -using xAiModels.Providers.Dtos; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Dtos -{ - public interface IXAiVectorServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiConversationEnricher.cs - -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Enrichers -{ - /// - /// Ai Conversation Enricher ... - /// - public interface IXAiConversationEnricher - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - Task Enrich( - XAiConversation source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMcpServerEnricher.cs - -using System.Threading; -using System.Threading.Tasks; -using xAiModels.Models.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Enrichers -{ - public interface IXAiMcpServerEnricher - { - Task Enrich( - XAiMcpServer source, - CancellationToken cancellationToken = default - ); - - Task Enrich( - XAiMcpServerDto source, - CancellationToken cancellationToken = default - ); - - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMessageEnricher.cs - -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Enrichers -{ - public interface IXAiMessageEnricher - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiMessage source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiProjectEnricher.cs - -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Enrichers -{ - public interface IXAiProjectEnricher - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - Task Enrich( - XAiProject source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiVectorEnricher.cs - -using System.Threading; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; - -namespace xAiModels.Interfaces.Enrichers -{ - public interface IXAiVectorEnricher - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiVector source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XAiVectorDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationEntityHub.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepository.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryEvents.cs - -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; -using xAiModels.Providers.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiConversationSeeder.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiConversationSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiDocumentEntityHub.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiDocumentEntityHub - { - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerEntityHub.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepository.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerRepository : IXBaseRepository { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryEvents.cs - -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; -using xAiModels.Providers.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerSeeder.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMcpServerSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageEntityHub.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepository.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryEvents.cs - -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; -using xAiModels.Providers.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageSeeder.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiMessageSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectEntityHub.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepository.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryEvents.cs - -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; -using xAiModels.Providers.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiProjectSeeder.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiProjectSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorEntityHub.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepository.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryEvents.cs - -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xAiModels.Models.Entities; -using xAiModels.Providers.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiVectorSeeder.cs - -using System; -using xDataService.Interfaces; -using xAiModels.Models.Entities; - -namespace xAiModels.Interfaces.Entities -{ - public interface IXAiVectorSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcError.cs - -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace xAiModels.Models -{ - public class XAiMcpJsonRpcError - { - [JsonPropertyName("code")] - public int Code { get; set; } - - [JsonPropertyName("message")] - public string Message { get; set; } - - [JsonPropertyName("data")] - public JsonElement? Data { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcRequest.cs - -using System; -using System.Text.Json.Serialization; - -namespace xAiModels.Models -{ - public class XAiMcpJsonRpcRequest - { - [JsonPropertyName("jsonrpc")] - public string JsonRpc { get; set; } = "2.0"; - - [JsonPropertyName("id")] - public string Id { get; set; } = Guid.NewGuid().ToString("N"); - - [JsonPropertyName("method")] - public string Method { get; set; } - - [JsonPropertyName("params")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public object Params { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcResponse.cs - -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace xAiModels.Models -{ - public class XAiMcpJsonRpcResponse - { - [JsonPropertyName("jsonrpc")] - public string JsonRpc { get; set; } - - [JsonPropertyName("id")] - public string Id { get; set; } - - [JsonPropertyName("result")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public JsonElement? Result { get; set; } - - [JsonPropertyName("error")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public XAiMcpJsonRpcError Error { get; set; } - - [JsonIgnore] - public bool IsSuccess => Error is null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDefinition.cs - -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace xAiModels.Models -{ - public class XAiMcpToolDefinition - { - [JsonPropertyName("name")] - public string Name { get; set; } - - [JsonPropertyName("description")] - public string Description { get; set; } - - [JsonPropertyName("inputSchema")] - public JsonElement InputSchema { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs - -using System; -using System.Threading; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; - -namespace xAiModels.Models -{ - public class XAiMcpToolDescriptor - { - public string Name { get; set; } - public string Description { get; set; } - public JObject InputSchema { get; set; } - public string RequiredPolicy { get; set; } - public bool RequiresAuthentication { get; set; } = false; - public Func> Execute { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiModelDescriptor.cs - -using xAiModels.Constants; - -namespace xAiModels.Models -{ - /// - /// Describe a Provided Model ... - /// - public class XAiModelDescriptor - { - /// - /// Provider Name ... - /// - public string Name { get; set; } - - /// - /// LLM Provider Url ... - /// - public string Url { get; set; } - - /// - /// Model Name ... - /// - public string LLM { get; set; } - - /// - /// Api Key for Connection ... - /// - public string ApiKey { get; set; } - - /// - /// Specified Model Provider Type ... - /// - public XAiModelProviderType Provider { get; set; } = XAiModelProviderType.Ollama; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiPromptDescriptor.cs - -namespace xAiModels.Models -{ - /// - /// Describe Specified Prompt ... - /// - public class XAiPromptDescriptor - { - /// - /// Prompt Name ... - /// - public string Name { get; set; } - - /// - /// Prompt Template ... - /// - public string Template { get; set; } - - /// - /// Prompt Description ... - /// - public string Description { get; set; } - - /// - /// Prompt Template Params ... - /// - public XAiPromptParam[] Params { get; set; } = []; - } - - /// - /// Specified a Prompt Param ... - /// - public class XAiPromptParam - { - /// - /// Param Name ... - /// - public string Name { get; set; } - - /// - /// Param Identifier ... - /// - public string Param { get; set; } - - /// - /// Parma Description ... - /// - public string Description { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResonseMessage.cs - -using System; -using xModels.Base; -using xAiModels.Constants; - -namespace xAiModels.Models -{ - public class XAiResonseMessage : XBaseDto - { - public long Sequence { get; set; } - public Guid RespondTo { get; set; } - public string OwnerId { get; set; } - public string Content { get; set; } - public XAiChatRole Role { get; set; } - public DateTime RespondedOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiResponseRequest.cs - -using System; -using xAiModels.Constants; - -namespace xAiModels.Models -{ - /// - /// /Request for a Response in Controllers ... - /// - public class XAiResponseRequest - { - /// - /// Prompt Text ... - /// - public string Prompt { get; set; } - - /// - /// Knowledge Type ... - /// - public string Type { get; set; } = XAiModelsConstants.XAiDefaultKnowledgeType; - - /// - /// Provided TopK in Vector Searchs ... - /// - public int? TopK { get; set; } - - /// - /// Min Score for Vector Searchs ... - /// - public float? MinScore { get; set; } - - /// - /// Specified Project Id ... - /// - public Guid? ProjectId { get; set; } - - /// - /// Specified Conversation Id ... - /// - public Guid? ConversationId { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\XFileExtractionResult.cs - -using System.Collections.Generic; - -namespace xAiModels.Models -{ - /// - /// Holds File Extraction Result ... - /// - public class XFileExtractionResult - { - /// - /// Extracted String Content ... - /// - public string Text { get; set; } = string.Empty; - - /// - /// Extracted Images for Vision Model ... - /// - public IList Images { get; set; } = []; - - /// - /// Extracted Content from Audio File ... - /// - public string AudioTranscript { get; set; } = string.Empty; - - /// - /// Main File Name ... - /// - public string FileName { get; set; } - - /// - /// Main File MIME Type ... - /// - public string MimeType { get; set; } - - /// - /// Specified Fallback done using Images or not ... - /// - public bool UsedImageFallback { get; set; } = false; - - /// - /// Error Message ... - /// - public string ErrorMessage { get; set; } - } - - /// - /// Extracted Image ... - /// - public class XExtractedImage - { - /// - /// Content as Byte ... - /// - public byte[] Bytes { get; set; } - - /// - /// MIME Type of Image ... - /// - public string MimeType { get; set; } = "image/png"; - - /// - /// for PDF Files ... - /// - public int? PageNumber { get; set; } - - /// - /// Describe Image ... - /// - public string Description { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiConversationDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using System.Collections.Generic; - -namespace xAiModels.Models.Dtos -{ - /// - /// Conversation Describe ... - /// - public class XAiConversationDto : XBaseGuidIDEntityDto - { - /// - /// User Identifier ... - /// - /// - public string OwnerId { get; set; } - - /// - /// Owner Info ... - /// - public virtual XPersonDto Owner { get; set; } = null; - - /// - /// Conversation Title Resource ID ... - /// - public string Title { get; set; } - - /// - /// All Exists Title Locale Resources ... - /// - public virtual XResourceDto TitleResource { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - - /// - /// Conversation Messages ... - /// - public virtual IEnumerable Messages { get; set; } = []; - - /// - /// Project ID ... - /// - public Guid ProjectId { get; set; } - - /// - /// Project Title Resource ID ... - /// - public virtual string ProjectTitle { get; set; } = null; - - /// - /// Project Description Resource ID ... - /// - public virtual string ProjectDescription { get; set; } = null; - - /// - /// Project Title Locale Resources ... - /// - public virtual XResourceDto ProjectTitleResource { get; set; } - - /// - /// Project Description Locale Resources ... - /// - public virtual XResourceDto ProjectDescriptionResource { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMcpServerDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xAiModels.Constants; - -namespace xAiModels.Models.Dtos -{ - public class XAiMcpServerDto : XBaseGuidIDEntityDto - { - /// - /// Owner ... - /// - public string OwnerId { get; set; } - public virtual XPersonDto Owner { get; set; } - - /// - /// Specified Which Scope can Use MCP Server ... - /// - public XAiMcpServerUsageScope Scope { get; set; } = XAiMcpServerUsageScope.Owner; - - /// - /// MCP Server Name ... - /// - public string Name { get; set; } - - /// - /// Description ... - /// - public string Description { get; set; } - - /// - /// Enabled or Disabled ... - /// - public bool Enabled { get; set; } = true; - - /// - /// Environment Variables as JSON Object ... - /// - public string EnvironmentVariables { get; set; } - - /// - /// Endpoint to Connect ... - /// - public string Endpoint { get; set; } - - /// - /// Headers List as Json Object ... - /// - public string Headers { get; set; } - - /// - /// Timout Secconds ... - /// - public int TimeoutSeconds { get; set; } = 30; - - public DateTime CreatedOn { get; set; } - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMessageDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xAiModels.Constants; -using xCommons.Extensions; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xAiModels.Models.Dtos -{ - public class XAiMessageDto : XBaseGuidIDEntityDto - { - /// - /// User Identifier ... - /// - /// - public string OwnerId { get; set; } - - /// - /// Owner Info ... - /// - public virtual XPersonDto Owner { get; set; } = null; - - /// - /// Message of Chat ... - /// - public string Content { get; set; } - - /// - /// Role of Message ... - /// - public XAiChatRole Role { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - - /// - /// Conversation Id ... - /// - public Guid ConversationId { get; set; } - - /// - /// Conversation Info ... - /// - public virtual string ConversationTitle { get; set; } = null; - public virtual XResourceDto ConversationTitleResouce { get; set; } = null; - - // - #region Meta Data Property ... - private string _metadata; - - /// - /// Meta Data of Message ... - /// - [NotMapped] - public IDictionary Metadata { get; private set; } = null; - - /// - /// Meta Data of MEssage in Json ... - /// - public string MetaDatas - { - // - get => _metadata; - - // - set - { - // - // Converts Json String to Dictionary ... - if (!value.IsNullOrEmpty()) - { - Metadata = value.FromJSON>(); - } - - // - _metadata = value; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiProjectDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using System.Collections.Generic; - -namespace xAiModels.Models.Dtos -{ - /// - /// Describe a Project ... - /// - public class XAiProjectDto : XBaseGuidIDEntityDto - { - /// - /// User Identifier ... - /// - /// - public string OwnerId { get; set; } - - /// - /// Owner Info ... - /// - public virtual XPersonDto Owner { get; set; } = null; - - /// - /// Title of Project ... - /// - public string Title { get; set; } - - /// - /// All Exists Title Locale Resources ... - /// - public virtual XResourceDto TitleResource { get; set; } - - /// - /// Description of Project ... - /// - public string Description { get; set; } - - /// - /// All Exists Description Locale Resources ... - /// - public virtual XResourceDto DescriptionResource { get; set; } - - /// - /// a Prompt for Project Start ... - /// - public string Prompt { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - - /// - /// Conversations ... - /// - public virtual IList Conversations { get; set; } = []; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorDto.cs - -using System; -using xModels.Base; -using System.Collections.Generic; - -namespace xAiModels.Models.Dtos -{ - /// - /// Vector DTO for AI Vector data ... - /// - public class XAiVectorDto : XBaseGuidIDEntityDto - { - /// - /// Text content of the vector ... - /// - public string Text { get; set; } - - /// - /// Doc and Chunk Identifier ... - /// - public string Identifier { get; set; } - - /// - /// Knowledge Base Type / Domain (Optional Filter on Search) ... - /// - public string Type { get; set; } - - /// - /// Embedding vector representation ... - /// - public virtual ReadOnlyMemory Embedding { get; set; } = null; - - /// - /// Metadata associated with the vector ... - /// - public virtual Dictionary Metadata { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiVectorSearchResult.cs - -using System; -using System.Collections.Generic; - -namespace xAiModels.Models.Dtos -{ - public class XAiVectorSearchResult - { - public Guid Id { get; set; } - public string Text { get; set; } - public float Score { get; set; } - public string Type { get; set; } - public string Identifier { get; set; } - public Dictionary Metadata { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiConversation.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xAiModels.Models.Entities -{ - /// - /// Conversation Describe ... - /// - public class XAiConversation : XBaseGuidIDEntity - { - /// - /// User Identifier ... - /// - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Title of Conversation ... - /// - [Required] - [StringLength(255)] - public string Title { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - - /// - /// Project ID ... - /// - [Required] - public Guid ProjectId { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMcpServer.cs - -using System; -using xModels.Base; -using xAiModels.Constants; -using System.ComponentModel.DataAnnotations; - -namespace xAiModels.Models.Entities -{ - /// - /// An MCP Server Descriptor for Adding Tools to XAI ... - /// - public class XAiMcpServer : XBaseGuidIDEntity - { - /// - /// Owner ... - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Specified Which Scope can Use MCP Server ... - /// - public XAiMcpServerUsageScope Scope { get; set; } = XAiMcpServerUsageScope.Owner; - - /// - /// MCP Server Name ... - /// - [Required] - [StringLength(255)] - public string Name { get; set; } - - /// - /// Description ... - /// - [StringLength(1000)] - public string Description { get; set; } - - /// - /// Enabled or Disabled ... - /// - public bool Enabled { get; set; } = true; - - /// - /// Environment Variables as JSON Object ... - /// - public string EnvironmentVariables { get; set; } - - /// - /// Endpoint to Connect ... - /// - [StringLength(1000)] - public string Endpoint { get; set; } - - /// - /// Headers List as Json Object ... - /// - public string Headers { get; set; } - - /// - /// Timout Secconds ... - /// - public int TimeoutSeconds { get; set; } = 30; - - public DateTime CreatedOn { get; set; } - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMessage.cs - -using System; -using xModels.Base; -using xAiModels.Constants; -using xCommons.Extensions; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xAiModels.Models.Entities -{ - /// - /// Message Model of Ai ... - /// - public class XAiMessage : XBaseGuidIDEntity - { - /// - /// User Identifier ... - /// - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Message of Chat ... - /// - [Required] - public string Content { get; set; } - - /// - /// Role of Message ... - /// - public XAiChatRole Role { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - - /// - /// Conversation Id ... - /// - [StringLength(255)] - public Guid ConversationId { get; set; } - - // - #region Meta Data Property ... - private string _metadata; - - /// - /// Meta Data of Message ... - /// - [NotMapped] - public IDictionary Metadata { get; private set; } = null; - - /// - /// Meta Data of MEssage in Json ... - /// - public string MetaDatas - { - // - get => _metadata; - - // - set - { - // - // Converts Json String to Dictionary ... - if (!value.IsNullOrEmpty()) - { - Metadata = value.FromJSON>(); - } - - // - _metadata = value; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiProject.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xAiModels.Models.Entities -{ - /// - /// Describe a Project ... - /// - public class XAiProject : XBaseGuidIDEntity - { - /// - /// User Identifier ... - /// - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Title of Project ... - /// - [Required] - [StringLength(255)] - public string Title { get; set; } - - /// - /// Description of Project ... - /// - [StringLength(1000)] - public string Description { get; set; } - - /// - /// a Prompt for Project Start ... - /// - public string Prompt { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiVector.cs - -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xAiModels.Models.Entities -{ - public class XAiVector : XBaseGuidIDEntity - { - /// - /// Thge Content Which Embedded ... - /// - public string Text { get; set; } - - /// - /// Doc and Chunk Identifier ... - /// - public string Identifier { get; set; } - - /// - /// Knowledge Base Type / Domain (e.g. "Legal", "Medical") ... - /// Used for Filtering on Search and Retrieve ... - /// - [StringLength(100)] - public string Type { get; set; } - - /// - /// a Json String which Represents IReadOnlyList of float ... - /// - public string Embedding { get; set; } - - /// - /// a Json String Which Represents MetaData ... - /// - public string Metadata { get; set; } = string.Empty; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xAiModels.Configurations.Entities; - -namespace xAiModels.Providers -{ - public class XAiConversationEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XAiConversationEntityRegisterar() - : base(nameof(XAiConversationEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XAiConversationEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiConversationTitleResourceProvider.cs - -using xAiModels.Constants; -using xAiModels.Interfaces; -using xCommons.Configurations; -using xStringService.Providers; -using xStringService.Interfaces.Dtos; - -namespace xAiModels.Providers -{ - public class XAiConversationTitleResourceProvider : XBaseOwnedItemResourceProvider, IXAiConversationTitleResourceProvider - { - public XAiConversationTitleResourceProvider( - XAppConfiguration appConfig, - IXStringServiceProvider stringProvider - ) : base( - appConfig: appConfig, - stringProvider: stringProvider, - item: XAiModelsConstants.XAiConversationTitleIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiDataProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xAiModels.Helpers; -using xAiModels.Constants; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using System.Linq.Expressions; -using xDataService.Extensions; -using xAiModels.Providers.Hubs; -using xAiModels.Interfaces.Dtos; -using xStringService.Interfaces; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers -{ - /// - /// All Data Manipulation Requirements ... - /// - public class XAiDataProvider : IXAiDataProvider - { - // - #region Properties ... - private readonly IXStringProvider stringProvider; - private readonly IXAiVectorEnricher vectorEnricher; - private readonly XAppConfiguration appConfiguration; - private readonly IHubContext hub; - private readonly IXAiMessageEnricher messageEnricher; - private readonly IXAiProjectEnricher projectEnricher; - private readonly IXAiVectorRepository vectorRepository; - private readonly IXAiMcpServerEnricher mcpServerEnricher; - private readonly IXAiMcpServerRepository mcpServerRepository; - private readonly IXAiConversationEnricher conversationEnricher; - private readonly IXAiVectorRepositoryService vectorRepositoryService; - private readonly IXAiMessageRepositoryService messageRepositoryService; - private readonly IXAiProjectRepositoryService projectRepositoryService; - private readonly IXAiMcpServerRepositoryService mcpServerRepositoryService; - private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; - private readonly IXAiConversationRepositoryService conversationRepositoryService; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; - #endregion - - public XAiDataProvider( - IXStringProvider stringProvider, - IXAiVectorEnricher vectorEnricher, - XAppConfiguration appConfiguration, - IHubContext hub, - IXAiProjectEnricher projectEnricher, - IXAiMessageEnricher messageEnricher, - IXAiVectorRepository vectorRepository, - IXAiMcpServerEnricher mcpServerEnricher, - IXAiMcpServerRepository mcpServerRepository, - IXAiConversationEnricher conversationEnricher, - IXAiVectorRepositoryService vectorRepositoryService, - IXAiMessageRepositoryService messageRepositoryService, - IXAiProjectRepositoryService projectRepositoryService, - IXAiMcpServerRepositoryService mcpServerRepositoryService, - IXAiProjectTitleResourceProvider projectTitleResourceProvider, - IXAiConversationRepositoryService conversationRepositoryService, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider, - IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider - ) - { - this.hub = hub; - this.stringProvider = stringProvider; - this.vectorEnricher = vectorEnricher; - this.projectEnricher = projectEnricher; - this.messageEnricher = messageEnricher; - this.appConfiguration = appConfiguration; - this.vectorRepository = vectorRepository; - this.mcpServerEnricher = mcpServerEnricher; - this.mcpServerRepository = mcpServerRepository; - this.conversationEnricher = conversationEnricher; - this.vectorRepositoryService = vectorRepositoryService; - this.messageRepositoryService = messageRepositoryService; - this.projectRepositoryService = projectRepositoryService; - this.mcpServerRepositoryService = mcpServerRepositoryService; - this.projectTitleResourceProvider = projectTitleResourceProvider; - this.conversationRepositoryService = conversationRepositoryService; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; - } - - // - #region Loaders ... - /// - /// Load Projects List of Specified Owner ... - /// - /// - /// - /// - /// - /// - /// - public async Task> LoadProjects( - string ownerId, - string connectionId = null, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Handle Default Project and Conversation ... - - // - // Default Project ... - bool hasDefault = await HasDefaultProject( - ownerId: ownerId, - cancellationToken: cancellationToken - ); - if (!hasDefault) - { - // - await CreateDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - var defaultProject = await GetDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Default Project's Default Conversation ... - hasDefault = await HasDefaultConversation( - ownerId: ownerId, - projectId: defaultProject.Id, - cancellationToken: cancellationToken - ); - if (!hasDefault) - { - // - await CreateDefaultConversation( - ownerId: ownerId, - connectionId: connectionId, - projectId: defaultProject.Id, - cancellationToken: cancellationToken - ); - } - - // - // Retrieve Project List ... - var result = await projectRepositoryService.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: x => x.OwnerId == ownerId, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - if (result.HasChild()) - { - // - result = await projectEnricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken, - fillConversations: fillConversations, - fillConversationMessages: fillConversationMessages - ); - } - - // - return result; - } - - /// - /// Load List of Conversations for Specified Project ... - /// - /// - /// - /// - /// - /// - public async Task> LoadConversations( - Guid projectId, - bool fillMessages = false, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (projectId.IsNull() || - projectId.IsDefaultGuid() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Project ... - var project = await projectRepositoryService.GetAsync( - id: projectId, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Default Conversation ... - var hasDefault = await HasDefaultConversation( - projectId: projectId, - ownerId: project.OwnerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!hasDefault) - { - // - await CreateDefaultConversation( - projectId: projectId, - ownerId: project.OwnerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - // Retrieve Conversation's List ... - var result = await conversationRepositoryService.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.ProjectId == projectId, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - if (result.HasChild()) - { - // - result = await conversationEnricher.EnrichRange( - sources: result, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Load Messages of Specified Conversation ... - /// - /// - /// - /// - public async Task> LoadMessages( - Guid conversationId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (conversationId.IsNull() || - conversationId.IsDefaultGuid() - ) - { - XException.InvalidArgs.Throw(); - } - - // - var conversation = await conversationRepositoryService.GetAsync( - id: conversationId, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Retrieve Message Lists of Specified Conversation ... - var result = await messageRepositoryService.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn), - predicate: x => x.ConversationId == conversationId - ); - - // - if (result.HasChild()) - { - // - result = await messageEnricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - #endregion - - // - #region Getters ... - /// - /// Retrieve Specified Project ... - /// - /// - /// - /// - /// - /// - public async Task GetProject( - Guid id, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await projectRepositoryService.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Handle Enrichment ... - result = await projectEnricher.Enrich( - source: result, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages - ); - - // - return result; - } - - /// - /// Retrieve Specified Conversation ... - /// - /// - /// - /// - /// - public async Task GetConversation( - Guid id, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await conversationRepositoryService.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Handle Enrichment ... - result = await conversationEnricher.Enrich( - source: result, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Creator/Adders ... - /// - /// Create Project ... - /// - /// - /// - /// - /// - /// - public async Task CreateProject( - string ownerId, - XAiProjectDto item = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Project Provided or not ... - var hasProject = !item.IsNullOrDefault(); - - // - // Normalize Provided Project ... - if (hasProject) - { - // - item.OwnerId = ownerId; - item.CreatedOn = DateTime.UtcNow; - - // - // Validate Item ... - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidData.Throw(); - } - } - - // - XAiProjectDto result = null; - var defaultLanguage = appConfiguration.DefaultLanguage; - - // - // Create Provided Project ... - if (hasProject) - { - // - // Add Item for ID Gneneration ... - result = await projectRepositoryService.AddAsync( - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Checking Resources ... - - // - // Titles ... - var titleResource = string.Empty; - if (!item.TitleResource.IsNullOrDefault() && - item.TitleResource.Locales.HasChild()) - { - // - // Adding Title Resource Locales ... - var isDefaultLanguageHandled = false; - foreach (var trl in item.TitleResource.Locales) - { - // - // Attaching Default Language ... - if (!isDefaultLanguageHandled && - trl.Language.IsNullOrEmpty()) - { - // - trl.Language = defaultLanguage; - isDefaultLanguageHandled = true; - } - - // - // Check Value Exists ... - if (trl.Value.IsNullOrEmpty()) - { - continue; - } - - // - var resource = await projectTitleResourceProvider.AddOrUpdateLocale( - locale: trl, - owner: ownerId, - identifier: result.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!resource.IsNullOrDefault() && - titleResource.IsNullOrEmpty()) - { - titleResource = resource.Resource; - } - } - } - - // - // Descriptions ... - var descriptionResource = string.Empty; - if (!item.DescriptionResource.IsNullOrDefault() && - item.DescriptionResource.Locales.HasChild()) - { - // - // Adding Description Resource Locales .... - var isDefaultLanguageHandled = false; - foreach (var trl in item.DescriptionResource.Locales) - { - // - // Attaching Default Language ... - if (!isDefaultLanguageHandled && - trl.Language.IsNullOrEmpty()) - { - // - trl.Language = defaultLanguage; - isDefaultLanguageHandled = true; - } - - // - // Check Value Exists ... - if (trl.Value.IsNullOrEmpty()) - { - continue; - } - - // - var resource = await projectDescriptionResourceProvider.AddOrUpdateLocale( - locale: trl, - owner: ownerId, - identifier: result.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!resource.IsNullOrDefault() && - descriptionResource.IsNullOrEmpty()) - { - descriptionResource = resource.Resource; - } - } - } - - // - // Update Data ... - result.Title = titleResource; - result.Description = descriptionResource; - result = await projectRepositoryService.UpdateAsync( - item: result, - id: result.Id, - saveChanges: true, - cancellationToken: cancellationToken - ); - if (!result.IsNullOrDefault()) - { - // - result = await projectEnricher.Enrich( - source: result, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - } - - // - // Handling Send Push Notification ... - if (!result.IsNullOrDefault() && - !connectionId.IsNullOrEmpty() - ) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: item.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.ProjectCreated.GetStringValue() - ); - } - } - // - // Check Default Project ... - else - { - // - // Check Default Project Exists or not ... - var hasDefault = await HasDefaultProject( - ownerId: ownerId, - cancellationToken: cancellationToken - ); - - // - // If Default Project Exists, Throw Exception ... - if (hasDefault) - { - XException.InvalidArgs.Throw(); - } - - // - // Create and Retrive Default Project ... - result = await GetDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - // Validate ... - if (result.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - // Handle Enrichment ... - result = await Enrich( - source: result, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Create an AI Conversation ... - /// - /// - /// - /// - /// - /// - /// - public async Task CreateConversation( - string ownerId, - Guid projectId, - XAiConversationDto item = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (projectId.IsNull() || - projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Handle Proejct ... - XAiProjectDto project = await projectRepositoryService.GetAsync( - id: projectId, - includeBuilder: null, - ignoreSoftDeleteds: true, - // fillConversations: false, - // fillConversationMessages: false, - cancellationToken: cancellationToken - ); - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check Conversation Provided or not ... - var hasConversation = !item.IsNullOrDefault(); - - // - // Normalize Conversation if Provided ... - if (hasConversation) - { - // - item.OwnerId = ownerId; - item.ProjectId = project.Id; - item.CreatedOn = DateTime.UtcNow; - - // - // Validate Item ... - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidData.Throw(); - } - } - - // - XAiConversationDto result = null; - var defaultLanguage = appConfiguration.DefaultLanguage; - - // - // Create Provided Conversation ... - if (hasConversation) - { - // - // Add Item for ID Gneneration ... - result = await conversationRepositoryService.AddAsync( - item: item, - saveChanges: true, - // fillMessages: false, - cancellationToken: cancellationToken - ); - - // - // Checking Resources ... - - // - // Titles ... - var titleResource = string.Empty; - if (!item.TitleResource.IsNullOrDefault() && - item.TitleResource.Locales.HasChild()) - { - // - // Adding Title Resource Locales ... - var isDefaultLanguageHandled = false; - foreach (var trl in item.TitleResource.Locales) - { - // - // Attaching Default Language ... - if (!isDefaultLanguageHandled && - trl.Language.IsNullOrEmpty()) - { - // - trl.Language = defaultLanguage; - isDefaultLanguageHandled = true; - } - - // - // Check Value Exists ... - if (trl.Value.IsNullOrEmpty()) - { - continue; - } - - // - var resource = await conversationTitleResourceProvider.AddOrUpdateLocale( - locale: trl, - owner: ownerId, - identifier: result.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!resource.IsNullOrDefault() && - titleResource.IsNullOrEmpty()) - { - titleResource = resource.Resource; - } - } - } - - // - // Update Data ... - result.Title = titleResource; - result = await conversationRepositoryService.UpdateAsync( - item: result, - id: result.Id, - saveChanges: true, - cancellationToken: cancellationToken - ); - if (!result.IsNullOrDefault()) - { - // - result = await conversationEnricher.Enrich( - source: result, - fillMessages: false, - cancellationToken: cancellationToken - ); - } - - // - // Handling Send Push Notification ... - if (!result.IsNullOrDefault() && - !connectionId.IsNullOrEmpty() - ) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: item.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.ConversationCreated.GetStringValue() - ); - } - } - // - // Check Default Conversation ... - else - { - // - // Check Default Conversation Exists or not ... - var hasDefault = await HasDefaultConversation( - projectId: project.Id, - ownerId: project.OwnerId, - cancellationToken: cancellationToken - ); - - // - // If Default Project Exists, Throw Exception ... - if (hasDefault) - { - XException.InvalidArgs.Throw(); - } - - // - // Create and Retrive Default Conversation ... - result = await GetDefaultConversation( - projectId: project.Id, - ownerId: project.OwnerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - // Validate ... - if (result.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - // Handle Enrichment ... - result = await Enrich( - source: result, - fillMessages: false, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add Message ... - /// - /// - /// - /// - /// - /// - public async Task AddMessage( - Guid conversationId, - XAiMessageDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (item.IsNullOrDefault() || - conversationId.IsNull() || - conversationId.IsDefaultGuid() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - item.CreatedOn = DateTime.UtcNow; - item.ConversationId = conversationId; - - // - // Validate Item ... - if (!item.IsValidForAddOrUpdate()) - { - XException.InvalidData.Throw(); - } - - // - var result = await messageRepositoryService.AddAsync( - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (!result.IsNullOrDefault()) - { - // - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - // Handling Send Push Notification ... - if (!result.IsNullOrDefault() && - !connectionId.IsNullOrEmpty() - ) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: item.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.MessageCreated.GetStringValue() - ); - } - - // - return result; - } - #endregion - - // - #region Updaters ... - #endregion - - // - #region Defaults ... - /// - /// Retrieve Default Project of Specified Owner ... - /// Create it if not Handled ... - /// - /// - /// - /// - /// - public async Task GetDefaultProject( - string ownerId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Default Project Exists or noit ... - var isExists = await HasDefaultProject( - ownerId: ownerId, - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - await CreateDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - var resource = await stringProvider.FindOne( - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.ResourceTitle - .ToNormalString() - .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) && - x.TranslatedValue - .ToNormalString() - .Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString()) - ); - if (resource.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await projectRepositoryService.FindOneAsync( - cancellationToken: cancellationToken, - predicate: x => x.Title - .Equals( - resource.ResourceTitle, - StringComparison.InvariantCultureIgnoreCase - ) - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - - /// - /// Retrieve Default Conversation of Specified Owner ... - /// Create it if not Handled ... - /// - /// - /// - /// - /// - /// - public async Task GetDefaultConversation( - string ownerId, - Guid? projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Project ... - XAiProjectDto project = null; - if (!projectId.HasValue || - projectId.Value.IsDefaultGuid() - ) - { - // - project = await GetDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - project = await projectRepositoryService.GetAsync( - id: projectId.Value, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - } - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check Default Conversation Exists or noit ... - var isExists = await HasDefaultConversation( - ownerId: ownerId, - projectId: project.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - await CreateDefaultConversation( - ownerId: ownerId, - projectId: project.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - // Check Default Owner Exists or not ... - var resource = await stringProvider.FindOne( - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle - .ToNormalString() - .Contains(ownerId.ToString().ToNormalString()) && - x.ResourceTitle - .ToNormalString() - .Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) && - x.TranslatedValue - .ToNormalString() - .Contains(XAiDataProviderConstants.XDefaultAiConversationSuffix.ToNormalString()) - ); - if (resource.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await conversationRepositoryService.FindOneAsync( - cancellationToken: cancellationToken, - predicate: x => - x.ProjectId == project.Id && - x.Title == resource.ResourceTitle - ); - - // - return result; - } - #endregion - - // - #region Query ... - /// - /// Query Projects ... - /// - /// - /// - /// - /// - public async Task> QueryProjects( - string ownerId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicate = null; - if (!ownerId.IsNullOrEmpty()) - { - predicate = x => x.OwnerId == ownerId; - } - - // - var result = await projectRepositoryService.QueryAsync( - query: query, - predicate: predicate, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - if (!result.IsNullOrDefault() && - result.Items.HasChild()) - { - // - result.Items = [..await EnrichRange( - sources: result.Items, - fillConversations: false, - fillConversationMessages: false, - cancellationToken: cancellationToken - )]; - } - - // - return result; - } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - public async Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Conversation ... - var conversation = await conversationRepositoryService.GetAsync( - id: conversationId, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - Expression> predicate = x => - x.ConversationId == conversationId; - if (!ownerId.IsNullOrEmpty()) - { - // - predicate = x => - x.OwnerId == ownerId && - x.ConversationId == conversationId; - } - - // - var result = await messageRepositoryService.QueryAsync( - query: query, - predicate: predicate, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - if (!result.IsNullOrDefault() && - result.Items.HasChild()) - { - // - result.Items = [..await EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - )]; - } - - // - return result; - } - - /// - /// Query McpServers ... - /// - /// - /// - /// - /// - public async Task> QueryMcpServers( - XQuery query, - Expression> predicate = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await mcpServerRepositoryService.QueryAsync( - query: query, - predicate: predicate, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - if (!result.IsNullOrDefault() && - result.Items.HasChild()) - { - // - result.Items = [..await EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - )]; - } - - // - return result; - } - - /// - /// Query Conversations ... - /// - /// - /// - /// - /// - /// - public async Task> QueryConversations( - string ownerId, - Guid projectId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (projectId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Project ... - var project = await projectRepositoryService.GetAsync( - id: projectId, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - Expression> predicate = x => - x.ProjectId == projectId; - if (!ownerId.IsNullOrEmpty()) - { - // - predicate = x => - x.OwnerId == ownerId && - x.ProjectId == projectId; - } - - // - var result = await conversationRepositoryService.QueryAsync( - query: query, - predicate: predicate, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - if (!result.IsNullOrDefault() && - result.Items.HasChild()) - { - // - result.Items = [..await EnrichRange( - fillMessages: false, - sources: result.Items, - cancellationToken: cancellationToken - )]; - } - - // - return result; - } - #endregion - - // - #region Vectors ... - /// - /// Insert or Update a Single Vector (Matched by Identifier) ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task UpsertVectorAsync( - string identifier, - string text, - ReadOnlyMemory embedding, - Dictionary metadata = null, - string type = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - embedding.IsEmpty || - text.IsNullOrEmpty() || - identifier.IsNullOrEmpty() - ) - { - XException.InvalidArgs.Throw(); - } - - // - var exists = await vectorRepository.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.Identifier == identifier - ); - var isExists = !exists.IsNullOrDefault(); - if (isExists) - { - // - exists.Text = text; - exists.Embedding = embedding.ToJSON(); - exists.Type = type.IsNullOrEmpty() ? exists.Type : type; - exists.Metadata = metadata.IsNullOrDefault() ? exists.Metadata : metadata.ToJSON(); - } - else - { - // - exists = new XAiVector - { - Text = text, - Type = type, - Identifier = identifier, - Metadata = metadata.ToJSON(), - Embedding = embedding.ToJSON(), - }; - } - - // - await vectorRepository.AddOrUpdateAsync( - item: exists, - saveChanges: true, - cancellationToken: cancellationToken - ); - } - - /// - /// Search Vectors by Cosine Similarity (Top K) ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> SearchVectorsAsync( - ReadOnlyMemory queryEmbedding, - int topK = 5, - float minScore = 0f, - string identifierPrefix = null, - string type = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - topK <= 0 || - queryEmbedding.IsEmpty - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (type.IsNullOrEmpty()) - { - type = XAiModelsConstants.XAiDefaultKnowledgeType; - } - - // - // Converts Question Vector to Vector Array ... - var queryVector = queryEmbedding.ToArray(); - var scoredResult = new List<(XAiVectorSearchResult Result, float Score)>(); - - // - // Load Candidates (Restricted by Prefix / Type when Provided) ... - var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type); - IAsyncEnumerable candidates; - if (predicateExp.IsNull()) - { - // - candidates = vectorRepository - .GetAllAsAsyncEnumerable( - ignoreSoftDeleteds: true, - orderBuilder: null, - includeBuilder: null - ); - } - else - { - // - candidates = (await vectorRepository - .FindManyAsync( - predicate: predicateExp, - ignoreSoftDeleteds: true, - orderBuilder: null, - includeBuilder: null, - cancellationToken: cancellationToken - )) - .ToAsyncEnumerable(); - } - - // - await foreach (var vector in candidates.WithCancellation(cancellationToken)) - { - // - // Validate Vector ... - if (vector.Embedding.IsNullOrEmpty()) - { - continue; - } - - // - // Ignore Unsame Vectors ... - var embd = vector.Embedding.AsEmbedding(); - if ( - embd.IsNull() || - embd.Length != queryEmbedding.Length - ) - { - continue; - } - - // - // Calculate Cosine Similarity Score ... - var score = VectorHelper.CosineSimilarity(queryVector, embd); - if (score < minScore) - { - continue; - } - - // - scoredResult.Add((new XAiVectorSearchResult - { - // - Score = score, - Id = vector.Id, - Text = vector.Text, - Type = vector.Type, - Identifier = vector.Identifier, - Metadata = vector.Metadata.AsMetadat(), - }, score)); - } - - // - var result = scoredResult - .OrderByDescending(x => x.Score) - .Take(topK) - .Select(x => x.Result) - .ToList(); - - // - return result; - } - - /// - /// Insert or Update a Batch of Vectors (Matched by Identifier) ... - /// - /// - /// - /// Count of Stored Vectors - public async Task UpsertVectorsAsync( - IEnumerable items, - CancellationToken cancellationToken = default - ) - { - // - // Validate & Normalize (Last One Wins on Duplicate Identifiers) ... - var validItems = (items ?? []) - .Where(x => - !x.IsNullOrDefault() && - !x.Embedding.IsEmpty && - !x.Text.IsNullOrEmpty() && - !x.Identifier.IsNullOrEmpty() - ) - .GroupBy(x => x.Identifier) - .Select(g => g.Last()) - .ToList(); - if (!validItems.HasChild()) - { - return 0; - } - - // - // Load Existing Vectors with Same Identifiers ... - var identifiers = validItems - .Select(x => x.Identifier) - .ToList(); - var existings = await vectorRepository.FindManyAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => identifiers.Contains(x.Identifier) - ); - var existingMap = (existings ?? []) - .GroupBy(x => x.Identifier) - .ToDictionary(g => g.Key, g => g.First()); - - // - // Split to Insert / Update ... - var toAdd = new List(); - var toUpdate = new List(); - foreach (var item in validItems) - { - // - if (existingMap.TryGetValue(item.Identifier, out var exists)) - { - // - exists.Text = item.Text; - exists.Embedding = item.Embedding.ToEmbedding(); - exists.Type = item.Type.IsNullOrEmpty() ? exists.Type : item.Type; - exists.Metadata = item.Metadata.IsNullOrDefault() ? exists.Metadata : item.Metadata.ToJSON(); - toUpdate.Add(exists); - } - else - { - // - toAdd.Add(new XAiVector - { - Text = item.Text, - Type = item.Type, - Identifier = item.Identifier, - Metadata = item.Metadata.ToJSON(), - Embedding = item.Embedding.ToEmbedding(), - Id = item.Id.IsDefaultGuid() ? Guid.NewGuid() : item.Id, - }); - } - } - - // - if (toUpdate.HasChild()) - { - await vectorRepository.UpdateRangeAsync( - items: toUpdate, - saveChanges: false, - cancellationToken: cancellationToken - ); - } - if (toAdd.HasChild()) - { - await vectorRepository.AddRangeAsync( - items: toAdd, - saveChanges: false, - cancellationToken: cancellationToken - ); - } - - // - await vectorRepository.SaveChangesAsync(cancellationToken); - - // - var result = toAdd.Count + toUpdate.Count; - return result; - } - - /// - /// Load Vectors whose Identifier Starts with Specified Prefix ... - /// - /// - /// - /// - /// - /// - public async Task> LoadVectorsAsync( - string identifierPrefix, - bool includeEmbedding = false, - string type = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (identifierPrefix.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var vectors = await vectorRepository.FindManyAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: BuildVectorPredicateExpression(identifierPrefix, type) - ); - - // - var result = (vectors ?? []) - .Select(v => new XAiVectorDto - { - Id = v.Id, - Text = v.Text, - Type = v.Type, - Identifier = v.Identifier, - Metadata = v.Metadata.AsMetadat(), - Embedding = includeEmbedding ? v.Embedding.AsEmbedding() : null, - }) - .ToList(); - - // - return result; - } - - /// - /// Remove Vectors whose Identifier Starts with Specified Prefix ... - /// - /// - /// - /// - /// Count of Removed Vectors - public async Task RemoveVectorsAsync( - string identifierPrefix, - string type = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (identifierPrefix.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var vectors = await vectorRepository.FindManyAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: BuildVectorPredicateExpression(identifierPrefix, type) - ); - var toRemove = (vectors ?? []).ToList(); - if (!toRemove.HasChild()) - { - return 0; - } - - // - // Hard Delete (Vectors are Disposable Data) ... - await vectorRepository.RemoveRangeAsync( - items: toRemove, - softDelete: false, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - var result = toRemove.Count; - return result; - } - #endregion - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XAiVectorDto source, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.Enrich( - source: source, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XAiVector source, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.Enrich( - source: source, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ) - { - // - var result = await messageEnricher.Enrich( - source: source, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await projectEnricher.Enrich( - source: source, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XAiMcpServerDto source, - CancellationToken cancellationToken = default - ) - { - // - var result = await mcpServerEnricher.Enrich( - source: source, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - public async Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await conversationEnricher.Enrich( - source: source, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.EnrichRange( - sources: sources, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.EnrichRange( - sources: sources, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await projectEnricher.EnrichRange( - sources: sources, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var result = await messageEnricher.EnrichRange( - sources: sources, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var result = await mcpServerEnricher.EnrichRange( - sources: sources, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await conversationEnricher.EnrichRange( - sources: sources, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Private ... - /// - /// Check Default Project Exists or not ... - /// - /// - /// - /// - private async Task HasDefaultProject( - string ownerId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var result = !ownerId.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - // Check Default Owner Exists or not ... - var defaultProjectResource = await stringProvider.FindOne( - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle - .ToNormalString() - .Contains(ownerId.ToNormalString()) && - x.ResourceTitle - .ToNormalString() - .Contains(XAiModelsConstants.XAiProjectTitleIdentifier.ToNormalString()) && - x.TranslatedValue - .ToNormalString() - .Contains(XAiDataProviderConstants.XDefaultAiProjectSuffix.ToNormalString()) - ); - result = !defaultProjectResource.IsNullOrDefault(); - - // - return result; - } - - /// - /// Create Default Project for Specified Owner ... - /// - /// - /// - /// - /// - private async Task CreateDefaultProject( - string ownerId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - if (ownerId.IsNullOrEmpty()) - { - return; - } - - // - var defaultLang = appConfiguration.DefaultLanguage; - - // - // Check Default Owner Exists or not ... - var isExists = await HasDefaultProject( - ownerId: ownerId, - cancellationToken: cancellationToken - ); - if (isExists) - { - return; - } - - // - // Create Default ... - var item = new XAiProjectDto() - { - OwnerId = ownerId, - CreatedOn = DateTime.UtcNow, - Title = Guid.NewGuid().ToString(), - Description = Guid.NewGuid().ToString(), - }; - item = await projectRepositoryService.AddAsync( - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Prepare Tile and Description Resource Ids ... - var titleResource = await projectTitleResourceProvider.AddOrUpdateLocale( - owner: ownerId, - identifier: item.Id, - locale: new XLocaleResourceDto - { - Language = defaultLang, - Value = XAiDataProviderConstants.XDefaultAiProjectSuffix - }, - cancellationToken: cancellationToken - ); - var descriptionResource = await projectDescriptionResourceProvider.AddOrUpdateLocale( - owner: ownerId, - identifier: item.Id, - new XLocaleResourceDto - { - Language = defaultLang, - Value = XAiDataProviderConstants.XDefaultAiProjectSuffix - }, - cancellationToken: cancellationToken - ); - if (titleResource.IsNullOrDefault() || - descriptionResource.IsNullOrDefault() - ) - { - return; - } - - // - // Update Project Resources ... - item.Title = titleResource.Resource; - item.Description = descriptionResource.Resource; - item = await projectRepositoryService.UpdateAsync( - id: item.Id, - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Sending Push ... - if (!connectionId.IsNullOrEmpty()) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: item.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.ProjectCreated.GetStringValue() - ); - } - } - - /// - /// Check Default Conversation Exists or not ... - /// - /// - /// - /// - /// - /// - private async Task HasDefaultConversation( - string ownerId, - Guid? projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var result = !ownerId.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - // Prepare Project ... - XAiProjectDto project = null; - if (!projectId.HasValue || - projectId.Value.IsDefaultGuid() - ) - { - // - project = await GetDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - project = await projectRepositoryService.GetAsync( - id: projectId.Value, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - } - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check Default Owner Exists or not ... - var resource = await stringProvider.FindOne( - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle - .ToNormalString() - .Contains(ownerId.ToString().ToNormalString()) && - x.ResourceTitle - .ToNormalString() - .Contains(XAiModelsConstants.XAiConversationTitleIdentifier.ToNormalString()) && - x.TranslatedValue - .ToNormalString() - .Contains(XAiDataProviderConstants.XDefaultAiConversationSuffix.ToNormalString()) - ); - result = !resource.IsNullOrDefault(); - if (!result) - { - return result; - } - - // - var defaultConversation = await conversationRepositoryService.FindOneAsync( - cancellationToken: cancellationToken, - predicate: x => - x.ProjectId == project.Id && - x.Title == resource.ResourceTitle - ); - result = !defaultConversation.IsNullOrDefault(); - - // - return result; - } - - /// - /// Check Default Conversation Exists or not ... - /// - /// - /// - /// - /// - /// - private async Task CreateDefaultConversation( - string ownerId, - Guid? projectId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !ownerId.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var defaultLang = appConfiguration.DefaultLanguage; - - // - // Prepare Project ... - XAiProjectDto project = null; - if (!projectId.HasValue || - projectId.Value.IsDefaultGuid() - ) - { - // - project = await GetDefaultProject( - ownerId: ownerId, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - project = await projectRepositoryService.GetAsync( - id: projectId.Value, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - } - if (project.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check Default Owner Exists or not ... - isValid = await HasDefaultConversation( - ownerId: ownerId, - projectId: project.Id, - cancellationToken: cancellationToken - ); - if (isValid) - { - return; - } - - // - // Create Default Conversation ... - var item = new XAiConversationDto - { - OwnerId = ownerId, - ProjectId = project.Id, - CreatedOn = DateTime.UtcNow, - Title = Guid.NewGuid().ToString() - }; - item = await conversationRepositoryService.AddAsync( - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Prepare Title Resource Ids ... - var titleResource = await conversationTitleResourceProvider.AddOrUpdateLocale( - owner: ownerId, - identifier: item.Id, - locale: new XLocaleResourceDto - { - Language = defaultLang, - Value = XAiDataProviderConstants.XDefaultAiConversationSuffix - }, - cancellationToken: cancellationToken - ); - if (titleResource.IsNullOrDefault()) - { - return; - } - - // - // Update Conversation Resources ... - item.Title = titleResource.Resource; - item = await conversationRepositoryService.UpdateAsync( - item: item, - id: item.Id, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - // Sending Push ... - if (!connectionId.IsNullOrEmpty()) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: item.ToJSON(camelCase: true), - action: XAiDataProviderHubActions.ConversationCreated.GetStringValue() - ); - } - } - - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - public async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Collect Allowed Actions ... - var actions = new List - { - XAiDataProviderHubActions.ProjectCreated.GetStringValue(), - XAiDataProviderHubActions.ProjectUpdated.GetStringValue(), - XAiDataProviderHubActions.ProjectRemoved.GetStringValue(), - XAiDataProviderHubActions.MessageCreated.GetStringValue(), - XAiDataProviderHubActions.MessageUpdated.GetStringValue(), - XAiDataProviderHubActions.MessageRemoved.GetStringValue(), - XAiDataProviderHubActions.ConversationCreated.GetStringValue(), - XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), - XAiDataProviderHubActions.ConversationRemoved.GetStringValue(), - }; - - // - // Validate Args ... - var isValid = - !action.IsNullOrEmpty() && - actions.Contains(action); - if (!isValid) - { - return; - } - - // - // Retrieve Connection Id ... - var clients = hub.Clients.All; - if (!connectionId.IsNullOrEmpty()) - { - clients = hub.Clients.AllExcept(connectionId); - } - - // - await clients.SendAsync( - action, - payLoad, - connectionId, - cancellationToken - ); - } - catch { } - } - - /// - /// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ... - /// Returns null when no Filter Provided ... - /// - /// - /// - /// - private Expression> BuildVectorPredicateExpression( - string identifierPrefix, - string type - ) - { - // - Expression> result = null; - - // - var hasType = !type.IsNullOrEmpty(); - var hasPrefix = !identifierPrefix.IsNullOrEmpty(); - - // - if (hasPrefix && hasType) - { - // - result = x => x.Identifier - .StartsWith(identifierPrefix) && x.Type == type; - } - else if (hasPrefix) - { - // - result = x => x.Identifier - .StartsWith(identifierPrefix); - } - else if (hasType) - { - result = x => x.Type == type; - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xAiModels.Configurations.Entities; - -namespace xAiModels.Providers -{ - public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XAiMcpServerEntityRegisterar() - : base(nameof(XAiMcpServerEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xAiModels.Configurations.Entities; - -namespace xAiModels.Providers -{ - public class XAiMessageEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XAiMessageEntityRegisterar() - : base(nameof(XAiMessageEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XAiMessageEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectDescriptionResourceProvider.cs - -using xAiModels.Constants; -using xAiModels.Interfaces; -using xCommons.Configurations; -using xStringService.Providers; -using xStringService.Interfaces.Dtos; - -namespace xAiModels.Providers -{ - public class XAiProjectDescriptionResourceProvider : XBaseOwnedItemResourceProvider, IXAiProjectDescriptionResourceProvider - { - public XAiProjectDescriptionResourceProvider( - XAppConfiguration appConfig, - IXStringServiceProvider stringProvider - ) : base( - appConfig: appConfig, - stringProvider: stringProvider, - item: XAiModelsConstants.XAiProjectDescriptionIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xAiModels.Configurations.Entities; - -namespace xAiModels.Providers -{ - public class XAiProjectEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XAiProjectEntityRegisterar() - : base(nameof(XAiProjectEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XAiProjectEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiProjectTitleResourceProvider.cs - -using xAiModels.Constants; -using xAiModels.Interfaces; -using xCommons.Configurations; -using xStringService.Providers; -using xStringService.Interfaces.Dtos; - -namespace xAiModels.Providers -{ - public class XAiProjectTitleResourceProvider : XBaseOwnedItemResourceProvider, IXAiProjectTitleResourceProvider - { - public XAiProjectTitleResourceProvider( - XAppConfiguration appConfig, - IXStringServiceProvider stringProvider - ) : base( - appConfig: appConfig, - stringProvider: stringProvider, - item: XAiModelsConstants.XAiProjectTitleIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiVectorEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xAiModels.Configurations.Entities; - -namespace xAiModels.Providers -{ - public class XAiVectorEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XAiVectorEntityRegisterar() - : base(nameof(XAiVectorEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XAiVectorEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationDtoHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Dtos -{ - public class XAiConversationDtoHub : XBaseDtoHub, IXAiConversationDtoHub - { - public XAiConversationDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationRepositoryService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Providers; -using xAiModels.Configurations; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Dtos -{ - public class XAiConversationRepositoryService : XBaseRepositoryService, IXAiConversationRepositoryService - { - private readonly IXIdentityProvider identityProvider; - private readonly IXAiConversationRepository repository; - private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; - - public XAiConversationRepositoryService( - IXIdentityProvider identityProvider, - IXAiConversationRepository repository, - IXAiProjectTitleResourceProvider projectTitleResourceProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider, - IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider - ) : base( - repository, - mapperProfiles: - [ - new XAiModelMappersProfile() - ] - ) - { - this.repository = repository; - this.identityProvider = identityProvider; - this.projectTitleResourceProvider = projectTitleResourceProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiConversation source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = Mapper.Map(source); - result = await Enrich( - source: result, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Handdle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - // - // Try to Retrieve User Info ... - var device = identityProvider.GetDevice(); - var userInfo = await identityProvider.GetUserInfo( - device: device, - userSelectByParam: source.OwnerId - ); - owner = userInfo.ToXPersonDto(); - } - - // - // Handle Title Resource ... - XResourceDto titleResource = null; - if (!source.Title.IsNullOrEmpty()) - { - // - titleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Project Info ... - XResourceDto projectTitleResource = null; - XResourceDto projectDescriptionResource = null; - if (!source.ProjectId.IsDefaultGuid()) - { - // - projectTitleResource = await projectTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ProjectId, - cancellationToken: cancellationToken - ); - - // - projectDescriptionResource = await projectDescriptionResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ProjectId, - cancellationToken: cancellationToken - ); - } - - // - // Attach Extracted Items ... - var result = Mapper.Map(source, options => - { - // - options.Items[nameof(source.Owner)] = owner; - options.Items[nameof(source.TitleResource)] = titleResource; - options.Items[nameof(source.ProjectTitleResource)] = projectTitleResource; - options.Items[nameof(source.ProjectDescriptionResource)] = projectDescriptionResource; - }); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - fillMessages: fillMessages, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - fillMessages: fillMessages, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiConversationServiceProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xAiModels.Providers.Dtos -{ - public class XAiConversationServiceProvider : XBaseDtoProvider, IXAiConversationServiceProvider - { - public XAiConversationServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXAiConversationRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerDtoHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMcpServerDtoHub : XBaseDtoHub, IXAiMcpServerDtoHub - { - public XAiMcpServerDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerRepositoryService.cs - -using System; -using xAiModels.Models.Dtos; -using xDataService.Providers; -using xAiModels.Configurations; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMcpServerRepositoryService : XBaseRepositoryService, IXAiMcpServerRepositoryService - { - private readonly IXAiMcpServerEnricher enricher; - private readonly IXAiMcpServerRepository repository; - - public XAiMcpServerRepositoryService( - IXAiMcpServerRepository repository, - IXAiMcpServerEnricher enricher - ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()]) - { - this.enricher = enricher; - this.repository = repository; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerServiceProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMcpServerServiceProvider : XBaseDtoProvider, IXAiMcpServerServiceProvider - { - public XAiMcpServerServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXAiMcpServerRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base(hub, dataConfiguration, service, identityProvider) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageDtoHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMessageDtoHub : XBaseDtoHub, IXAiMessageDtoHub - { - public XAiMessageDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageRepositoryService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Providers; -using xAiModels.Configurations; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMessageRepositoryService : XBaseRepositoryService, IXAiMessageRepositoryService - { - private readonly IXIdentityProvider identityProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - - public XAiMessageRepositoryService( - IXAiMessageRepository repository, - IXIdentityProvider identityProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider - ) : base( - repository, - mapperProfiles: - [ - new XAiModelMappersProfile() - ] - ) - { - this.identityProvider = identityProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiMessage source, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = Mapper.Map(source); - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ) - { - // - // Handdle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - // - // Try to Retrieve User Info ... - var device = identityProvider.GetDevice(); - var userInfo = await identityProvider.GetUserInfo( - device: device, - userSelectByParam: source.OwnerId - ); - owner = userInfo.ToXPersonDto(); - } - - // - // Hanlde Conversation Title ... - string conversationTitle = string.Empty; - XResourceDto conversationTitleResource = null; - if (!source.ConversationId.IsDefaultGuid()) - { - // - conversationTitleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ConversationId, - cancellationToken: cancellationToken - ); - if (!conversationTitleResource.IsNullOrDefault()) - { - conversationTitle = conversationTitleResource.Resource; - } - } - - // - // Attach Extracted Items ... - var result = Mapper.Map(source, options => - { - // - options.Items[nameof(source.Owner)] = owner; - options.Items[nameof(source.ConversationTitle)] = conversationTitle; - options.Items[nameof(source.ConversationTitleResouce)] = conversationTitleResource; - }); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageServiceProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xAiModels.Providers.Dtos -{ - public class XAiMessageServiceProvider : XBaseDtoProvider, IXAiMessageServiceProvider - { - public XAiMessageServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXAiMessageRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectDtoHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Dtos -{ - public class XAiProjectDtoHub : XBaseDtoHub, IXAiProjectDtoHub - { - public XAiProjectDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectRepositoryService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xDataService.Providers; -using xAiModels.Configurations; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Dtos -{ - public class XAiProjectRepositoryService : XBaseRepositoryService, IXAiProjectRepositoryService - { - private readonly IXIdentityProvider identityProvider; - private readonly IXAiMessageRepository messageRepository; - private readonly IXAiConversationRepository conversationRepository; - private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; - - public XAiProjectRepositoryService( - IXAiProjectRepository repository, - IXIdentityProvider identityProvider, - IXAiMessageRepository messageRepository, - IXAiConversationRepository conversationRepository, - IXAiProjectTitleResourceProvider projectTitleResourceProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider, - IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider - ) : base( - repository, - mapperProfiles: - [ - new XAiModelMappersProfile() - ] - ) - { - // - this.identityProvider = identityProvider; - this.messageRepository = messageRepository; - this.conversationRepository = conversationRepository; - this.projectTitleResourceProvider = projectTitleResourceProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiProject source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = Mapper.Map(source); - result = await Enrich( - source: result, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Handle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - // - // Try to Retrieve User Info ... - var device = identityProvider.GetDevice(); - var userInfo = await identityProvider.GetUserInfo( - device: device, - userSelectByParam: source.OwnerId - ); - owner = userInfo.ToXPersonDto(); - } - - // - // Handle Title ... - XResourceDto titleResource = null; - if (!source.Title.IsNullOrEmpty()) - { - // - titleResource = await projectTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Description ... - XResourceDto descriptionResource = null; - if (!source.Description.IsNullOrEmpty()) - { - // - descriptionResource = await projectDescriptionResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Conversations ... - IEnumerable conversations = []; - if (fillConversations) - { - // - // Reading Entities ... - var entitiies = await conversationRepository.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.ProjectId == source.Id, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - // Converts to Dto Enumerable ... - conversations = entitiies - .MapConvert(); - - // - // Handle Conversation Enrichment ... - foreach (var conversation in conversations) - { - // - // Handle Owner ... - if (!conversation.OwnerId.IsNullOrEmpty()) - { - conversation.Owner = owner; - } - - // - // Handle Title Resource ... - if (!conversation.Title.IsNullOrEmpty()) - { - // - conversation.TitleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: conversation.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Project Info ... - if (!conversation.ProjectId.IsDefaultGuid()) - { - conversation.ProjectTitle = source.Title; - conversation.ProjectTitleResource = titleResource; - conversation.ProjectDescription = source.Description; - conversation.ProjectDescriptionResource = descriptionResource; - } - } - - // - // Handle Fill Messages ... - if (fillConversationMessages) - { - // - foreach (var conversation in conversations) - { - // - IEnumerable messages = []; - - // - // Retrieve Message Entities ... - var messageEntities = await messageRepository.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn), - predicate: x => x.ConversationId == conversation.Id - ); - if (messageEntities.HasChild()) - { - // - // Converts to Message ... - messages = messageEntities - .MapConvert(); - - // - // Ennrich Messages ... - foreach (var message in messages) - { - // - // Handle Owner ... - if (!message.OwnerId.IsNullOrEmpty()) - { - message.Owner = owner; - } - - // - // Handle Conversation ... - if (!message.ConversationId.IsDefaultGuid()) - { - message.ConversationTitle = conversation.Title; - message.ConversationTitleResouce = conversation.TitleResource; - } - } - } - - // - conversation.Messages = [.. messages]; - } - } - } - - // - // Attach Extracted Items ... - var result = Mapper.Map(source, options => - { - // - options.Items[nameof(source.Owner)] = owner; - options.Items[nameof(source.Conversations)] = conversations; - options.Items[nameof(source.TitleResource)] = titleResource; - options.Items[nameof(source.DescriptionResource)] = descriptionResource; - }); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken, - fillConversations: fillConversations, - fillConversationMessages: fillConversationMessages - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken, - fillConversations: fillConversations, - fillConversationMessages: fillConversationMessages - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiProjectServiceProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xAiModels.Providers.Dtos -{ - public class XAiProjectServiceProvider : XBaseDtoProvider, IXAiProjectServiceProvider - { - public XAiProjectServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXAiProjectRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorDtoHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Dtos -{ - public class XAiVectorDtoHub : XBaseDtoHub, IXAiVectorDtoHub - { - public XAiVectorDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorRepositoryService.cs - -using System; -using xAiModels.Models.Dtos; -using xDataService.Providers; -using xAiModels.Configurations; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Dtos -{ - public class XAiVectorRepositoryService : XBaseRepositoryService, IXAiVectorRepositoryService - { - public XAiVectorRepositoryService( - IXAiVectorRepository repository - ) : base( - repository, - mapperProfiles: - [ - new XAiModelMappersProfile() - ] - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiVectorServiceProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Dtos; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xAiModels.Providers.Dtos -{ - public class XAiVectorServiceProvider : XBaseDtoProvider, IXAiVectorServiceProvider - { - public XAiVectorServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXAiVectorRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiConversationEnricher.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xAiModels.Interfaces.Entities; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Enrichers -{ - public class XAiConversationEnricher : IXAiConversationEnricher - { - private readonly IXIdentityProvider identityProvider; - private readonly IXAiConversationRepository repository; - private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; - - public XAiConversationEnricher( - IXIdentityProvider identityProvider, - IXAiConversationRepository repository, - IXAiProjectTitleResourceProvider projectTitleResourceProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider, - IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider - ) - { - // - this.repository = repository; - this.identityProvider = identityProvider; - this.projectTitleResourceProvider = projectTitleResourceProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiConversation source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = source.MapConvert(); - result = await Enrich( - source: result, - fillMessages: fillMessages, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiConversationDto source, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Handdle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - // - // Try to Retrieve User Info ... - var device = identityProvider.GetDevice(); - var userInfo = await identityProvider.GetUserInfo( - device: device, - userSelectByParam: source.OwnerId - ); - owner = userInfo.ToXPersonDto(); - } - - // - // Handle Title Resource ... - XResourceDto titleResource = null; - if (!source.Title.IsNullOrEmpty()) - { - // - titleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Project Info ... - XResourceDto projectTitleResource = null; - XResourceDto projectDescriptionResource = null; - if (!source.ProjectId.IsDefaultGuid()) - { - // - projectTitleResource = await projectTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ProjectId, - cancellationToken: cancellationToken - ); - - // - projectDescriptionResource = await projectDescriptionResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ProjectId, - cancellationToken: cancellationToken - ); - } - - // - // Attach Extracted Items ... - var result = source.MapConvert(); - result.Owner = owner; - result.TitleResource = titleResource; - result.ProjectTitleResource = projectTitleResource; - result.ProjectTitle = projectTitleResource.Resource; - result.ProjectDescriptionResource = projectDescriptionResource; - result.ProjectDescription = projectDescriptionResource.Resource; - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - fillMessages: fillMessages, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - fillMessages: fillMessages, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMcpServerEnricher.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Enrichers -{ - public class XAiMcpServerEnricher : IXAiMcpServerEnricher - { - private readonly IXPersonService personService; - - public XAiMcpServerEnricher( - IXPersonService personService - ) - { - this.personService = personService; - } - - public virtual async Task Enrich( - XAiMcpServer source, - CancellationToken cancellationToken = default - ) - { - // - var result = source.MapConvert(); - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - public virtual async Task Enrich( - XAiMcpServerDto source, - CancellationToken cancellationToken = default - ) - { - // - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - owner = await personService.GetPerson(source.OwnerId); - } - - // - var result = source.MapConvert(); - result.Owner = owner; - - // - return result; - } - - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - var tasks = sources.Select(x => Enrich(x, cancellationToken)); - return await Task.WhenAll(tasks); - } - - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - var tasks = sources.Select(x => Enrich(x, cancellationToken)); - return await Task.WhenAll(tasks); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMessageEnricher.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Enrichers -{ - public class XAiMessageEnricher : IXAiMessageEnricher - { - private readonly IXPersonService personService; - private readonly IXIdentityProvider identityProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - - public XAiMessageEnricher( - IXPersonService personService, - IXIdentityProvider identityProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider - ) - { - this.personService = personService; - this.identityProvider = identityProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiMessage source, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = source.MapConvert(); - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiMessageDto source, - CancellationToken cancellationToken = default - ) - { - // - // Handdle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - owner = await personService.GetPerson(source.OwnerId); - } - - // - // Hanlde Conversation Title ... - string conversationTitle = string.Empty; - XResourceDto conversationTitleResource = null; - if (!source.ConversationId.IsDefaultGuid()) - { - // - conversationTitleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.ConversationId, - cancellationToken: cancellationToken - ); - if (!conversationTitleResource.IsNullOrDefault()) - { - conversationTitle = conversationTitleResource.Resource; - } - } - - // - // Attach Extracted Items ... - var result = source.MapConvert(); - result.Owner = owner; - result.ConversationTitle = conversationTitle; - result.ConversationTitleResouce = conversationTitleResource; - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiProjectEnricher.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Interfaces; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xAiModels.Interfaces.Entities; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Enrichers -{ - public class XAiProjectEnricher : IXAiProjectEnricher - { - private readonly IXPersonService personService; - private readonly IXIdentityProvider identityProvider; - private readonly IXAiMessageRepository messageRepository; - private readonly IXAiConversationRepository conversationRepository; - private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; - private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; - private readonly IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider; - - public XAiProjectEnricher( - IXPersonService personService, - IXIdentityProvider identityProvider, - IXAiMessageRepository messageRepository, - IXAiConversationRepository conversationRepository, - IXAiProjectTitleResourceProvider projectTitleResourceProvider, - IXAiConversationTitleResourceProvider conversationTitleResourceProvider, - IXAiProjectDescriptionResourceProvider projectDescriptionResourceProvider - ) - { - // - this.personService = personService; - this.identityProvider = identityProvider; - this.messageRepository = messageRepository; - this.conversationRepository = conversationRepository; - this.projectTitleResourceProvider = projectTitleResourceProvider; - this.conversationTitleResourceProvider = conversationTitleResourceProvider; - this.projectDescriptionResourceProvider = projectDescriptionResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiProject source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = source.MapConvert(); - result = await Enrich( - source: result, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Enrich( - XAiProjectDto source, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - // Handle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - owner = await personService.GetPerson(source.OwnerId); - } - - // - // Handle Title ... - XResourceDto titleResource = null; - if (!source.Title.IsNullOrEmpty()) - { - // - titleResource = await projectTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Description ... - XResourceDto descriptionResource = null; - if (!source.Description.IsNullOrEmpty()) - { - // - descriptionResource = await projectDescriptionResourceProvider.GetResource( - owner: source.OwnerId, - identifier: source.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Conversations ... - IEnumerable conversations = []; - if (fillConversations) - { - // - // Reading Entities ... - var entitiies = await conversationRepository.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.ProjectId == source.Id, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - // Converts to Dto Enumerable ... - conversations = entitiies - .MapConvert(); - - // - // Handle Conversation Enrichment ... - foreach (var conversation in conversations) - { - // - // Handle Owner ... - if (!conversation.OwnerId.IsNullOrEmpty()) - { - conversation.Owner = owner; - } - - // - // Handle Title Resource ... - if (!conversation.Title.IsNullOrEmpty()) - { - // - conversation.TitleResource = await conversationTitleResourceProvider.GetResource( - owner: source.OwnerId, - identifier: conversation.Id, - cancellationToken: cancellationToken - ); - } - - // - // Handle Project Info ... - if (!conversation.ProjectId.IsDefaultGuid()) - { - conversation.ProjectTitle = source.Title; - conversation.ProjectTitleResource = titleResource; - conversation.ProjectDescription = source.Description; - conversation.ProjectDescriptionResource = descriptionResource; - } - } - - // - // Handle Fill Messages ... - if (fillConversationMessages) - { - // - foreach (var conversation in conversations) - { - // - IEnumerable messages = []; - - // - // Retrieve Message Entities ... - var messageEntities = await messageRepository.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn), - predicate: x => x.ConversationId == conversation.Id - ); - if (messageEntities.HasChild()) - { - // - // Converts to Message ... - messages = messageEntities - .MapConvert(); - - // - // Ennrich Messages ... - foreach (var message in messages) - { - // - // Handle Owner ... - if (!message.OwnerId.IsNullOrEmpty()) - { - message.Owner = owner; - } - - // - // Handle Conversation ... - if (!message.ConversationId.IsDefaultGuid()) - { - message.ConversationTitle = conversation.Title; - message.ConversationTitleResouce = conversation.TitleResource; - } - } - } - - // - conversation.Messages = [.. messages]; - } - } - } - - // - // Attach Extracted Items ... - var result = source.MapConvert(); - result.Owner = owner; - result.TitleResource = titleResource; - result.Conversations = [.. conversations]; - result.DescriptionResource = descriptionResource; - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken, - fillConversations: fillConversations, - fillConversationMessages: fillConversationMessages - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken, - fillConversations: fillConversations, - fillConversationMessages: fillConversationMessages - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiVectorEnricher.cs - -using System.Linq; -using System.Threading; -using xCommons.Extensions; -using xAiModels.Extensions; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using xAiModels.Interfaces.Enrichers; - -namespace xAiModels.Providers.Enrichers -{ - public class XAiVectorEnricher : IXAiVectorEnricher - { - public XAiVectorEnricher() - { } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiVector source, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = source.MapConvert(); - - // - // Here we Converts Embeddings ... - result.Metadata = source.Metadata.AsMetadat(); - result.Embedding = source.Embedding.AsEmbedding(); - - // - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public virtual async Task Enrich( - XAiVectorDto source, - CancellationToken cancellationToken = default - ) - { - // - // Currently no additional enrichment needed for XAiVector - // This can be extended in the future if needed - return await Task.FromResult(source); - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public virtual async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich( - source: x, - cancellationToken: cancellationToken - )); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationEFRepository : XBaseEFRepository, IXAiConversationRepository - where TContext : XDbContext - { - public XAiConversationEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXAiConversationKeyGenerator keyGenerator = null, - IXAiConversationRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationEntityHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationEntityHub : XBaseEntityHub, IXAiConversationEntityHub - { - public XAiConversationEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationInMemoryRepository : XBaseInMemoryRepository, IXAiConversationRepository - { - public XAiConversationInMemoryRepository( - XDataServiceConfiguration configuration, - IXAiConversationKeyGenerator keyGenerator = null, - IXAiConversationRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationKeyGenerator.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationKeyGenerator : XGuidKeyGenerator, IXAiConversationKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationMongoRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationMongoRepository : XBaseMongoRepository, IXAiConversationRepository - { - public XAiConversationMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXAiConversationKeyGenerator keyGenerator = null, - IXAiConversationRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryEvents.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationRepositoryEvents : XBaseRepositoryEvents, IXAiConversationRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationRepositoryProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiConversationRepositoryProvider : XBaseEntityProvider, IXAiConversationRepositoryProvider - { - public XAiConversationRepositoryProvider( - IHubContext hub, - IXAiConversationRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiConversationSeederBase.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public abstract class XAiConversationSeederBase : XBaseDbSeeder, IXAiConversationSeeder - { - protected XAiConversationSeederBase( - string entity, - string database, - IXAiConversationRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerEFRepository : XBaseEFRepository, IXAiMcpServerRepository - where TContext : XDbContext - { - public XAiMcpServerEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXAiMcpServerKeyGenerator keyGenerator = null, - IXAiMcpServerRepositoryEvents baseRepositoryEvents = null - ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEntityHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerEntityHub : XBaseEntityHub, IXAiMcpServerEntityHub - { - public XAiMcpServerEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerInMemoryRepository : XBaseInMemoryRepository, IXAiMcpServerRepository - { - public XAiMcpServerInMemoryRepository( - XDataServiceConfiguration configuration, - IXAiMcpServerKeyGenerator keyGenerator = null, - IXAiMcpServerRepositoryEvents baseRepositoryEvents = null - ) : base(configuration, keyGenerator, baseRepositoryEvents) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerKeyGenerator.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerKeyGenerator : XGuidKeyGenerator, IXAiMcpServerKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerMongoRepository.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using xAiModels.Interfaces.Entities; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xDataService.Providers; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerMongoRepository : XBaseMongoRepository, IXAiMcpServerRepository - { - public XAiMcpServerMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXAiMcpServerKeyGenerator keyGenerator = null, - IXAiMcpServerRepositoryEvents baseRepositoryEvents = null - ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryEvents.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerRepositoryEvents : XBaseRepositoryEvents, IXAiMcpServerRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMcpServerRepositoryProvider : XBaseEntityProvider, IXAiMcpServerRepositoryProvider - { - public XAiMcpServerRepositoryProvider( - IHubContext hub, - IXAiMcpServerRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base(hub, repository, dataConfiguration, identityProvider) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerSeederBase.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public abstract class XAiMcpServerSeederBase : XBaseDbSeeder, IXAiMcpServerSeeder - { - protected XAiMcpServerSeederBase( - string entity, - string database, - IXAiMcpServerRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageEFRepository : XBaseEFRepository, IXAiMessageRepository - where TContext : XDbContext - { - public XAiMessageEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXAiMessageKeyGenerator keyGenerator = null, - IXAiMessageRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEntityHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageEntityHub : XBaseEntityHub, IXAiMessageEntityHub - { - public XAiMessageEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageInMemoryRepository : XBaseInMemoryRepository, IXAiMessageRepository - { - public XAiMessageInMemoryRepository( - XDataServiceConfiguration configuration, - IXAiMessageKeyGenerator keyGenerator = null, - IXAiMessageRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageKeyGenerator.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageKeyGenerator : XGuidKeyGenerator, IXAiMessageKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageMongoRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageMongoRepository : XBaseMongoRepository, IXAiMessageRepository - { - public XAiMessageMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXAiMessageKeyGenerator keyGenerator = null, - IXAiMessageRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryEvents.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageRepositoryEvents : XBaseRepositoryEvents, IXAiMessageRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageRepositoryProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiMessageRepositoryProvider : XBaseEntityProvider, IXAiMessageRepositoryProvider - { - public XAiMessageRepositoryProvider( - IHubContext hub, - IXAiMessageRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageSeederBase.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public abstract class XAiMessageSeederBase : XBaseDbSeeder, IXAiMessageSeeder - { - protected XAiMessageSeederBase( - string entity, - string database, - IXAiMessageRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectEFRepository : XBaseEFRepository, IXAiProjectRepository - where TContext : XDbContext - { - public XAiProjectEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXAiProjectKeyGenerator keyGenerator = null, - IXAiProjectRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectEntityHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectEntityHub : XBaseEntityHub, IXAiProjectEntityHub - { - public XAiProjectEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectInMemoryRepository : XBaseInMemoryRepository, IXAiProjectRepository - { - public XAiProjectInMemoryRepository( - XDataServiceConfiguration configuration, - IXAiProjectKeyGenerator keyGenerator = null, - IXAiProjectRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectKeyGenerator.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectKeyGenerator : XGuidKeyGenerator, IXAiProjectKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectMongoRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectMongoRepository : XBaseMongoRepository, IXAiProjectRepository - { - public XAiProjectMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXAiProjectKeyGenerator keyGenerator = null, - IXAiProjectRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryEvents.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectRepositoryEvents : XBaseRepositoryEvents, IXAiProjectRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectRepositoryProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiProjectRepositoryProvider : XBaseEntityProvider, IXAiProjectRepositoryProvider - { - public XAiProjectRepositoryProvider( - IHubContext hub, - IXAiProjectRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiProjectSeederBase.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public abstract class XAiProjectSeederBase : XBaseDbSeeder, IXAiProjectSeeder - { - protected XAiProjectSeederBase( - string entity, - string database, - IXAiProjectRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorEFRepository : XBaseEFRepository, IXAiVectorRepository - where TContext : XDbContext - { - public XAiVectorEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXAiVectorKeyGenerator keyGenerator = null, - IXAiVectorRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorEntityHub.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using Microsoft.Extensions.Logging; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorEntityHub : XBaseEntityHub, IXAiVectorEntityHub - { - public XAiVectorEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorInMemoryRepository : XBaseInMemoryRepository, IXAiVectorRepository - { - public XAiVectorInMemoryRepository( - XDataServiceConfiguration configuration, - IXAiVectorKeyGenerator keyGenerator = null, - IXAiVectorRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorKeyGenerator.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorKeyGenerator : XGuidKeyGenerator, IXAiVectorKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorMongoRepository.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorMongoRepository : XBaseMongoRepository, IXAiVectorRepository - { - public XAiVectorMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXAiVectorKeyGenerator keyGenerator = null, - IXAiVectorRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryEvents.cs - -using xDataService.Providers; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorRepositoryEvents : XBaseRepositoryEvents, IXAiVectorRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorRepositoryProvider.cs - -using System; -using xPushService.Base; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public class XAiVectorRepositoryProvider : XBaseEntityProvider, IXAiVectorRepositoryProvider - { - public XAiVectorRepositoryProvider( - IHubContext hub, - IXAiVectorRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiVectorSeederBase.cs - -using System; -using xDataService.Providers; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.Entities -{ - public abstract class XAiVectorSeederBase : XBaseDbSeeder, IXAiVectorSeeder - { - protected XAiVectorSeederBase( - string entity, - string database, - IXAiVectorRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQLTypeHelper.cs - -using System; -using xAiModels.Constants; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiConversationGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiConversationGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XAiModelsConstants.XAiConversationCollectionName; - } - - public override string GetInQuerySingleName() - { - return XAiModelsConstants.XAiConversationSignleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiConversationGraphQuery : XBaseGraphQLQuery - { - public XAiConversationGraphQuery( - XDataServiceConfiguration configuration, - IXAiConversationRepository repository, - IXAiConversationGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiConversationGraphSchema : Schema - { - public XAiConversationGraphSchema(IServiceProvider services) : base(services) - { - Query = (XAiConversationGraphQuery)services.GetService(typeof(XAiConversationGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiConversationGraphType.cs - -using System; -using xDataService.GraphQL; -using xAiModels.Models.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiConversationGraphType : XBaseGraphObjectType - { - public XAiConversationGraphType() : base() - { - Field(x => x.Title); - Field(x => x.OwnerId); - Field(x => x.CreatedOn); - Field(x => x.UpdatedAt); - Field(x => x.ProjectId); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQLTypeHelper.cs - -using System; -using xAiModels.Constants; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMcpServerGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiMcpServerGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XAiModelsConstants.XAiMcpServerCollectionName; - } - - public override string GetInQuerySingleName() - { - return XAiModelsConstants.XAiMcpServerSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMcpServerGraphQuery : XBaseGraphQLQuery - { - public XAiMcpServerGraphQuery( - XDataServiceConfiguration configuration, - IXAiMcpServerRepository repository, - IXAiMcpServerGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMcpServerGraphSchema : Schema - { - public XAiMcpServerGraphSchema(IServiceProvider services) : base(services) - { - Query = (XAiMcpServerGraphQuery)services.GetService(typeof(XAiMcpServerGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphType.cs - -using System; -using xDataService.GraphQL; -using xAiModels.Models.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMcpServerGraphType: XBaseGraphObjectType - { - public XAiMcpServerGraphType() : base() - { - Field(x => x.Name); - Field(x => x.Enabled); - Field(x => x.OwnerId); - Field(x => x.Headers); - Field(x => x.Endpoint); - Field(x => x.CreatedOn); - Field(x => x.UpdatedAt); - Field(x => x.Description); - Field(x => x.TimeoutSeconds); - Field(x => x.EnvironmentVariables); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQLTypeHelper.cs - -using System; -using xAiModels.Constants; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMessageGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiMessageGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XAiModelsConstants.XAiMessageCollectionName; - } - - public override string GetInQuerySingleName() - { - return XAiModelsConstants.XAiMessageSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMessageGraphQuery : XBaseGraphQLQuery - { - public XAiMessageGraphQuery( - XDataServiceConfiguration configuration, - IXAiMessageRepository repository, - IXAiMessageGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMessageGraphSchema : Schema - { - public XAiMessageGraphSchema(IServiceProvider services) : base(services) - { - Query = (XAiMessageGraphQuery)services.GetService(typeof(XAiMessageGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphType.cs - -using System; -using xDataService.GraphQL; -using xAiModels.Models.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiMessageGraphType: XBaseGraphObjectType - { - public XAiMessageGraphType() : base() - { - Field(x => x.Role); - Field(x => x.OwnerId); - Field(x => x.Content); - Field(x => x.Metadata); - Field(x => x.CreatedOn); - Field(x => x.UpdatedAt); - Field(x => x.ConversationId); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQLTypeHelper.cs - -using System; -using xAiModels.Constants; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiProjectGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiProjectGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XAiModelsConstants.XAiProjectCollectionName; - } - - public override string GetInQuerySingleName() - { - return XAiModelsConstants.XAiProjectSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiProjectGraphQuery : XBaseGraphQLQuery - { - public XAiProjectGraphQuery( - XDataServiceConfiguration configuration, - IXAiProjectRepository repository, - IXAiProjectGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiProjectGraphSchema : Schema - { - public XAiProjectGraphSchema(IServiceProvider services) : base(services) - { - Query = (XAiProjectGraphQuery)services.GetService(typeof(XAiProjectGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiProjectGraphType.cs - -using System; -using xDataService.GraphQL; -using xAiModels.Models.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiProjectGraphType : XBaseGraphObjectType - { - public XAiProjectGraphType() : base() - { - Field(x => x.Title); - Field(x => x.OwnerId); - Field(x => x.Prompt); - Field(x => x.CreatedOn); - Field(x => x.UpdatedAt); - Field(x => x.Description); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQLTypeHelper.cs - -using System; -using xAiModels.Constants; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiVectorGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiVectorGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XAiModelsConstants.XAiVectorCollectionName; - } - - public override string GetInQuerySingleName() - { - return XAiModelsConstants.XAiVectorSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xAiModels.Models.Entities; -using xDataService.Configuration; -using xAiModels.Interfaces.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiVectorGraphQuery : XBaseGraphQLQuery - { - public XAiVectorGraphQuery( - XDataServiceConfiguration configuration, - IXAiVectorRepository repository, - IXAiVectorGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiVectorGraphSchema : Schema - { - public XAiVectorGraphSchema(IServiceProvider services) : base(services) - { - Query = (XAiVectorGraphQuery)services.GetService(typeof(XAiVectorGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiVectorGraphType.cs - -using System; -using xDataService.GraphQL; -using xAiModels.Models.Entities; - -namespace xAiModels.Providers.GraphQL -{ - public class XAiVectorGraphType : XBaseGraphObjectType - { - public XAiVectorGraphType() : base() - { - Field(x => x.Text); - Field(x => x.Metadata); - Field(x => x.Embedding); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Hubs\XAiDataProviderHub.cs - -using System.Threading; -using xPushService.Base; -using xAiModels.Constants; -using xCommons.Extensions; -using xAiModels.Models.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.Logging; - -namespace xAiModels.Providers.Hubs -{ - public class XAiDataProviderHub : XBaseHub - { - public XAiDataProviderHub( - ILogger logger - ) : base(logger) - { } - - // - #region XAiProject ... - /// - /// Notify a New Item Created ... - /// - /// - /// - /// - public async Task ProjectCreated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ProjectCreated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Removed ... - /// - /// - /// - /// - public async Task ProjectRemoved( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ProjectRemoved.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task ProjectUpdated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ProjectUpdated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - - // - #region XAiMessage ... - /// - /// Notify a New Item Created ... - /// - /// - /// - /// - public async Task MessageCreated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.MessageCreated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Removed ... - /// - /// - /// - /// - public async Task MessageRemoved( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.MessageRemoved.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task MessageUpdated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.MessageUpdated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - - // - #region XAiMcpServer ... - /// - /// Notify a New Item Created ... - /// - /// - /// - /// - public async Task McpServerCreated( - XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.McpServerCreated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Removed ... - /// - /// - /// - /// - public async Task McpServerRemoved( - XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.McpServerRemoved.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task McpServerUpdated( - XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.McpServerUpdated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - - // - #region XAiConversation ... - /// - /// Notify a New Item Created ... - /// - /// - /// - /// - public async Task ConversationCreated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationCreated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Removed ... - /// - /// - /// - /// - public async Task ConversationRemoved( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationRemoved.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task ConversationUpdated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261109_152620.txt deleted file mode 100644 index 24f19b7..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiService-20261109_152620.txt +++ /dev/null @@ -1,1947 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs - -namespace xAiService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string AI_SERVICE_NODE = "AIServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs - -namespace xAiService.Constants -{ - public struct XAiServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XAiServiceDILogTag = "XAiService"; - - // - // File Provider Identifiers ... - public const string XAiProjectFilesIdentifier = "AiPrjF"; - public const string XAiMessageFilesIdentifier = "AiMsgF"; - public const string XMetaDataFileIdsIdentifier = "FileIds"; - public const string XAiConversationFilesIdentifier = "AiCnvrF"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs - -using System.Threading; -using xCommons.Providers; -using Newtonsoft.Json.Linq; -using xAiService.Interfaces; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xAiService.Controllers -{ - [Route("mcp")] - [AllowAnonymous] - public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller - { - private readonly IXAiMcpHandler mcpHandler; - - protected XAiMcpControllerBase( - IXAiMcpHandler mcpHandler, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - ILogger logger, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { - this.mcpHandler = mcpHandler; - } - - /// - /// Handle MCP ... - /// - /// - /// - /// - [HttpPost] - public virtual async Task HandleMcp( - [FromBody] JObject request, - CancellationToken cancellationToken = default - ) - { - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var response = await mcpHandler.ProcessAsync( - request: request, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(response); - } - - /// - /// Handle SSE EndPoint ... - /// - /// - /// - [HttpGet("sse")] - public virtual async Task SseEndpoint( - CancellationToken cancellationToken = default - ) - { - // - Response.Headers.Add("Content-Type", "text/event-stream"); - Response.Headers.Add("Cache-Control", "no-cache"); - - // - await Response - .WriteAsync( - "event: endpoint\ndata: /mcp\n\n", - cancellationToken - ); - - // - await Response.Body.FlushAsync(cancellationToken); - - // - while (!cancellationToken.IsCancellationRequested) - { - await Task.Delay(1000, cancellationToken); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs - -using System.Net.Http; -using System.Threading; -using xAiModels.Constants; -using xAiService.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Register XAiMcpClient in DI ... - /// - /// - public static void AddXAiMcpClient( - this IServiceCollection source - ) - { - // - // Register Http Client ... - source.AddHttpClient( - XAiMcpConstants.XAiMcpClientName, - client => - { - client.Timeout = Timeout.InfiniteTimeSpan; - } - ) - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true - }); - - // - source.AddScoped(); - source.AddSingleton(); - - // - source.AddHostedService(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs - -using System; -using System.Linq; -using System.Reflection; -using xAiService.Services; -using xAiService.Interfaces; -using Microsoft.Extensions.DependencyInjection; - -namespace xAiService.Extensions -{ - public static class DIExtensions - { - /// - /// Register XAiMcpHandler Service ... - /// - /// - public static void AddXAiMcpHandler( - this IServiceCollection source - ) - { - // - // Register MCP User Context ... - source.AddScoped(); - - // - // Register MCP Tool Scanner ... - source.AddSingleton(sp => - { - // - // Scan All Exists Assemblies ... - var asms = AppDomain.CurrentDomain - .GetAssemblies() - .Where(a => !a.IsDynamic && - a.GetName().Name != null && - a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) - .Append(Assembly.GetEntryAssembly()!) - .ToArray(); - - // - return new XAiMcpToolScanner(asms); - }); - - // - // 2) Register MCP Handler ... - source.AddScoped(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs - -using xAiModels.Models; -using xCommons.Extensions; -using xAiService.Services; -using xExceptions.Constants; -using xIdentityModels.Models; -using Microsoft.Extensions.AI; -using System.Collections.Generic; - -namespace xAiService.Extensions -{ - public static class XAiServiceExtensions - { - /// - /// Validate User Info ... - /// - /// - /// - public static bool IsValid(this XUserClaimsInfoDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.UserId.IsNullOrEmpty() && - !source.AccessToken.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate User Info ... - /// - /// - /// - public static void Validate( - this XUserClaimsInfoDto source, - XException invalidException = XException.InvalidArgs - ) - { - // - var isValid = source.IsValid(); - if (!isValid) - { - invalidException.Throw(); - } - } - - /// - /// Converts To AITools ... - /// - /// - /// - /// - public static IList ToAITools( - this IList source, - XAiMcpClient client - ) - { - // - if (client.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = new List(); - - // - foreach (var tool in source) - { - result.Add(new XAiMcpAIFunction(client, tool)); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs - -using System; -using Newtonsoft.Json.Linq; - -namespace xAiService.Helpers -{ - public static class XAiMcpArgumentHelper - { - /// - /// Bind Parameters ... - /// - /// - /// - /// - public static object Bind( - JToken token, - Type targetType - ) - { - // - var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; - - // - // Null Handling ... - if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) - { - // - if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) - { - return null; - } - - // - return Activator.CreateInstance(targetType); - } - - // - // Primitive Types ... - - // - if (underlying == typeof(string)) - { - return token.ToString(); - } - - // - if (underlying == typeof(int)) - { - return token.Value(); - } - - // - if (underlying == typeof(long)) - { - return token.Value(); - } - - // - if (underlying == typeof(short)) - { - return token.Value(); - } - - // - if (underlying == typeof(float)) - { - return token.Value(); - } - - // - if (underlying == typeof(double)) - { - return token.Value(); - } - - // - if (underlying == typeof(decimal)) - { - return token.Value(); - } - - // - if (underlying == typeof(bool)) - { - return token.Value(); - } - - // - if (underlying == typeof(Guid)) - { - return token.Value(); - } - - // - if (underlying == typeof(DateTime)) - { - return token.Value(); - } - - // - // Enum ... - if (underlying.IsEnum) - { - return Enum.Parse(underlying, token.ToString(), ignoreCase: true); - } - - // - // Arrays ... - if (underlying.IsArray && token is JArray jarr) - { - // - var elementType = underlying.GetElementType(); - var arr = Array.CreateInstance(elementType, jarr.Count); - for (var i = 0; i < jarr.Count; i++) - { - arr.SetValue(Bind(jarr[i], elementType), i); - } - - // - return arr; - } - - // - // Fallback: JSON Deserialize - return token.ToObject(underlying); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs - -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; - -namespace xAiService.Helpers -{ - public static class XAiMcpResultExtractionHelper - { - /// - /// Extract Specified Object Result of Method Invoking ... - /// - /// - /// - /// - public static async Task ExtractAsync( - object raw, - Type returnType - ) - { - // - // Task / Task - if (raw is Task task) - { - // - await task.ConfigureAwait(false); - if (returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(Task<>)) - { - // - var value = returnType.GetProperty("Result").GetValue(task); - return Format(value); - } - - // - return string.Empty; - } - - // - // ValueTask (non-generic) - if (returnType == typeof(ValueTask)) - { - // - await ((ValueTask)raw).ConfigureAwait(false); - return string.Empty; - } - - // - // ValueTask ... - if (returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) - { - // - var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); - await asTask.ConfigureAwait(false); - var value = asTask.GetType().GetProperty("Result").GetValue(asTask); - - // - return Format(value); - } - - // - // void / T Syncron ... - return Format(raw); - } - - // - #region Private ... - /// - /// Format Extracted Response ... - /// /// - /// - /// - private static string Format(object value) - { - // - if (value == null) - { - return string.Empty; - } - - // - if (value is string s) - { - return s; - } - - // - if (value is JToken jt) - { - return jt.ToString(Formatting.None); - } - - // - if (value.GetType().IsPrimitive || value is decimal) - { - return value.ToString(); - } - - // - return JToken.FromObject(value).ToString(Formatting.None); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs - -using System.Threading; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; -using xIdentityModels.Models; - -namespace xAiService.Interfaces -{ - public interface IXAiMcpHandler - { - /// - /// Process Specified JSON-RPC Request ... - /// - /// - /// - /// - /// - /// - Task ProcessAsync( - JObject request, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs - -using xIdentityModels.Models; - -namespace xAiService.Interfaces -{ - /// - /// User Context for MCP Servers ... - /// - /// Automatic Filled in HTTP Request Execution Time ... - /// When Request Execution Ended, Disposed ... - /// - /// - for Instanced Tools: Accessible using Dependency Injection ... - /// - for Static Tools: Accessible using Static Properties Current* ... - /// - public interface IXAiMcpUserContext - { - /// - /// Connection Id ... - /// - /// - string ConnectionId { get; } - - /// - /// User Claims ... - /// - /// - XUserClaimsInfoDto UserInfo { get; } - - /// - /// Fill Context ... - /// - /// - /// - void Set( - XUserClaimsInfoDto userInfo, - string connectionId = null - ); - - /// - /// Clear Context ... - /// - void Clear(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs - -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Text.Json.Nodes; -using System.Threading.Tasks; -using Microsoft.Extensions.AI; - -namespace xAiService.Services -{ - /// - /// a Customized AIFunction Implementation ... - /// - public class XAiMcpAIFunction : AIFunction - { - // - private readonly XAiMcpClient client; - private readonly JsonElement jsonSchema; - private readonly XAiMcpToolDefinition definition; - - public XAiMcpAIFunction( - XAiMcpClient client, - XAiMcpToolDefinition definition - ) - { - // - if (client.IsNull() || definition.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - this.client = client; - this.definition = definition; - - // - jsonSchema = definition.InputSchema.Clone(); - } - - // - public override string Name => definition.Name; - public override JsonElement JsonSchema => jsonSchema; - public override string Description => definition.Description; - - /// - /// Invoke Tool ... - /// - /// - /// - /// - protected override async ValueTask InvokeCoreAsync( - AIFunctionArguments arguments, - CancellationToken cancellationToken = default - ) - { - // - var jsonArgs = ToJsonObject(arguments); - return await client.CallToolAsync( - definition.Name, - jsonArgs, - cancellationToken - ); - } - - private JsonObject ToJsonObject(AIFunctionArguments arguments) - { - // - var result = new JsonObject(); - if (arguments.IsNull() || - arguments is null) - { - return result; - } - - // - foreach (var kvp in arguments) - { - result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs - -using System; -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xAiModels.Helpers; -using xAiModels.Constants; -using xCommons.Extensions; -using System.Text.Json.Nodes; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpClient : IAsyncDisposable - { - // - private readonly Uri endpoint; - private readonly Guid serverId; - private readonly ILogger logger; - private readonly string connectionId; - private readonly XUserClaimsInfoDto userInfo; - private readonly XAiMcpHttpTransport transport; - private readonly XAiMcpSessionStore sessionStore; - private readonly XAppConfiguration appConfiguration; - - // - public string ServerName { get; private set; } - public bool IsInitialized { get; private set; } - public string ServerVersion { get; private set; } - public string ProtocolVersion { get; private set; } = XAiMcpConstants.XAiMcpProtocol; - - public XAiMcpClient( - Uri endpoint, - Guid serverId, - ILogger logger, - XAiMcpHttpTransport transport, - XAiMcpSessionStore sessionStore, - XAppConfiguration appConfiguration, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ) - { - // - this.logger = logger; - this.serverId = serverId; - this.endpoint = endpoint; - this.userInfo = userInfo; - this.transport = transport; - this.sessionStore = sessionStore; - this.connectionId = connectionId; - this.appConfiguration = appConfiguration; - } - - /// - /// Initialize MCP Server ... - /// - /// - /// - public async Task InitializeAsync(CancellationToken cancellationToken = default) - { - // - if (IsInitialized) - { - return; - } - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.Initialize.GetStringValue(), - Params = new - { - capabilities = new { tools = new { } }, - protocolVersion = XAiMcpConstants.XAiMcpProtocol, - clientInfo = new { - name = XAiMcpConstants.serverInfoNameValue, - version = XAiMcpConstants.serverInfoVersionValue - } - } - }; - - // - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - connectionId: connectionId, - appConfiguration: appConfiguration - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}"); - } - - // - var result = response.Result?.Deserialize(); - if (result?.TryGetProperty(XAiMcpConstants.ProtocolVersionKey, out var pv) == true) - { - ProtocolVersion = pv.GetString() ?? ProtocolVersion; - } - if (result?.TryGetProperty(XAiMcpConstants.ServerInfoKey, out var si) == true) - { - // - ServerName = si.TryGetProperty(XAiMcpConstants.ServerInfoNameKey, out var n) ? n.GetString() : null; - ServerVersion = si.TryGetProperty(XAiMcpConstants.ServerInfoVersionKey, out var v) ? v.GetString() : null; - } - - // - IsInitialized = true; - logger.LogInformation( - "MCP initialized: {Name} v{Version} (protocol {PV})", - ServerName, - ServerVersion, - ProtocolVersion - ); - } - - /// - /// Get a List of Available Tools on Initialize MCP Server ... - /// - /// - /// - public async Task> ListToolsAsync(CancellationToken cancellationToken = default) - { - // - await EnsureInitializedAsync(cancellationToken); - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.ToolsList.GetStringValue() - }; - - // - var sessionId = sessionStore.Get(serverId, userInfo.UserId); - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - appConfiguration: appConfiguration, - connectionId: connectionId, - sessionId: sessionId, - protocolVersion: ProtocolVersion - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}"); - } - - // - var toolsArray = response.Result?.Deserialize(); - if (toolsArray?.TryGetProperty("tools", out var tools) != true) - { - return new List(); - } - - // - return tools.Deserialize>() ?? new(); - } - - /// - /// Call Specified Tools of MCP Server ... - /// - /// - /// - /// - /// - public async Task CallToolAsync( - string toolName, - JsonObject arguments, - CancellationToken cancellationToken = default - ) - { - // - await EnsureInitializedAsync(cancellationToken); - - // - var request = new XAiMcpJsonRpcRequest - { - Method = XAiMcpMethods.ToolsCall.GetStringValue(), - Params = new - { - name = toolName, - arguments = arguments ?? new JsonObject() - } - }; - - // - var sessionId = sessionStore.Get(serverId, userInfo.UserId); - var headers = XAiMcpHeaderBuilder.Build( - userInfo: userInfo, - sessionId: sessionId, - connectionId: connectionId, - protocolVersion: ProtocolVersion, - appConfiguration: appConfiguration - ); - - // - var response = await transport - .SendAsync( - endpoint, - headers, - request, - cancellationToken - ); - if (!response.IsSuccess) - { - throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}"); - } - - // - var result = response.Result?.Deserialize(); - if (result?.TryGetProperty(XAiMcpConstants.ContentKey, out var content) == true && - content.ValueKind == JsonValueKind.Array && - content.GetArrayLength() > 0 - ) - { - // - var first = content[0]; - if (first.TryGetProperty(XAiMcpConstants.TextKey, out var text)) - { - return text.GetString() ?? string.Empty; - } - } - - // - return result?.GetRawText() ?? string.Empty; - } - - /// - /// Dispose Instanced Client ... - /// - /// - public async ValueTask DisposeAsync() - { - await Task.CompletedTask; - } - - // - #region Private ... - private async Task EnsureInitializedAsync(CancellationToken ct) - { - // - if (!IsInitialized) - { - await InitializeAsync(ct); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs - -using System; -using System.Threading; -using xAiModels.Models; -using Newtonsoft.Json.Linq; -using xAiService.Interfaces; -using System.Threading.Tasks; -using System.Collections.Generic; -using xIdentityModels.Models; -using xCommons.Extensions; -using System.Linq; -using xIdentityService.Interfaces; - -namespace xAiService.Services -{ - public class XAiMcpHandler : IXAiMcpHandler - { - // - private readonly XAiMcpToolScanner scanner; - private readonly IXPolicyHandler policyHandler; - private readonly IXAiMcpUserContext userContext; - private readonly IServiceProvider serviceProvider; - private readonly Dictionary tools = new(); - - public XAiMcpHandler( - XAiMcpToolScanner scanner, - IXPolicyHandler policyHandler, - IXAiMcpUserContext userContext, - IServiceProvider serviceProvider - ) - { - // - this.scanner = scanner; - this.userContext = userContext; - this.policyHandler = policyHandler; - this.serviceProvider = serviceProvider; - - // - RegisterTools(); - } - - /// - /// Process Specified JSON-RPC Request ... - /// - /// - /// - /// - /// - /// - public async Task ProcessAsync( - JObject request, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Filling User Context ... - userContext.Set(userInfo, connectionId); - - // - try - { - // - var id = request["id"]; - var method = request["method"]?.ToString(); - - // - return method switch - { - "initialize" => HandleInitialize(id), - "tools/list" => HandleToolsList(id, userInfo), - "tools/call" => await HandleToolCallAsync(request, id, userInfo, cancellationToken), - "ping" => HandlePing(id), - _ => CreateError(id, -32601, $"Method not found: {method}") - }; - } - finally - { - userContext.Clear(); - } - } - - // - #region Private ... - private JObject HandleInitialize(JToken id) - { - return CreateResult(id, new JObject - { - ["protocolVersion"] = "2024-11-05", - ["capabilities"] = new JObject - { - ["tools"] = new JObject { ["listChanged"] = true } - }, - ["serverInfo"] = new JObject - { - ["name"] = "xAiMcpServer", - ["version"] = "1.0.0" - } - }); - } - - private JObject HandleToolsList( - JToken id, - XUserClaimsInfoDto userInfo - ) - { - var jsonTools = new JArray(); - foreach (var tool in tools.Values) - { - // - if (!tool.RequiredPolicy.IsNullOrEmpty() && - !CheckPolicy(userInfo, tool.RequiredPolicy)) - { - continue; - } - - // - jsonTools.Add(new JObject - { - ["name"] = tool.Name, - ["description"] = tool.Description, - ["inputSchema"] = tool.InputSchema - }); - } - - // - return CreateResult(id, new JObject { ["tools"] = jsonTools }); - } - - private async Task HandleToolCallAsync( - JObject request, - JToken id, - XUserClaimsInfoDto userInfo, - CancellationToken ct - ) - { - // - var toolName = request["params"]?["name"]?.ToString(); - var args = request["params"]?["arguments"] as JObject; - - // - if (!tools.ContainsKey(toolName)) - { - return CreateError(id, -32602, $"Tool not found: {toolName}"); - } - - // - var tool = tools[toolName]; - - // - // Check User Info Required or not ... - - // - // Level 1 ... - if (userInfo.IsNull() && tool.RequiresAuthentication) - { - return CreateError(id, -32001, $"Authentication required for tool: {toolName}"); - } - - // - // Level 2 ... - if (!tool.RequiredPolicy.IsNullOrEmpty() && - !CheckPolicy(userInfo, tool.RequiredPolicy)) - { - return CreateError(id, -32002, $"Access denied for tool: {toolName}"); - } - - // - var result = await tool.Execute(args, ct); - return CreateResult(id, new JObject - { - ["content"] = new JArray - { - new JObject - { - ["type"] = "text", - ["text"] = result - } - } - }); - } - - private JObject CreateResult( - JToken id, - JObject result - ) - { - // - return new JObject - { - ["jsonrpc"] = "2.0", - ["id"] = id, - ["result"] = result - }; - } - - private JObject CreateError( - JToken id, - int code, - string message - ) - { - // - return new JObject - { - ["jsonrpc"] = "2.0", - ["id"] = id, - ["error"] = new JObject - { - ["code"] = code, - ["message"] = message - } - }; - } - - private void RegisterTools() - { - // - // 1) Manually Register Tools ... - RegisterManualTools(); - - // - // 2) Register Scanned Tools uding Reflection ... - foreach (var blueprint in scanner.Blueprints) - { - // - // Prevent Double Registration if Name Exists ... - if (tools.ContainsKey(blueprint.Name)) - { - continue; - } - - // - tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider); - } - } - - private void RegisterManualTools() - { - // Manually Tools Registration ... - // tools["search_knowledge"] = new XAiMcpToolDescriptor - // { - // Name = "search_knowledge", - // Description = "Search in knowledge base", - // InputSchema = new JObject - // { - // ["type"] = "object", - // ["properties"] = new JObject - // { - // ["query"] = new JObject { ["type"] = "string" } - // }, - // ["required"] = new JArray("query") - // }, - // Execute = async (args, ct) => - // { - // var query = args?["query"]?.ToString() ?? ""; - // return $"Results for: {query}"; - // } - // }; - } - - private JObject HandlePing(JToken id) - { - return CreateResult(id, new JObject()); - } - - private bool CheckPolicy(XUserClaimsInfoDto user, string policy) - { - // - var result = false; - - // - if (user.IsNullOrDefault()) - { - return result; - } - - // - // Handle Authorization ... - result = policyHandler.IsPolicyPassed( - policy: policy, - roles: user.Roles - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs - -using System; -using System.Text; -using System.Net.Http; -using System.Text.Json; -using System.Threading; -using xAiModels.Models; -using xAiModels.Helpers; -using xAiModels.Constants; -using System.Threading.Tasks; -using System.Net.Http.Headers; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpHttpTransport - { - // - private readonly IHttpClientFactory httpClientFactory; - private readonly ILogger logger; - - public XAiMcpHttpTransport( - IHttpClientFactory httpClientFactory, - ILogger logger - ) - { - // - this.logger = logger; - this.httpClientFactory = httpClientFactory; - } - - public async Task SendAsync( - Uri endpoint, - Dictionary headers, - XAiMcpJsonRpcRequest request, - CancellationToken cancellationToken = default - ) - { - // - var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName); - client.Timeout = Timeout.InfiniteTimeSpan; - - // - using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint); - - // - // Add all Headers ... - foreach (var header in headers) - { - httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); - } - - // - // Prepare For Accepting SSE and JSON-RPC ... - httpRequest.Headers.Accept.Clear(); - httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); - - // - var json = JsonSerializer.Serialize(request); - httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json"); - headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId); - - // - logger.LogDebug( - "MCP → {Method} | {Url} | Session={Session}", - request.Method, - endpoint, - sessionId - ); - - // - var response = await client - .SendAsync( - httpRequest, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken - ); - - // - if (!response.IsSuccessStatusCode) - { - // - var errorBody = await response.Content.ReadAsStringAsync(); - logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody); - - // - throw new HttpRequestException( - $"MCP request failed: {response.StatusCode}. Body: {errorBody}"); - } - - // - // Content Type Detection ... - var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json"; - if (contentType.Contains("text/event-stream")) - { - // - // SSE Answer ... - var stream = await response.Content.ReadAsStreamAsync(); - await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken)) - { - // - var parsed = JsonSerializer.Deserialize(data); - if (parsed?.Id == request.Id || parsed?.Id is null) - { - return parsed; - } - } - - // - throw new InvalidOperationException("SSE stream ended without matching response."); - } - else - { - // - // Simple JSON answer ... - var body = await response.Content.ReadAsStringAsync(); - return JsonSerializer.Deserialize(body); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace xAiService.Services -{ - public class XAiMcpSessionCleanupService : BackgroundService - { - // - private readonly XAiMcpSessionStore store; - private readonly ILogger logger; - - public XAiMcpSessionCleanupService( - XAiMcpSessionStore store, - ILogger logger - ) - { - // - this.store = store; - this.logger = logger; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - // - while (!stoppingToken.IsCancellationRequested) - { - // - await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); - var removed = store.CleanupExpired(); - if (removed > 0) - { - // - logger - .LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed); - } - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs - -using System; -using System.Collections.Concurrent; - -namespace xAiService.Services -{ - public class XAiMcpSessionStore - { - // - private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15); - private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new(); - - public string Get( - Guid serverId, - string userId - ) - { - // - if (!sessions.TryGetValue((serverId, userId), out var entry)) - { - return null; - } - - // - // Expriration Check ... - if (DateTime.UtcNow - entry.LastAccessAt > Ttl) - { - // - sessions.TryRemove((serverId, userId), out _); - return null; - } - - // - entry.LastAccessAt = DateTime.UtcNow; - return entry.SessionId; - } - - public void Set( - Guid serverId, - string userId, - string sessionId - ) - { - // - sessions[(serverId, userId)] = new SessionEntry - { - SessionId = sessionId, - LastAccessAt = DateTime.UtcNow - }; - } - - public void Remove( - Guid serverId, - string userId - ) => sessions.TryRemove((serverId, userId), out _); - - public int CleanupExpired() - { - // - var count = 0; - var now = DateTime.UtcNow; - foreach (var kv in sessions) - { - // - if (now - kv.Value.LastAccessAt > Ttl) - { - if (sessions.TryRemove(kv.Key, out _)) - { - count++; - } - } - } - - // - return count; - } - - private class SessionEntry - { - public string SessionId { get; set; } - public DateTime LastAccessAt { get; set; } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs - -using System; -using xAiModels.Models; -using System.Threading; -using System.Reflection; -using xAiService.Helpers; -using Newtonsoft.Json.Linq; -using System.Threading.Tasks; - -namespace xAiService.Services -{ - public class XAiMcpToolBlueprint - { - public string Name { get; set; } - public string Description { get; set; } - public JObject InputSchema { get; set; } - public string RequiredPolicy { get; set; } - public bool RequiresAuthentication { get; set; } - - internal MethodInfo Method { get; set; } - internal Type DeclaringType { get; set; } - - /// - /// Create an Specific Descriptor which can Execute on Current IServiceProvider ... - /// - /// - /// - public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) - { - // - var result = new XAiMcpToolDescriptor - { - Name = Name, - Description = Description, - InputSchema = InputSchema, - RequiredPolicy = RequiredPolicy, - Execute = BuildExecute(serviceProvider), - RequiresAuthentication = RequiresAuthentication, - }; - - // - return result; - } - - /// - /// Build Tools Execution for MCP Method ... - /// - /// - /// - private Func> BuildExecute( - IServiceProvider serviceProvider - ) - { - // - var method = Method; - var declaringType = DeclaringType; - return async (args, ct) => - { - // - try - { - // - // 1. Make/Retrieve Instance ... - var instance = method.IsStatic - ? null - : (serviceProvider.GetService(declaringType) - ?? Activator.CreateInstance(declaringType)); - - // - // 2. Binding Method Arguments ... - var parameters = method.GetParameters(); - var values = new object[parameters.Length]; - for (var i = 0; i < parameters.Length; i++) - { - // - var p = parameters[i]; - - // - // Handle CancellationToken Token ... - if (p.ParameterType == typeof(CancellationToken)) - { - values[i] = ct; - continue; - } - - // - // Retrieve Param Attribute ... - var attr = p.GetCustomAttribute(); - var jsonName = attr?.Name ?? p.Name; - values[i] = XAiMcpArgumentHelper.Bind(args?[jsonName], p.ParameterType); - } - - // - // 3. Invoke and Await ... - object raw; - try - { - raw = method.Invoke(instance, values); - } - catch (TargetInvocationException tie) when (tie.InnerException != null) - { - throw tie.InnerException; - } - - // - // 4. Extract Invoking Result ... - return await XAiMcpResultExtractionHelper.ExtractAsync(raw, method.ReturnType); - } - catch (Exception ex) - { - return $"Error: {ex.Message}"; - } - }; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs - -using System; -using System.Linq; -using System.Threading; -using System.Reflection; -using Newtonsoft.Json.Linq; -using xAiModels.Attributes; -using System.ComponentModel; -using System.Collections.Generic; - -namespace xAiService.Services -{ - public class XAiMcpToolScanner - { - private readonly Assembly[] assemblies; - private readonly Lazy> blueprints; - - public XAiMcpToolScanner(IEnumerable assemblies) - { - // - this.assemblies = assemblies? - .Where(a => a != null && !a.IsDynamic) - .Distinct() - .ToArray() ?? []; - - // - blueprints = new Lazy>( - Scan, - LazyThreadSafetyMode.ExecutionAndPublication - ); - } - - public IReadOnlyList Blueprints => blueprints.Value; - - // - #region Private ... - private IReadOnlyList Scan() - { - // - var result = new List(); - var seenNames = new HashSet(StringComparer.Ordinal); - foreach (var asm in assemblies) - { - // - foreach (var type in SafeGetTypes(asm)) - { - // - if (type.GetCustomAttribute() == null) - { - continue; - } - - // - foreach (var method in type.GetMethods( - BindingFlags.Public | - BindingFlags.Instance | - BindingFlags.Static)) - { - // - var attr = method.GetCustomAttribute(); - if (attr == null) - { - continue; - } - - // - var name = string.IsNullOrWhiteSpace(attr.Name) - ? method.Name - : attr.Name.Trim(); - - if (!seenNames.Add(name)) - { - // - throw new InvalidOperationException( - $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); - } - - // - var description = attr.Description - ?? method.GetCustomAttribute()?.Description - ?? string.Empty; - - // - var requiredPolicy = attr.RequiredPolicy - ?? string.Empty; - - // - var requiredAuthenticated = attr.RequiresAuthentication; - - // - result.Add(new XAiMcpToolBlueprint - { - Name = name, - Method = method, - DeclaringType = type, - Description = description, - RequiredPolicy = requiredPolicy, - InputSchema = BuildInputSchema(method), - RequiresAuthentication = requiredAuthenticated - }); - } - } - } - - // - return result; - } - - private static JObject BuildInputSchema(MethodInfo method) - { - // - var properties = new JObject(); - var required = new JArray(); - - // - foreach (var p in method.GetParameters()) - { - // - // CancellationToken doesnt exists in Schema ... - if (p.ParameterType == typeof(CancellationToken)) - { - continue; - } - - // - var attr = p.GetCustomAttribute(); - var jsonName = attr?.Name ?? p.Name; - var description = attr?.Description - ?? p.GetCustomAttribute()?.Description - ?? string.Empty; - - // - var propSchema = new JObject - { - ["type"] = MapJsonType(p.ParameterType) - }; - - // - if (!string.IsNullOrWhiteSpace(description)) - { - propSchema["description"] = description; - } - - // - // Define Items Array ... - var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; - if (underlying.IsArray) - { - // - propSchema["items"] = new JObject - { - ["type"] = MapJsonType(underlying.GetElementType()) - }; - } - - // - properties[jsonName] = propSchema; - - // Check is Required ... - var isRequired = attr?.Required ?? true; - if (isRequired) - { - required.Add(jsonName); - } - } - - // - var result = new JObject - { - ["type"] = "object", - ["required"] = required, - ["properties"] = properties, - }; - - // - return result; - } - - private static string MapJsonType(Type type) - { - // - var t = Nullable.GetUnderlyingType(type) ?? type; - - // - if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) - { - return "string"; - } - - // - if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) - { - return "integer"; - } - - // - if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) - { - return "number"; - } - - // - if (t == typeof(bool)) - { - return "boolean"; - } - - // - if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) - { - return "array"; - } - - // - if (t.IsEnum) - { - return "string"; - } - - // - return "object"; - } - - private static IEnumerable SafeGetTypes(Assembly asm) - { - // - try - { - return asm.GetTypes(); - } - catch (ReflectionTypeLoadException ex) - { - return ex.Types.Where(t => t != null)!; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpUserContext.cs - -using System.Threading; -using xAiService.Interfaces; -using xIdentityModels.Models; - -namespace xAiService.Services -{ - /// - /// User Context for MCP Servers ... - /// - /// Automatic Filled in HTTP Request Execution Time ... - /// When Request Execution Ended, Disposed ... - /// - /// - for Instanced Tools: Accessible using Dependency Injection ... - /// - for Static Tools: Accessible using Static Properties Current* ... - /// - public class XAiMcpUserContext : IXAiMcpUserContext - { - // - private static readonly AsyncLocal connectionIdAsyncLocal = new(); - private static readonly AsyncLocal userAsyncLocal = new(); - - /// - /// User Claims ... - /// - /// - public XUserClaimsInfoDto UserInfo => userAsyncLocal.Value; - - /// - /// Connection Id ... - /// - /// - public string ConnectionId => connectionIdAsyncLocal.Value; - - /// - /// Fill Context ... - /// - /// - /// - public void Set( - XUserClaimsInfoDto userInfo, - string connectionId = null - ) - { - // - userAsyncLocal.Value = userInfo; - connectionIdAsyncLocal.Value = connectionId; - } - - /// - /// Clear Context ... - /// - public void Clear() - { - // - userAsyncLocal.Value = null; - connectionIdAsyncLocal.Value = null; - } - - // - #region Static ... - public static XUserClaimsInfoDto CurrentUser => userAsyncLocal.Value; - public static string CurrentConnectionId => connectionIdAsyncLocal.Value; - public static bool IsAuthenticated => userAsyncLocal.Value != null; - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xApi-20261109_152617.txt b/Documents/GeneratedContext/xDashboard-xApi-20261109_152617.txt deleted file mode 100644 index 012fbbe..0000000 --- a/Documents/GeneratedContext/xDashboard-xApi-20261109_152617.txt +++ /dev/null @@ -1,1319 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Program.cs - -using xLoggingService.DI; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace xApi -{ - public class Program - { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - // - var result = Host.CreateDefaultBuilder(args) - .ConfigureLogging(logging => - logging.AddXTelemetryLogger()) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .AddXTelemetry(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Startup.cs - -using System; -using System.IO; -using xServices.DI; -using System.Net.Http; -using Newtonsoft.Json; -using xApi.Extensions; -using xHttpService.DI; -using System.Reflection; -using xLoggingService.DI; -using xCommons.Extensions; -using xDataService.Models; -using xIdentityService.DI; -using xServices.Databases; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.Extensions.Hosting; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Newtonsoft.Json.Serialization; -using Microsoft.Extensions.Configuration; -using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.Extensions.DependencyInjection; -using IdentityModel.AspNetCore.OAuth2Introspection; - -namespace xApi -{ - public class Startup - { - // - public IConfiguration Configuration { get; } - private readonly XApiDatabaseDescriptor apiDatabaseDescriptor; - - public Startup(IConfiguration configuration) - { - // - Configuration = configuration; - - // - // Create an Api Descriptor Class Instance ... - apiDatabaseDescriptor = new XApiDatabaseDescriptor(); - } - - public void ConfigureServices(IServiceCollection services) - { - // - // Register Validation Provider and all XCommons Module Services ... - services.AddXCommons(Configuration); - - // - // Register App Configuration ... - services.AddXAppConfiguration(Configuration); - var appConfiguration = services.GetRegisteredService(); - - // - // Register Logging Service ... - services.AddXLoggingService(Configuration); - - // - // Register Allowed Origins ... - services.AddXCors(appConfiguration.AllowedOrigins); - - // - // Register Swagger ... - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - services.AddXSwagger(Configuration, xmlFilePath: xmlPath); - - // - // Register HttpService ... - services.AddXHttpService(Configuration); - - // - // Add Api V1 Versioning ... - services.AddXApiV1Versioning(); - - // - // OAuthIntrospectin Http Client Handler ... - // this is for handling SSLErrors ... - services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName) - .ConfigurePrimaryHttpMessageHandler(() => - { - return new HttpClientHandler - { - ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true - }; - }); - - // - // Register Authorizations ... - services.AddXAuthorization(); - - // - services.AddControllers() - .AddNewtonsoftJson(x => - { - x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - }); - - // - // Custom ... - - // - services.Configure(options => - { - options.AllowSynchronousIO = true; - }); - - // - services.Configure(options => - { - options.AllowSynchronousIO = true; - }); - - // - // Register Services ... - services.AddXServices( - configuration: Configuration, - databases: new List - { - apiDatabaseDescriptor - }, - lifeTime: ServiceLifetime.Scoped - ); - } - - public void Configure( - IApplicationBuilder app, - IWebHostEnvironment env - ) - { - // - var isDevelopmentEnvironment = env.IsDevelopment(); - if (isDevelopmentEnvironment) - { - app.UseDeveloperExceptionPage(); - } - - // - // Setting Environment in App Confiuration ... - app.AddEnvironmentToXAppConfiguration(env.EnvironmentName); - - // - // Use Swagger Middleware ... - app.UseXSwagger(); - - // - app.UseHttpsRedirection(); - - // - // Using Cors ... - app.UseXCors(); - - // - app.UseRouting(); - - // - // Using Request Logging ... - if (!isDevelopmentEnvironment) - { - app.UseXRequestLogger(); - } - - // - // Enable Api Key Usage Logs ... - // app.UseXApiKeyUsage(); - - // - // Use xIdentityService ... - app.UseXIdentityService(); - - // - app.UseAuthorization(); - - // - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - - // - // Use xDataService Middleware ... - app.UseXServices( - databases: new List - { - apiDatabaseDescriptor - }, - isDevelopmentEnvironment: env.IsDevelopment() - ); - } - } -} - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Controllers\AccountController.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityHelper.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xApi.Controllers -{ - public partial class AccountController : XAccountControllerBase - { - // - #region Constructor ... - public AccountController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Controllers\StartupController.cs - -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using xCommons.Configurations; -using xCommons.Controllers; -using xCommons.Providers; - -namespace xApi.Controllers { - /// - /// Runing when application start ... - /// - [Route ("")] - [AllowAnonymous] - public class StartupController : XBaseController { - - public StartupController ( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base ( - logger, - appConfiguration, - validationProvider - ) { } - - /// - /// Show Configured Welcome Message - /// - /// - [HttpGet ("")] - [AllowAnonymous] - public virtual ActionResult Index () { - // - var controllerName = GetControllerName (); - var message = $"{AppConfiguration.WelcomeMessage}"; - - // - return Ok (message); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Controllers\TestFeaturesController.cs - -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using xCategoryService.Interfaces; -using xCommons.Configurations; -using xCommons.Controllers; -using xCommons.Providers; - -namespace xApi.Controllers -{ - [AllowAnonymous] - public class TestFeaturesController : XBaseApiController - { - private readonly IXSubCategoryTitleResourceProvider subCategoryTitleResourceProvider; - - public TestFeaturesController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXSubCategoryTitleResourceProvider subCategoryTitleResourceProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - this.subCategoryTitleResourceProvider = subCategoryTitleResourceProvider; - } - - [HttpGet] - public async Task TestFeature() - { - // - var result = await subCategoryTitleResourceProvider.GetLanguages( - identifier: "SSSSAAALLLAAAM" - ); - - // - return Ok(result); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Controllers\TestIdentity.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using xIdentityHelper.Controllers; -using Microsoft.Extensions.Logging; - -namespace xApi.Controllers { - /// - /// Test all Authentication Policies ... - /// - public class TestIdentity : XTestIdentityControllerBase { - public TestIdentity ( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base ( - logger, - appConfiguration, - identityProvider, - validationProvider - ) { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Extensions\XStartupExtensions.cs - -using System.Linq; -using xIdentityHelper; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.DependencyInjection; - -namespace xApi.Extensions { - public static class XStartupExtensions { - public static void AddXAuthorization( - this IServiceCollection services, - IDictionary policies = null - ) - { - // - var policyHandler = services.GetRegisteredService(); - services.AddAuthorization(options => - { - // - if (!policies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = policies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - var policyDescriptor = policiesEnumerator.Current; - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - - // - var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); - if (!xPolicies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = xPolicies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - // - var policyDescriptor = policiesEnumerator.Current; - - // - // Add Policy to Authorization ... - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - }); - - // - services.AddSingleton(); - } - - /// - /// Use Forward Headers Options for resolving behind a proxy issues ... - /// - /// - /// - public static void UseXForwardOptions (this IApplicationBuilder source) { - // - var forwardOptions = new ForwardedHeadersOptions { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, - RequireHeaderSymmetry = false - }; - - // - forwardOptions.KnownNetworks.Clear (); - forwardOptions.KnownProxies.Clear (); - - // - // ref: https://github.com/aspnet/Docs/issues/2384 - source.UseForwardedHeaders (forwardOptions); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Extensions\XUserClaimsInfoDtoExtensions.cs - -using xCommons.Extensions; -using xIdentityModels.Constants; -using xIdentityModels.Models; - -namespace xApi.Extensions { - public static class XUserClaimsInfoDtoExtensions { - public static string GetUserSelectByParam ( - this XUserClaimsInfoDto source, - XUserSelectBy userSelectBy = XUserSelectBy.Username - ) { - // - var result = ""; - - // - switch (userSelectBy) { - // - case XUserSelectBy.ID: - result = source.UserId; - break; - - // - case XUserSelectBy.Username: - result = source.UserName; - break; - - // - case XUserSelectBy.Email: - result = source.Email; - break; - - // - case XUserSelectBy.MobileNumber: - result = source.PhoneNumber; - break; - } - - // - if (result.IsNullOrEmpty ()) { - // - if (!source.UserId.IsNullOrEmpty ()) { - result = source.UserId; - } else if (!source.UserName.IsNullOrEmpty ()) { - result = source.UserName; - } else if (!source.Email.IsNullOrEmpty ()) { - result = source.Email; - } else if (!source.PhoneNumber.IsNullOrEmpty ()) { - result = source.PhoneNumber; - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Migrations\20260906032546_InitialMigration.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xApi.Migrations -{ - public partial class InitialMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Categories", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Title = table.Column(nullable: true), - Description = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Categories", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Contents", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 255, nullable: true), - CreatedOn = table.Column(nullable: false), - UpdatedAt = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Contents", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Files", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Type = table.Column(nullable: false), - OwnerId = table.Column(maxLength: 255, nullable: false), - Name = table.Column(maxLength: 255, nullable: false), - Path = table.Column(nullable: false), - Thumb = table.Column(nullable: true), - ThumbPath = table.Column(nullable: true), - UploadedOn = table.Column(nullable: false), - FileName = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Files", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Strings", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Language = table.Column(maxLength: 10, nullable: false), - ResourceTitle = table.Column(maxLength: 255, nullable: false), - TranslatedValue = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Strings", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "SubCategories", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Title = table.Column(nullable: true), - Description = table.Column(nullable: true), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_SubCategories", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tags", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - Tag = table.Column(maxLength: 255, nullable: false), - References = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Tags", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tests", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Firstname = table.Column(nullable: true), - Lastname = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Tests", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Webinars", - columns: table => new - { - Id = table.Column(nullable: false), - Deleted = table.Column(nullable: false), - Title = table.Column(maxLength: 255, nullable: false), - Description = table.Column(maxLength: 255, nullable: false), - OwnerId = table.Column(nullable: false), - Type = table.Column(nullable: false), - CreatedOn = table.Column(nullable: false), - Enabled = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Webinars", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "WebinarSubscribers", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Deleted = table.Column(nullable: false), - SubscriberId = table.Column(nullable: false), - WebinarId = table.Column(nullable: false), - SubscribedOn = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_WebinarSubscribers", x => x.Id); - }); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Categories"); - - migrationBuilder.DropTable( - name: "Contents"); - - migrationBuilder.DropTable( - name: "Files"); - - migrationBuilder.DropTable( - name: "Strings"); - - migrationBuilder.DropTable( - name: "SubCategories"); - - migrationBuilder.DropTable( - name: "Tags"); - - migrationBuilder.DropTable( - name: "Tests"); - - migrationBuilder.DropTable( - name: "Webinars"); - - migrationBuilder.DropTable( - name: "WebinarSubscribers"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Migrations\20260906032546_InitialMigration.Designer.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xServices.Databases; - -namespace xApi.Migrations -{ - [DbContext(typeof(XApiDbContext))] - [Migration("20260906032546_InitialMigration")] - partial class InitialMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xCategoryService.Models.Entities.XCategory", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Categories"); - }); - - modelBuilder.Entity("xCategoryService.Models.Entities.XSubCategory", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("SubCategories"); - }); - - modelBuilder.Entity("xContentService.Models.Entities.XContent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Contents"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xServices.Models.Entities.XTest", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Firstname") - .HasColumnType("TEXT"); - - b.Property("Lastname") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Tests"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); - - modelBuilder.Entity("xWebinarService.Models.Entities.XWebinar", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.ToTable("Webinars"); - }); - - modelBuilder.Entity("xWebinarService.Models.Entities.XWebinarSubscriber", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("SubscribedOn") - .HasColumnType("TEXT"); - - b.Property("SubscriberId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("WebinarId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("WebinarSubscribers"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xApi\Migrations\XApiDbContextModelSnapshot.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xServices.Databases; - -namespace xApi.Migrations -{ - [DbContext(typeof(XApiDbContext))] - partial class XApiDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "3.1.14"); - - modelBuilder.Entity("xCategoryService.Models.Entities.XCategory", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Categories"); - }); - - modelBuilder.Entity("xCategoryService.Models.Entities.XSubCategory", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("SubCategories"); - }); - - modelBuilder.Entity("xContentService.Models.Entities.XContent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Contents"); - }); - - modelBuilder.Entity("xFileService.Models.Entities.XFile", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("FileName") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Path") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Thumb") - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UploadedOn") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Files"); - }); - - modelBuilder.Entity("xServices.Models.Entities.XTest", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Firstname") - .HasColumnType("TEXT"); - - b.Property("Lastname") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Tests"); - }); - - modelBuilder.Entity("xStringService.Models.Entities.XString", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Language") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(10); - - b.Property("ResourceTitle") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("TranslatedValue") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Strings"); - }); - - modelBuilder.Entity("xTagService.Models.Entities.XTag", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("References") - .HasColumnType("TEXT"); - - b.Property("Tag") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.HasKey("Id"); - - b.ToTable("Tags"); - }); - - modelBuilder.Entity("xWebinarService.Models.Entities.XWebinar", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("OwnerId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Title") - .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.ToTable("Webinars"); - }); - - modelBuilder.Entity("xWebinarService.Models.Entities.XWebinarSubscriber", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("SubscribedOn") - .HasColumnType("TEXT"); - - b.Property("SubscriberId") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("WebinarId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("WebinarSubscribers"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261109_153852.txt b/Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261112_120913.txt similarity index 96% rename from Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261109_153852.txt rename to Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261112_120913.txt index b87c0aa..2dd2678 100644 --- a/Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261109_153852.txt +++ b/Documents/GeneratedContext/xDashboard-xApiSDKHolder-20261112_120913.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\public-api.ts /* * Public API Surface of x-framework-api-sdk @@ -101,7 +101,7 @@ export * from './lib/x-saherelm-api.service'; // Module ... export * from './lib/x-saherelm-api-sdk.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\x-saherelm-api-sdk.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\x-saherelm-api-sdk.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -130,7 +130,7 @@ import { XFrameworkIdentitySdkModule } from 'x-framework-identity-sdk'; }) export class XSaherElmApiSdkModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\x-saherelm-api.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\x-saherelm-api.service.ts import { XLoggable } from 'x-framework-core'; import { Inject, Injectable } from '@angular/core'; @@ -163,7 +163,7 @@ export class XSaherElmAPIService extends XLoggable { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\i-x-entity-actions.interface.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\i-x-entity-actions.interface.ts import { Observable } from 'rxjs'; import { XBaseRangeRequestDto } from 'x-framework-core'; @@ -638,7 +638,7 @@ export interface IXEntityActions { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\x-base-entity.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\x-base-entity.service.ts import { XQueryDto, @@ -1437,7 +1437,7 @@ export abstract class XBaseEntityService //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\x-base.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\base\x-base.guard.ts import { Route, @@ -1551,7 +1551,7 @@ export abstract class XBaseGuard //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\config\x-saherelm-api-sdk.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\config\x-saherelm-api-sdk.config.ts import { XFrameworkCoreConfig } from 'x-framework-core'; import { XFrameworkServicesConfig } from 'x-framework-services'; @@ -1573,7 +1573,7 @@ export interface XSaherElmApiSDKConfig extends XSharedConfig { corsBypasserProxy: string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\configurations\x-configurations.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\configurations\x-configurations.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable, Inject } from '@angular/core'; @@ -1606,7 +1606,7 @@ export class XConfigurationsService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\x-file.services.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\x-file.services.ts import { Injectable } from '@angular/core'; import { XFileEntityService } from './services/x-file.entity.service'; @@ -1630,7 +1630,7 @@ export class XFileServices { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\x-file.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\x-file.typings.ts /** * All Available EndPoint Routes ... @@ -1662,7 +1662,7 @@ export enum XFileParam { Files = 'files', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\models\x-file.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\models\x-file.dto.ts import { XBaseDto, @@ -1868,7 +1868,7 @@ export function fileEntityToDto( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.entity.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.entity.push.service.ts import { Injectable } from "@angular/core"; import { XFileEntity } from "../models/x-file.dto"; @@ -1895,7 +1895,7 @@ export class XFileEntityPushService extends XBaseEntityPushService //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.entity.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.entity.service.ts import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @@ -1937,7 +1937,7 @@ export class XFileEntityService extends XBaseEntityService< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.provider.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\files\services\x-file.provider.service.ts import { toArray, @@ -2948,7 +2948,7 @@ export class XFileProviderService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\admin-or-agent.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\admin-or-agent.guard.ts import { Injectable } from '@angular/core'; import { XBaseGuard } from '../base/x-base.guard'; @@ -2964,7 +2964,7 @@ export class AdminOrAgentGuard extends XBaseGuard { ]; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\admin.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\admin.guard.ts import { Injectable } from '@angular/core'; import { XBaseGuard } from '../base/x-base.guard'; @@ -2977,7 +2977,7 @@ export class AdminGuard extends XBaseGuard { roles = XAvailableRoles.Admin; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\agent.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\agent.guard.ts import { Injectable } from '@angular/core'; import { XBaseGuard } from '../base/x-base.guard'; @@ -2990,7 +2990,7 @@ export class AgentGuard extends XBaseGuard { roles = XAvailableRoles.Agent; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\user.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\guards\user.guard.ts import { Injectable } from '@angular/core'; import { XBaseGuard } from '../base/x-base.guard'; @@ -3003,7 +3003,7 @@ export class UserGuard extends XBaseGuard { roles = XAvailableRoles.User; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\models\x-person.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\models\x-person.dto.ts import { XBaseDto, @@ -3086,7 +3086,7 @@ export const isXPersonDto = typeGuard([ 'lastname', ]); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\models\x-reference.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\models\x-reference.dto.ts import { nameof, @@ -3302,7 +3302,7 @@ export function references2String( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\services\x-push-token-fetcher.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\services\x-push-token-fetcher.service.ts import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @@ -3360,7 +3360,7 @@ export class XPushTokenFetcherService } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\x-string.services.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\x-string.services.ts import { Injectable } from '@angular/core'; import { XStringEntityService } from './services/x-string.entity.service'; @@ -3384,7 +3384,7 @@ export class XStringServices { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\x-string.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\x-string.typings.ts /** * All Available EndPoint Routes ... @@ -3438,7 +3438,7 @@ export enum XStringParam { Language = 'language', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\models\x-string.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\models\x-string.dto.ts import { XBaseDto, @@ -3633,7 +3633,7 @@ export const isXStringDto = typeGuard([ 'translatedValue', ]); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.entity.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.entity.push.service.ts import { Injectable } from '@angular/core'; import { XStringDto } from '../models/x-string.dto'; @@ -3660,7 +3660,7 @@ export class XStringEntityPushService extends XBaseEntityPushService //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.entity.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.entity.service.ts import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @@ -3702,7 +3702,7 @@ export class XStringEntityService extends XBaseEntityService< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.provider.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\strings\services\x-string.provider.service.ts import { HttpEvent, @@ -5547,7 +5547,7 @@ export class XStringProviderService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\x-tag.services.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\x-tag.services.ts import { Injectable } from '@angular/core'; import { XTagEntityService } from './services/x-tag.entity.service'; @@ -5571,7 +5571,7 @@ export class XTagServices { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\x-tag.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\x-tag.typings.ts /** * All Available EndPoint Routes ... @@ -5597,7 +5597,7 @@ export enum XTagParam { Query = 'query' } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\models\x-tag.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\models\x-tag.dto.ts import { hasChild, @@ -5738,7 +5738,7 @@ export function tagEntity2Dto(value: XTagEntity) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.entity.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.entity.push.service.ts import { Injectable } from '@angular/core'; import { XTagEntity } from '../models/x-tag.dto'; @@ -5773,7 +5773,7 @@ export class XTagEntityPushService extends XBaseEntityPushService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.entity.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.entity.service.ts import { Router } from '@angular/router'; import { XTagEntity } from '../models/x-tag.dto'; @@ -5815,7 +5815,7 @@ export class XTagEntityService extends XBaseEntityService< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.provider.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tags\services\x-tag.provider.service.ts import { toArray, @@ -6472,7 +6472,7 @@ export class XTagProviderService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\x-terms.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\x-terms.service.ts import { Injectable } from '@angular/core'; import { XTermsPushService } from './services/x-terms.push.service'; @@ -6494,7 +6494,7 @@ export class XTermsServices { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\x-terms.typings.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\x-terms.typings.dto.ts /** * All Available EndPoint Routes ... @@ -6516,7 +6516,7 @@ export enum XTermsParam { Language = 'language', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\services\x-terms.provider.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\services\x-terms.provider.service.ts import { HttpEvent, @@ -7026,7 +7026,7 @@ export class XTermsProviderService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\services\x-terms.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\terms\services\x-terms.push.service.ts import { Subject } from 'rxjs'; import { @@ -7198,7 +7198,7 @@ export class XTermsPushService extends XBasePushService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tokens\x-injectable-tokens.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tokens\x-injectable-tokens.ts import { InjectionToken } from '@angular/core'; import { XSaherElmApiSDKConfig } from '../config/x-saherelm-api-sdk.config'; @@ -7207,7 +7207,7 @@ export const X_SAHERELM_API_SDK_CONFIG = new InjectionToken(model: T) { return model; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tools\x-role.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tools\x-role.tools.ts import { toArray, @@ -7521,7 +7521,7 @@ export function extractAvaialableRoles() { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tools\x-route.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\tools\x-route.tools.ts import { hasChild, @@ -7562,7 +7562,7 @@ export function fillRouteParams( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-endpoint.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-endpoint.typings.ts // //#region Custom Header and Params ... @@ -7656,7 +7656,7 @@ export enum XConfigurationEndPoint { export type XConfigurationEndPoints = keyof typeof XConfigurationEndPoint; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-push-provider.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-push-provider.typings.ts import { HttpHeaders } from '@angular/common/http'; import { isNullOrEmptyString, isNullOrUndefined } from 'x-framework-core'; @@ -7692,7 +7692,7 @@ export function applyConnectionIdToHeader( return headers; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-role.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\typings\x-role.typings.ts export enum XAvailableRoles { Admin = 'admin', @@ -7722,7 +7722,7 @@ export interface XUserRoleInfo { isUser: boolean; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\x-webinar.services.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\x-webinar.services.ts import { Injectable } from '@angular/core'; import { XWebinarPushService } from './services/x-webinar.push.service'; @@ -7750,7 +7750,7 @@ export class XWebinarServices { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\x-webinar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\x-webinar.typings.ts /** * All Available EndPoint Routes ... @@ -7835,7 +7835,7 @@ export enum XWebinarEntityPushAction { Unsubscribe = 'Unsubscribe', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\models\x-webinar.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\models\x-webinar.dto.ts import { XBaseDto, @@ -8037,7 +8037,7 @@ export const isXWebinarDto = typeGuard([ 'title', ]); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\services\x-webinar.entity.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xApiSDKHolder\projects\x-saherelm-api-sdk\src\lib\webinars\services\x-webinar.entity.push.service.ts import { Subject } from 'rxjs'; import { Injectable } from '@angular/core'; @@ -8207,7 +8207,7 @@ export class XWebinarEntityPushService extends XBaseEntityPushService - /// Bot User / System User Relation ... - /// - public class XBotUserDto : XBaseIntIDEntityDto - { - /// - /// User Id ... - /// - /// - public string UserId { get; set; } - - /// - /// System Person Information ... - /// - /// - public virtual XPersonDto User { get; set; } = null; - - /// - /// Chat Bot User Name ... - /// - /// - public string BotUserName { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Models\Entities\XBotUser.cs - -using xModels.Base; - -namespace xBotService.Models.Entities -{ - /// - /// Bot User / System User Relation ... - /// - public class XBotUser : XBaseIntIDEntity - { - /// - /// User Id ... - /// - /// - public string UserId { get; set; } - - /// - /// Chat Bot User Name ... - /// - /// - public string BotUserName { get; set; } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xBotService-20261111_153912.txt b/Documents/GeneratedContext/xDashboard-xBotService-20261111_153912.txt deleted file mode 100644 index b747b8b..0000000 --- a/Documents/GeneratedContext/xDashboard-xBotService-20261111_153912.txt +++ /dev/null @@ -1,1011 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Configuration\Entities\XBotUserEntityConfiguration.cs - -using xBotService.Constants; -using xDataService.Providers; -using xBotService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xBotService.Configuration.Entities -{ - public class XBotUserEntityConfiguration: XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XBotServiceConstants.XBotUserTable); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Constants\ConfigurationNodeNames.cs - -namespace xBotService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string BOT_SERVICE_NODE = "BotServiceConfiguration"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Constants\XBotServiceConstants.cs - -namespace xBotService.Constants -{ - public struct XBotServiceConstants - { - // - // Bot Service Log Tag ... - public const string XBotServiceDILogTag = "XBotService"; - - // - // Table Mapping ... - public const string XBotUserTable = "BotUsers"; - - // - // GraphQL Mappings ... - public const string XBotUserSingleName = "botUser"; - public const string XBotUserCollectionName = "botUsers"; - - // - // Hubs ... - public const string XBotUserDtoHub = "botUserDto"; - public const string XBotUserEntityHub = "botUserEntity"; - - // - // Helper Method Names ... - public const string GetXBotUserEFRepositoryDescriptor = "GetXBotUserEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using xBotService.Constants; -using xDataService.Constants; -using XBotUserService.Helpers; -using xHttpService.Interfaces; -using xBotService.Providers.Dtos; -using Microsoft.AspNetCore.Builder; -using xBotService.Interfaces.Entities.Dtos; -using Microsoft.Extensions.DependencyInjection; - -namespace xBotService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register XBotService - /// - public static void AddXBotService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddBotService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register XBotService with Context - /// - public static void AddXBotService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) where TContext : XDbContext - { - AddBotService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XBotService Middleware - /// - public static void UseXBotService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // Using XBot Repository Descriptor - if (!descriptor.IsNull()) - { - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - private static string XLogTag = XBotServiceConstants.XBotServiceDILogTag; - - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - private static void AddBotService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); - - // - // Validate Services - if (services.IsNull()) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Check Requirements ... - var httpService = services.GetRegisteredService(); - if (httpService.IsNull()) - { - // - Log("Service Registration failed, HttpService not provided ..."); - throw exception; - } - - // - // Validate Repository Type - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || repositoryType == XRepositoryType.InMemory) && contextType.IsNull()); - if (!isRepositoryTypeValid) - { - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Make Instance of Repository Descriptor - switch (repositoryType) - { - case XRepositoryType.EF: - descriptor = typeof(XBotServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XBotServiceConstants.GetXBotUserEFRepositoryDescriptor - ); - break; - case XRepositoryType.Mongo: - // descriptor = XBotServiceHelper.GetXBotUserMongoRepositoryDescriptor(); - Log("MongoDB support not implemented yet for XBotService."); - break; - case XRepositoryType.InMemory: - // descriptor = XBotServiceHelper.GetXBotUserInMemoryRepositoryDescriptor(); - Log("InMemory support not implemented yet for XBotService."); - break; - } - - // - // Register XBotUser Repository Descriptor - if (!descriptor.IsNull()) - { - services.AddXRepository(lifeTime: lifeTime, descriptor: descriptor); - } - - // - // Register Dto Services - services.Add(new ServiceDescriptor(typeof(IXBotUserRepositoryService), typeof(XBotUserRepositoryService), lifeTime)); - Log("XBotService Registration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Helper\XBotServiceHelper.cs - -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xBotService.Models.Entities; -using xBotService.Providers.GraphQL; -using xBotService.Providers.Entities; -using xBotService.Interfaces.Entities; - -namespace XBotUserService.Helpers -{ - public static class XBotServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserEFRepository, - TContext - > GetXBotUserEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserEFRepository, - TContext, - IXBotUserSeeder, - TSeederImplementation - > GetXBotUserEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserEFRepository, - TContext, - IXBotUserSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserMongoRepository - > GetXBotUserMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserMongoRepository, - IXBotUserSeeder, - TSeederImplementation - > GetXBotUserMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserMongoRepository, - IXBotUserSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserInMemoryRepository - > GetXBotUserInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserInMemoryRepository, - IXBotUserSeeder, - TSeederImplementation - > GetXBotUserInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XBotUser, - int, - IXBotUserKeyGenerator, - XBotUserKeyGenerator, - IXBotUserRepositoryEvents, - XBotUserRepositoryEvents, - XBotUserGraphType, - IntGraphType, - XBotUserGraphQuery, - IXBotUserGraphQLTypeHelper, - XBotUserGraphQLTypeHelper, - XBotUserGraphSchema, - IXBotUserRepository, - XBotUserInMemoryRepository, - IXBotUserSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Dtos\IXBotUserDtoHub.cs - -using xBotService.Models.Dtos; -using xPushService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Dtos -{ - public interface IXBotUserDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Dtos\IXBotUserRepositoryService.cs - -using xBotService.Models.Dtos; -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities.Dtos -{ - public interface IXBotUserRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Dtos\IXBotUserServiceProvider.cs - -using xBotService.Models.Dtos; -using xPushService.Interfaces; -using xBotService.Models.Entities; -using xBotService.Providers.Dtos; - -namespace xBotService.Interfaces.Dtos -{ - public interface IXBotUserServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserEntityHub.cs - -using xPushService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserKeyGenerator.cs - -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserRepository.cs - -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserRepositoryEvents.cs - -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserRepositoryProvider.cs - -using xPushService.Interfaces; -using xBotService.Models.Entities; -using xBotService.Providers.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Interfaces\Entities\IXBotUserSeeder.cs - -using xDataService.Interfaces; -using xBotService.Models.Entities; - -namespace xBotService.Interfaces.Entities -{ - public interface IXBotUserSeeder: IXBaseDbSeeder - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Models\Dtos\XBotUserDto.cs - -using xModels.Base; -using xModels.Dtos; - -namespace xBotService.Models.Dtos -{ - /// - /// Bot User / System User Relation ... - /// - public class XBotUserDto : XBaseIntIDEntityDto - { - /// - /// User Id ... - /// - /// - public string UserId { get; set; } - - /// - /// System Person Information ... - /// - /// - public virtual XPersonDto User { get; set; } = null; - - /// - /// Chat Bot User Name ... - /// - /// - public string BotUserName { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Models\Entities\XBotUser.cs - -using xModels.Base; - -namespace xBotService.Models.Entities -{ - /// - /// Bot User / System User Relation ... - /// - public class XBotUser : XBaseIntIDEntity - { - /// - /// User Id ... - /// - /// - public string UserId { get; set; } - - /// - /// Chat Bot User Name ... - /// - /// - public string BotUserName { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\XBotUserEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using xBotService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xBotService.Configuration.Entities; - -namespace xBotService.Providers -{ - public class XBotUserEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XBotUserEntityRegisterar() - : base(nameof(XBotUserEntityRegisterar)) - { - // - // Add XBotUser Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XBotUserEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Dtos\XBotUserDtoHub.cs - -using xPushService.Base; -using xBotService.Models.Dtos; -using xBotService.Interfaces.Dtos; -using xBotService.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xBotService.Providers.Dtos -{ - public class XBotUserDtoHub : XBaseDtoHub, IXBotUserDtoHub - { - public XBotUserDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Dtos\XBotUserRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using xBotService.Models.Dtos; -using xBotService.Models.Entities; -using System.Collections.Generic; -using xBotService.Interfaces.Entities; -using xBotService.Interfaces.Entities.Dtos; - -namespace xBotService.Providers.Dtos -{ - public class XBotUserRepositoryService : XBaseRepositoryService, IXBotUserRepositoryService - { - public XBotUserRepositoryService( - IXBotUserRepository repository, - IEnumerable mapperProfiles = null - ) : base(repository, mapperProfiles) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Dtos\XBotUserServiceProvider.cs - -using xPushService.Base; -using xBotService.Models.Dtos; -using xDataService.Configuration; -using xBotService.Interfaces.Dtos; -using xBotService.Models.Entities; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xBotService.Interfaces.Entities.Dtos; - -namespace xBotService.Providers.Dtos -{ - public class XBotUserServiceProvider : XBaseDtoProvider, IXBotUserServiceProvider - { - public XBotUserServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXBotUserRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserEFRepository : XBaseEFRepository, IXBotUserRepository - where TContext : XDbContext - { - public XBotUserEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXBotUserKeyGenerator keyGenerator = null, - IXBotUserRepositoryEvents baseRepositoryEvents = null - ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserEntityHub.cs - -using xPushService.Base; -using xBotService.Models.Entities; -using Microsoft.Extensions.Logging; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserEntityHub : XBaseEntityHub, IXBotUserEntityHub - { - public XBotUserEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserInMemoryRepository : XBaseInMemoryRepository, IXBotUserRepository - { - public XBotUserInMemoryRepository( - XDataServiceConfiguration configuration, - IXBotUserKeyGenerator keyGenerator = null, - IXBotUserRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserKeyGenerator.cs - -using xDataService.Providers; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserKeyGenerator : XIntKeyGenerator, IXBotUserKeyGenerator - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserMongoRepository : XBaseMongoRepository, IXBotUserRepository - { - public XBotUserMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXBotUserKeyGenerator keyGenerator = null, - IXBotUserRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserRepositoryEvents.cs - -using xDataService.Providers; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public class XBotUserRepositoryEvents : XBaseRepositoryEvents, IXBotUserRepositoryEvents - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\Entities\XBotUserSeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.Entities -{ - public abstract class XBotUserSeederBase : XBaseDbSeeder, IXBotUserSeeder - { - protected XBotUserSeederBase( - string entity, - string database, - IXBotUserRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\GraphQL\XBotUserGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; -using xBotService.Constants; - -namespace xBotService.Providers.GraphQL -{ - public class XBotUserGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXBotUserGraphQLTypeHelper - { - public XBotUserGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) - : base(configuration) - { - } - - public override string GetInQueryCollectionName() - { - return XBotServiceConstants.XBotUserCollectionName; - } - - public override string GetInQuerySingleName() - { - return XBotServiceConstants.XBotUserSingleName; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\GraphQL\XBotUserGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xBotService.Models.Entities; -using xBotService.Interfaces.Entities; - -namespace xBotService.Providers.GraphQL -{ - public class XBotUserGraphQuery : XBaseGraphQLQuery - { - public XBotUserGraphQuery( - XDataServiceConfiguration configuration, - IXBotUserRepository repository, - IXBotUserGraphQLTypeHelper helper - ) : base(configuration, repository, helper) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\GraphQL\XBotUserGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xBotService.Providers.GraphQL -{ - public class XBotUserGraphSchema : Schema - { - public XBotUserGraphSchema(IServiceProvider services) : base(services) - { - Query = (XBotUserGraphQuery)services.GetService(typeof(XBotUserGraphQuery)); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xBotService\Providers\GraphQL\XBotUserGraphType.cs - -using xDataService.GraphQL; -using xBotService.Models.Entities; - -namespace xBotService.Providers.GraphQL -{ - public class XBotUserGraphType : XBaseGraphObjectType - { - public XBotUserGraphType() : base() - { - Field(x => x.UserId); - Field(x => x.BotUserName); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xCategoryService-20261109_152622.txt b/Documents/GeneratedContext/xDashboard-xCategoryService-20261109_152622.txt deleted file mode 100644 index 63d4a30..0000000 --- a/Documents/GeneratedContext/xDashboard-xCategoryService-20261109_152622.txt +++ /dev/null @@ -1,10095 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Configurations\XCategoryServiceConfiguration.cs - -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Configurations -{ - /// - /// a Configuration Class for Providing Data to Configure XCategoryService ... - /// - public class XCategoryServiceConfiguration - { - /// - /// a List of Categories for Seeding ... - /// - public XCategoryResourceDto[] Categories { get; set; } = []; - - /// - /// a List of SubCategories for Seeding ... - /// - public XSubCategoryResourceDto[] SubCategories { get; set; } = []; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Configurations\Entities\XCategoryEntityConfiguration.cs - -using xDataService.Providers; -using xCategoryService.Constants; -using Microsoft.EntityFrameworkCore; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xCategoryService.Configurations.Entities -{ - public class XCategoryEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XCategoryServiceConstants.XCategoryTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Configurations\Entities\XSubCategoryEntityConfiguration.cs - -using xDataService.Providers; -using xCategoryService.Constants; -using Microsoft.EntityFrameworkCore; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xCategoryService.Configurations.Entities -{ - public class XSubCategoryEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XCategoryServiceConstants.XSubCategoryTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Constants\ConfigurationNodeNames.cs - -namespace xCategoryService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string CATEGORY_SERVICE_NODE = "CategoryServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Constants\XCategoryServiceConstants.cs - -namespace xCategoryService.Constants -{ - public struct XCategoryServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XCategoryServiceDILogTag = "XCategoryService"; - - // - // Table Mapping Identifiers ... - public const string XCategoryTable = "Categories"; - public const string XSubCategoryTable = "SubCategories"; - - // - // GraphQL Collection Mappings ... - public const string XCategorySingleName = "category"; - public const string XCategoryCollectionName = "categories"; - public const string XSubCategorySingleName = "subCategory"; - public const string XSubCategoryCollectionName = "subCategories"; - - // - // Hubs ... - public const string XCategoryDtoHub = "categoryDto"; - public const string XCategoryEntityHub = "categoryEntity"; - public const string XSubCategoryDtoHub = "subCategoryDto"; - public const string XSubCategoryEntityHub = "subCategoryEntity"; - - // - // Custome Constants ... - public const string SubCategoryReference = "SubCat"; - public const string CategoryTitleResourceIdentifier = "CatT"; - public const string CategoryDescriptionResourceIdentifier = "CatD"; - public const string SubCategoryTitleResourceIdentifier = "SubCatT"; - public const string SubCategoryDescriptionResourceIdentifier = "SubCatD"; - - // - // EF Repositories Helper Extensions ... - public const string GetXCategoryEFRepositoryDescriptor = "GetXCategoryEFRepositoryDescriptor"; - public const string GetXSubCategoryEFRepositoryDescriptor = "GetXSubCategoryEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XCategoryProviderControllerBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xPushService.Controllers; -using System.Collections.Generic; -using xCategoryService.Interfaces; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XCategoryProviderControllerBase : XBaseProvidedController, IXCategoryProviderController - { - private readonly IXCategoryProvider provider; - - protected XCategoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXCategoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { - this.provider = provider; - } - - // - #region Overrides ... - [NonAction] - [HttpGet("{id}")] - public override async Task> Get( - [FromRoute] int id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.Get( - id: id, - useDefaultIncludes: useDefaultIncludes, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpGet("")] - public override async Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.GetAll( - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Find/One")] - public override async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.FindOne( - query: query, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Find/Many")] - public override async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.FindMany( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Query")] - public override async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.Query( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Query/Owned")] - public override async Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.QueryOwned( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpPost("")] - public override async Task> Add( - [FromBody] XCategoryDto item, - CancellationToken cancellationToken = default - ) - { - // - return await base.Add( - item: item, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpPut("{id}")] - public override async Task> Update( - [FromRoute] int id, - [FromBody] XCategoryDto item, - CancellationToken cancellationToken = default - ) - { - // - return await base.Update( - id: id, - item: item, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpDelete("{id}")] - public override async Task> Remove( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - return await base.Remove( - id: id, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Actions ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - [HttpGet("Resources/{id}/HasLocale")] - public virtual async Task> HasLocale( - [FromRoute] int id, - [FromQuery] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(language); - - // - var result = await provider.HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - [HttpGet("Resources/{id}")] - public virtual async Task> GetResource( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Category Item for Specified Language ... - /// - /// - /// - /// - /// - [HttpPost("Resources")] - public virtual async Task> Add( - [FromBody] XCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotEmpty(language) - .AddNotEmpty(item.Title) - .AddNotEmpty(item.Description) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Add( - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Category Item for by It's Locales ... - /// - /// - /// - /// - [HttpPost("Resources/AddResource")] - public virtual async Task> AddResource( - [FromBody] XCategoryResourceDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(item.Titles) - .AddNotZeroChilds(item.Titles.Locales) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.AddResource( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - [HttpDelete("Resources/{id}")] - public virtual async Task> Remove( - [FromRoute] int id, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - id: id, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Category Item for Specified Language ... - /// - /// - /// - /// - /// - /// - [HttpPut("Resources/{id}")] - public virtual async Task> Update( - [FromRoute] int id, - [FromBody] XCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotEmpty(language) - .AddNotEmpty(item.Title) - .AddNotEmpty(item.Description) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Update( - id: id, - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - [HttpPost("Resources/Refresh")] - public virtual async Task> Refresh( - [FromBody] XCategoryResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(resource) - .AddNotNull(resource.Item) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Resources ... - /// - /// - /// - [HttpGet("Resources/All")] - public virtual async Task>> GetAllResources( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetAllResources( - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/One")] - public virtual async Task> FindOneResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindOneResource( - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/Many")] - public virtual async Task>> FindManyResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindManyResource( - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query), - orderBuilder: x => x.OrderBy(y => y.Item.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - [HttpGet("Resources/Query")] - public virtual async Task>> QueryResources( - [FromQuery] XQuery query = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var result = await provider.QueryResources( - query: query, - predicate: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Item.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XCategoryRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Controllers -{ - public abstract class XCategoryRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XCategoryRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXCategoryRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XCategoryRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xCategoryService.Providers.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Controllers -{ - public abstract class XCategoryRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XCategoryRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXCategoryRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XCategoryServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XCategoryServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XCategoryServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXCategoryRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XCategoryServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XCategoryServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XCategoryServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXCategoryServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XSubCategoryProviderControllerBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xPushService.Controllers; -using System.Collections.Generic; -using xCategoryService.Interfaces; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XSubCategoryProviderControllerBase : XBaseProvidedController, IXSubCategoryProviderController - { - private readonly IXSubCategoryProvider provider; - - protected XSubCategoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXSubCategoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { - this.provider = provider; - } - - // - #region Overrides ... - [NonAction] - [HttpGet("{id}")] - public override async Task> Get( - [FromRoute] int id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.Get( - id: id, - useDefaultIncludes: useDefaultIncludes, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpGet("")] - public override async Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.GetAll( - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Find/One")] - public override async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.FindOne( - query: query, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Find/Many")] - public override async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.FindMany( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Query")] - public override async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.Query( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpGet("Query/Owned")] - public override async Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - return await base.QueryOwned( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - useDefaultIncludes: useDefaultIncludes - ); - } - - [NonAction] - [HttpPost("")] - public override async Task> Add( - [FromBody] XSubCategoryDto item, - CancellationToken cancellationToken = default - ) - { - // - return await base.Add( - item: item, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpPut("{id}")] - public override async Task> Update( - [FromRoute] int id, - [FromBody] XSubCategoryDto item, - CancellationToken cancellationToken = default - ) - { - // - return await base.Update( - id: id, - item: item, - cancellationToken: cancellationToken - ); - } - - [NonAction] - [HttpDelete("{id}")] - public override async Task> Remove( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - return await base.Remove( - id: id, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Actions ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - [HttpGet("Resources/{id}/HasLocale")] - public virtual async Task> HasLocale( - [FromRoute] int id, - [FromQuery] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(language); - - // - var result = await provider.HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - [HttpGet("Resources/{id}")] - public virtual async Task> GetResource( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Category Item for Specified Language ... - /// - /// - /// - /// - /// - [HttpPost("Resources")] - public virtual async Task> Add( - [FromBody] XSubCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotEmpty(language) - .AddNotEmpty(item.Title) - .AddNotEmpty(item.Description) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Add( - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - [HttpPost("Resources/AddResource")] - public virtual async Task> AddResource( - [FromBody] XSubCategoryResourceDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(item.Titles) - .AddNotZeroChilds(item.Titles.Locales) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.AddResource( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - [HttpDelete("Resources/{id}")] - public virtual async Task> Remove( - [FromRoute] int id, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - id: id, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Category Item for Specified Language ... - /// - /// - /// - /// - /// - /// - [HttpPut("Resources/{id}")] - public virtual async Task> Update( - [FromRoute] int id, - [FromBody] XSubCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid || - !id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotEmpty(language) - .AddNotEmpty(item.Title) - .AddNotEmpty(item.Description) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Update( - id: id, - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - [HttpPost("Resources/Refresh")] - public virtual async Task> Refresh( - [FromBody] XSubCategoryResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(resource) - .AddNotNull(resource.Item) - .ValidateGroupAsync(); - - // - // Reading Requirements ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Resources ... - /// - /// - /// - [HttpGet("Resources/All")] - public virtual async Task>> GetAllResources( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetAllResources( - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/One")] - public virtual async Task> FindOneResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindOneResource( - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/Many")] - public virtual async Task>> FindManyResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindManyResource( - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query), - orderBuilder: x => x.OrderBy(y => y.Item.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - [HttpGet("Resources/Query")] - public virtual async Task>> QueryResources( - [FromQuery] XQuery query = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var result = await provider.QueryResources( - query: query, - predicate: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Item.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XSubCategoryRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Controllers -{ - public abstract class XSubCategoryRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XSubCategoryRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXSubCategoryRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XSubCategoryRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xCategoryService.Providers.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Controllers -{ - public abstract class XSubCategoryRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XSubCategoryRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXSubCategoryRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XSubCategoryServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XSubCategoryServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XSubCategoryServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXSubCategoryRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Controllers\XSubCategoryServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xCategoryService.Controllers -{ - public abstract class XSubCategoryServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XSubCategoryServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXSubCategoryServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xPushService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xCategoryService.Helpers; -using xCategoryService.Constants; -using xCategoryService.Providers; -using xCategoryService.Interfaces; -using Microsoft.AspNetCore.Builder; -using xCategoryService.Configurations; -using xCategoryService.Providers.Dtos; -using xCategoryService.Interfaces.Dtos; -using Microsoft.Extensions.Configuration; -using xCategoryService.Providers.Entities; -using xCategoryService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xCategoryService.DI -{ - public static class XDIHelperExtension - { - /// - /// Extract Service Configurations ... - /// - /// - /// - public static XCategoryServiceConfiguration GetXCategoryServiceConfigurations( - this IConfiguration source - ) - { - // - XCategoryServiceConfiguration result = null; - - // - var section = source.GetSection(Constants.ConfigurationNodeNames.CATEGORY_SERVICE_NODE); - var sectionJson = source.GetSectionAsJson(Constants.ConfigurationNodeNames.CATEGORY_SERVICE_NODE); - if (!section.IsNull()) - { - result = sectionJson.FromJSON(); - } - - // - return result; - } - - /// - /// Register Service Configuration ... - /// - /// - /// - public static void AddXCategoryServiceConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - // Extract Configuration Class ... - var config = configuration.GetXCategoryServiceConfigurations(); - - // - // Register Class as Service ... - source.AddXCategoryServiceConfiguration(config); - } - - /// - /// Register Service Configuration ... - /// - /// - /// - public static void AddXCategoryServiceConfiguration( - this IServiceCollection source, - XCategoryServiceConfiguration configuration - ) - { - // - // Normalize Configuration Class ... - if (configuration.IsNull()) - { - configuration = new XCategoryServiceConfiguration(); - } - - // - // Register ... - source.AddSingleton(configuration); - } - - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXCategoryService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddCategoryService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXCategoryService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddCategoryService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XSubCategoryService Middleware ... - /// - /// - /// - public static void UseXCategoryService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - // Category ... - pushHelper.AddHub(XCategoryServiceConstants.XCategoryDtoHub); - pushHelper.AddHub(XCategoryServiceConstants.XCategoryEntityHub); - - // - // SubCategory ... - pushHelper.AddHub(XCategoryServiceConstants.XSubCategoryDtoHub); - pushHelper.AddHub(XCategoryServiceConstants.XSubCategoryEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XCategory Repository Descriptor ... - if (!categoryDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: categoryDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Using XSubCategory Repository Descriptor ... - if (!subCategoryDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: subCategoryDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Create an Scope for Services Acces ... - // Handle Seeding Category/SubCategory Resources ... - using (var scope = app.ApplicationServices.CreateScope()) - { - // - // Retrieve Configuratuions ... - var categoryProvider = scope.ServiceProvider.GetService(); - var subCategoryProvider = scope.ServiceProvider.GetService(); - var configuration = scope.ServiceProvider.GetService(); - if (!configuration.IsNullOrDefault() && - !categoryProvider.IsNullOrDefault() && - !subCategoryDescriptor.IsNullOrDefault() - ) - { - // - // Logging ... - Log("Start Seeding ..."); - - // - // Count Data in Category ... - var hasCategory = categoryProvider.Count().GetAwaiter().GetResult() > 0; - var hasSubCategory = subCategoryProvider.Count().GetAwaiter().GetResult() > 0; - - // - // Seed Category Resources ... - var canSeed = - !hasCategory && - configuration.Categories.HasChild(); - if (canSeed) - { - // - // Loop through Provided items ... - foreach (var cat in configuration.Categories) - { - // - try - { - // - Log($"Start Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} ..."); - - // - categoryProvider.Refresh( - resource: cat, - userInfo: null, - connectionId: null, - cancellationToken: default - ) - .GetAwaiter() - .GetResult(); - - // - Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); - } - catch (Exception ex) - { - Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); - } - } - } - - // - // Seed SubCategory Resources ... - canSeed = - !hasSubCategory && - configuration.SubCategories.HasChild(); - if (canSeed) - { - // - // Loop through Provided items ... - foreach (var subcat in configuration.SubCategories) - { - // - try - { - // - Log($"Start Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} ..."); - - // - subCategoryProvider.Refresh( - userInfo: null, - resource: subcat, - connectionId: null, - cancellationToken: default - ) - .GetAwaiter() - .GetResult(); - - // - Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); - } - catch (Exception ex) - { - Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); - } - } - } - - // - Log("Finish Seeding ..."); - } - } - } - - // - #region Private ... - private static XRepositoryDescriptor categoryDescriptor = null; - private static XRepositoryDescriptor subCategoryDescriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XCategoryServiceConstants.XCategoryServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddCategoryService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - // Category ... - categoryDescriptor = typeof(XCategoryServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XCategoryServiceConstants.GetXCategoryEFRepositoryDescriptor - ); - - // - // SubCategory ... - subCategoryDescriptor = typeof(XCategoryServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XCategoryServiceConstants.GetXSubCategoryEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - // - // Category ... - categoryDescriptor = XCategoryServiceHelper.GetXCategoryMongoRepositoryDescriptor(); - - // - // SubCategory ... - subCategoryDescriptor = XCategoryServiceHelper.GetXSubCategoryMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - // - // Category ... - categoryDescriptor = XCategoryServiceHelper.GetXCategoryInMemoryRepositoryDescriptor(); - - // - // SubCategory ... - subCategoryDescriptor = XCategoryServiceHelper.GetXSubCategoryInMemoryRepositoryDescriptor(); - break; - } - - // - // Register Category Repository Descriptor ... - if (!categoryDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: categoryDescriptor - ); - } - - // - // Register SubCategory Repository Descriptor ... - if (!subCategoryDescriptor.IsNull()) - { - // - services.AddXRepository( - lifeTime: lifeTime, - descriptor: subCategoryDescriptor - ); - } - - // - #region Register Services ... - // - #region Category ... - // - // Models ... - services.Add( - new ServiceDescriptor(typeof(IXCategoryServiceProvider), typeof(XCategoryServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXCategoryRepositoryService), typeof(XCategoryRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXCategoryRepositoryProvider), typeof(XCategoryRepositoryProvider), lifeTime) - ); - - // - // Resource Providers ... - services.Add( - new ServiceDescriptor(typeof(IXCategoryTitleResourceProvider), typeof(XCategoryTitleResourceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXCategoryDescriptionResourceProvider), typeof(XCategoryDescriptionResourceProvider), lifeTime) - ); - - // - // Reference Providers ... - services.Add( - new ServiceDescriptor(typeof(IXCategorySubCategoryReferenceProvider), typeof(XCategorySubCategoryReferenceProvider), lifeTime) - ); - - // - // Provider ... - services.Add( - new ServiceDescriptor(typeof(IXCategoryProvider), typeof(XCategoryProvider), lifeTime) - ); - #endregion - - // - #region SubCategory ... - // - // Models ... - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryServiceProvider), typeof(XSubCategoryServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryRepositoryService), typeof(XSubCategoryRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryRepositoryProvider), typeof(XSubCategoryRepositoryProvider), lifeTime) - ); - - // - // Resource Providers ... - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryTitleResourceProvider), typeof(XSubCategoryTitleResourceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryDescriptionResourceProvider), typeof(XSubCategoryDescriptionResourceProvider), lifeTime) - ); - - // - // Provider ... - services.Add( - new ServiceDescriptor(typeof(IXSubCategoryProvider), typeof(XSubCategoryProvider), lifeTime) - ); - #endregion - #endregion - - // - // Register Service Main Provider ... - services.Add( - new ServiceDescriptor(typeof(IXCategoryService), typeof(XCategoryService), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Extensions\XCategoryResourceExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Extensions -{ - /// - /// Extensions Method Related to XCategoryResourceDto ... - /// - public static class XCategoryResourceExtensions - { - /// - /// Extract Available Languages ... - /// - /// - /// - public static string[] ExtractLanguages( - this XCategoryResourceDto source - ) - { - // - var result = new string[] { }; - - // - // Validate ... - if (!source.IsNullOrDefault()) - { - return result; - } - - // - result = - source.Titles.Locales.Select(x => x.Language) - .Union(source.Descriptions.Locales.Select(x => x.Language)) - .Distinct() - .ToArray(); - - // - return result; - } - - /// - /// Check Has Locale or not ... - /// - /// - /// - /// - public static bool HasLocale( - this XCategoryResourceDto source, - string language - ) - { - // - var result = - !language.IsNullOrEmpty() && - !source.IsNullOrDefault() && - source.Titles.Locales - .Any(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Get Item Translation ... - /// - /// - /// - /// - public static XCategoryDto GetTranslate( - this XCategoryResourceDto source, - string language - ) - { - // - XCategoryDto result = null; - - // - var isValid = source - .HasLocale(language); - if (!isValid) - { - return result; - } - - // - var titleLocale = source.Titles.Locales - .FirstOrDefault(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - var descriptionLocale = source.Descriptions.Locales - .FirstOrDefault(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - isValid = !titleLocale.IsNullOrDefault(); - if (!isValid) - { - return result; - } - - // - result = source.Item; - result.Title = titleLocale.Value; - result.Description = - descriptionLocale.IsNullOrDefault() - ? string.Empty - : descriptionLocale.Value; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Extensions\XModelExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Extensions; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Extensions -{ - public static class XModelExtensions - { - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XCategory source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XCategoryDto source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XCategory UpdateReferences( - this XCategory source, - IList> references, - bool forceClean = true - ) - { - // - XCategory result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XCategoryDto UpdateReferences( - this XCategoryDto source, - IList> references, - bool forceClean = true - ) - { - // - XCategoryDto result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Extensions\XSubCategoryResourceExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Extensions -{ - /// - /// Extensions Method Related to XSubCategoryResourceDto ... - /// - public static class XSubCategoryResourceExtensions - { - /// - /// Extract Available Languages ... - /// - /// - /// - public static string[] ExtractLanguages( - this XSubCategoryResourceDto source - ) - { - // - var result = new string[] { }; - - // - // Validate ... - if (!source.IsNullOrDefault()) - { - return result; - } - - // - result = - source.Titles.Locales.Select(x => x.Language) - .Union(source.Descriptions.Locales.Select(x => x.Language)) - .Distinct() - .ToArray(); - - // - return result; - } - - /// - /// Check Has Locale or not ... - /// - /// - /// - /// - public static bool HasLocale( - this XSubCategoryResourceDto source, - string language - ) - { - // - var result = - !language.IsNullOrEmpty() && - !source.IsNullOrDefault() && - source.Titles.Locales - .Any(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Get Item Translation ... - /// - /// - /// - /// - public static XSubCategoryDto GetTranslate( - this XSubCategoryResourceDto source, - string language - ) - { - // - XSubCategoryDto result = null; - - // - var isValid = source - .HasLocale(language); - if (!isValid) - { - return result; - } - - // - var titleLocale = source.Titles.Locales - .FirstOrDefault(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - var descriptionLocale = source.Descriptions.Locales - .FirstOrDefault(l => l.Language - .Equals( - language, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - isValid = !titleLocale.IsNullOrDefault(); - if (!isValid) - { - return result; - } - - // - result = source.Item; - result.Title = titleLocale.Value; - result.Description = - descriptionLocale.IsNullOrDefault() - ? string.Empty - : descriptionLocale.Value; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Helpers\XCategoryServiceHelper.cs - -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xCategoryService.Models.Entities; -using xCategoryService.Providers.GraphQL; -using xCategoryService.Providers.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Helpers -{ - public static class XCategoryServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - // - #region Category - public static XEFRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryEFRepository, - TContext - > GetXCategoryEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryEFRepository, - TContext, - IXCategorySeeder, - TSeederImplementation - > GetXCategoryEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryEFRepository, - TContext, - IXCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region SubCategory - public static XEFRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryEFRepository, - TContext - > GetXSubCategoryEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryEFRepository, - TContext, - IXSubCategorySeeder, - TSeederImplementation - > GetXSubCategoryEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryEFRepository, - TContext, - IXSubCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - // - #region Category - public static XMongoRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryMongoRepository - > GetXCategoryMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryMongoRepository, - IXCategorySeeder, - TSeederImplementation - > GetXCategoryMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryMongoRepository, - IXCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region SubCategory - public static XMongoRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryMongoRepository - > GetXSubCategoryMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryMongoRepository, - IXSubCategorySeeder, - TSeederImplementation - > GetXSubCategoryMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryMongoRepository, - IXSubCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - // - #region Category - public static XInMemoryRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryInMemoryRepository - > GetXCategoryInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryInMemoryRepository, - IXCategorySeeder, - TSeederImplementation - > GetXCategoryInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XCategory, - int, - IXCategoryKeyGenerator, - XCategoryKeyGenerator, - IXCategoryRepositoryEvents, - XCategoryRepositoryEvents, - XCategoryGraphType, - IntGraphType, - XCategoryGraphQuery, - IXCategoryGraphQLTypeHelper, - XCategoryGraphQLTypeHelper, - XCategoryGraphSchema, - IXCategoryRepository, - XCategoryInMemoryRepository, - IXCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region SubCategory - public static XInMemoryRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryInMemoryRepository - > GetXSubCategoryInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryInMemoryRepository, - IXSubCategorySeeder, - TSeederImplementation - > GetXSubCategoryInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XSubCategory, - int, - IXSubCategoryKeyGenerator, - XSubCategoryKeyGenerator, - IXSubCategoryRepositoryEvents, - XSubCategoryRepositoryEvents, - XSubCategoryGraphType, - IntGraphType, - XSubCategoryGraphQuery, - IXSubCategoryGraphQLTypeHelper, - XSubCategoryGraphQLTypeHelper, - XSubCategoryGraphSchema, - IXSubCategoryRepository, - XSubCategoryInMemoryRepository, - IXSubCategorySeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXBaseCategoryProvider.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Interfaces -{ - public interface IXBaseCategoryProvider : IXBaseReferencedProvider - {} -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategoryDescriptionResourceProvider.cs - -using xStringService.Interfaces; - -namespace xCategoryService.Interfaces -{ - public interface IXCategoryDescriptionResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategoryProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xPushService.Interfaces; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces -{ - public interface IXCategoryProvider : IXBaseProvided, IXCategorySubCategoryReferenceProvider - { - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - Task HasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - Task GetResource( - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - Task Add( - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by It's Locales ... - /// - /// - /// - /// - /// - /// - Task AddResource( - XCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - Task Remove( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - Task Update( - int id, - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - Task Refresh( - XCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - Task> GetAllResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - Task FindOneResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - Task> FindManyResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - Task> QueryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - IAsyncEnumerable GetAllResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategoryProviderController.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces -{ - public interface IXCategoryProviderController : IXBaseProvidedController - { - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - [HttpGet("Resources/{id}/HasLocale")] - Task> HasLocale( - [FromRoute] int id, - [FromQuery] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - [HttpGet("Resources/{id}")] - Task> GetResource( - [FromRoute] int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - [HttpPost("Resources")] - Task> Add( - [FromBody] XCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by It's Locales ... - /// - /// - /// - /// - [HttpPost("Resources/AddResource")] - Task> AddResource( - [FromBody] XCategoryResourceDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - [HttpDelete("Resources/{id}")] - Task> Remove( - [FromRoute] int id, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - [HttpPut("Resources/{id}")] - Task> Update( - [FromRoute] int id, - [FromBody] XCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - [HttpPost("Resources/Refresh")] - Task> Refresh( - [FromBody] XCategoryResourceDto resource, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - [HttpGet("Resources/All")] - Task>> GetAllResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/One")] - Task> FindOneResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/Many")] - Task>> FindManyResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - [HttpGet("Resources/Query")] - Task>> QueryResources( - [FromQuery] XQuery query = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategoryService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Interfaces -{ - /// - /// Completely Exported Service ... - /// - public interface IXCategoryService - { - // - #region Category Provider ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - Task CategoryHasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - Task GetCategoryResource( - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - Task AddCategory( - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by It's Locales ... - /// - /// - /// - /// - /// - /// - Task AddCategoryResource( - XCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - Task RemoveCategory( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - Task UpdateCategory( - int id, - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - Task RefreshCategory( - XCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - Task> GetAllCategoryResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - Task FindOneCategoryResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - Task> FindManyCategoryResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - Task> QueryCategoryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - IAsyncEnumerable GetAllCategoryResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ); - #endregion - - // - #region SubCategory Provider ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - Task SubCategoryHasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - Task GetSubCategoryResource( - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - Task AddSubCategory( - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - /// - /// - Task AddSubCategoryResource( - XSubCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - Task RemoveSubCategory( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - Task UpdateSubCategory( - int id, - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - Task RefreshSubCategory( - XSubCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - Task> GetAllSubCategoryResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - Task FindOneSubCategoryResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - Task> FindManySubCategoryResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - Task> QuerySubCategoryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - IAsyncEnumerable GetAllSubCategoryResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategorySubCategoryReferenceProvider.cs - -namespace xCategoryService.Interfaces -{ - /// - /// a Service for SubCategory Referencing on Category ... - /// - public interface IXCategorySubCategoryReferenceProvider : IXBaseCategoryProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXCategoryTitleResourceProvider.cs - -using xStringService.Interfaces; - -namespace xCategoryService.Interfaces -{ - public interface IXCategoryTitleResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXSubCategoryDescriptionResourceProvider.cs - -using xStringService.Interfaces; - -namespace xCategoryService.Interfaces -{ - public interface IXSubCategoryDescriptionResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXSubCategoryProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xPushService.Interfaces; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces -{ - public interface IXSubCategoryProvider : IXBaseProvided - { - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - Task HasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - Task GetResource( - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - Task Add( - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - /// - /// - Task AddResource( - XSubCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - Task Remove( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - Task Update( - int id, - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - Task Refresh( - XSubCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - Task> GetAllResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - Task FindOneResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - Task> FindManyResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - Task> QueryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - IAsyncEnumerable GetAllResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXSubCategoryProviderController.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces -{ - public interface IXSubCategoryProviderController : IXBaseProvidedController - { - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - [HttpGet("Resources/{id}/HasLocale")] - Task> HasLocale( - [FromRoute] int id, - [FromQuery] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - [HttpGet("Resources/{id}")] - Task> GetResource( - [FromRoute] int id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - [HttpPost("Resources")] - Task> Add( - [FromBody] XSubCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - [HttpPost("Resources/AddResource")] - Task> AddResource( - [FromBody] XSubCategoryResourceDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - [HttpDelete("Resources/{id}")] - Task> Remove( - [FromRoute] int id, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - [HttpPut("Resources/{id}")] - Task> Update( - [FromRoute] int id, - [FromBody] XSubCategoryDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - [HttpPost("Resources/Refresh")] - Task> Refresh( - [FromBody] XSubCategoryResourceDto resource, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Resources ... - /// - /// - /// - [HttpGet("Resources/All")] - Task>> GetAllResources( - CancellationToken cancellationToken = default - ); - - /// - /// Find One Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/One")] - Task> FindOneResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ); - - /// - /// Find Many Resource ... - /// - /// - /// - /// - [HttpGet("Resources/Find/Many")] - Task>> FindManyResource( - [FromQuery] string query, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - [HttpGet("Resources/Query")] - Task>> QueryResources( - [FromQuery] XQuery query = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\IXSubCategoryTitleResourceProvider.cs - -using xStringService.Interfaces; - -namespace xCategoryService.Interfaces -{ - public interface IXSubCategoryTitleResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXCategoryDtoHub.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXCategoryDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXCategoryRepositoryService.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXCategoryRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXCategoryServiceProvider.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXCategoryServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXSubCategoryDtoHub.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXSubCategoryDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXSubCategoryRepositoryService.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXSubCategoryRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Dtos\IXSubCategoryServiceProvider.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Providers.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Dtos -{ - public interface IXSubCategoryServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryEntityHub.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryKeyGenerator.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryRepository.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryRepositoryEvents.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategoryRepositoryProvider.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Entities; -using xCategoryService.Providers.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategoryRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXCategorySeeder.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXCategorySeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryEntityHub.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryKeyGenerator.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryRepository.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryRepositoryEvents.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategoryRepositoryProvider.cs - -using xPushService.Interfaces; -using xCategoryService.Models.Entities; -using xCategoryService.Providers.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategoryRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Interfaces\Entities\IXSubCategorySeeder.cs - -using xDataService.Interfaces; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Interfaces.Entities -{ - public interface IXSubCategorySeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Dtos\XCategoryDto.cs - -using xModels.Base; - -namespace xCategoryService.Models.Dtos -{ - public class XCategoryDto : XBaseIntIDEntityDto - { - /// - /// Title of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Title { get; set; } - - /// - /// Description of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Description { get; set; } - - /// - /// References List String Representation ... - /// each SubCategory Referenced to Category ID which List here ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Dtos\XCategoryResourceDto.cs - -using xModels.Base; -using xModels.Dtos; - -namespace xCategoryService.Models.Dtos -{ - /// - /// Represent a Category by all of it's Resources ... - /// - public class XCategoryResourceDto : XBaseDto - { - /// - /// Category Dto Item for Add or Update ... - /// - public XCategoryDto Item { get; set; } - - /// - /// Exists Category Titles ... - /// - public XResourceDto Titles { get; set; } - - /// - /// Exists Category Description ... - /// - public XResourceDto Descriptions { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Dtos\XSubCategoryDto.cs - -using xModels.Base; - -namespace xCategoryService.Models.Dtos -{ - public class XSubCategoryDto : XBaseIntIDEntityDto - { - /// - /// Title of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Title { get; set; } - - /// - /// Description of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Description { get; set; } - - /// - /// References List String Representation ... - /// each SubCategory Referenced to Category ID which List here ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Dtos\XSubCategoryResourceDto.cs - -using xModels.Base; -using xModels.Dtos; - -namespace xCategoryService.Models.Dtos -{ - public class XSubCategoryResourceDto : XBaseDto - { - /// - /// SubCategory Dto Item for Add or Update ... - /// - public XSubCategoryDto Item { get; set; } - - /// - /// Exists SubCategory Titles ... - /// - public XResourceDto Titles { get; set; } - - /// - /// Exists SubCategory Description ... - /// - public XResourceDto Descriptions { get; set; } - - /// - /// Exists Category Resource Dto for Add or Update Category or - /// Related Categopry ... - /// - public XCategoryResourceDto Category { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Entities\XCategory.cs - -using xModels.Base; - -namespace xCategoryService.Models.Entities -{ - public class XCategory : XBaseIntIDEntity - { - /// - /// Title of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Title { get; set; } - - /// - /// Description of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Description { get; set; } - - /// - /// References List String Representation ... - /// each SubCategory Referenced to Category ID which List here ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Models\Entities\XSubCategory.cs - -using xModels.Base; - -namespace xCategoryService.Models.Entities -{ - public class XSubCategory : XBaseIntIDEntity - { - /// - /// Title of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Title { get; set; } - - /// - /// Description of SubCategory ... - /// this is a Resource Title ... - /// - /// - public string Description { get; set; } - - /// - /// References List String Representation ... - /// each SubCategory Referenced to Category ID which List here ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XBaseCategoryProvider.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xDataService.Extensions; -using System.Collections.Generic; -using xCategoryService.Extensions; -using xCategoryService.Interfaces; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public abstract class XBaseCategoryProvider : IXBaseCategoryProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - public string Provider { get; } - - /// - /// Tag Provider for Maipulating Tags ... - /// - public IXCategoryServiceProvider CategoryProvider { get; } - #endregion - - // - #region Constructor ... - public XBaseCategoryProvider( - string providedFor, - IXCategoryServiceProvider categoryProvider - ) - { - // - Provider = providedFor; - CategoryProvider = categoryProvider; - } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - public async Task GetReference( - TKey providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (forIndex < 0) - { - forIndex = 0; - } - - // - // Retrieve Last Index ... - var indexes = await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - var maxIndex = indexes.HasChild() ? indexes.Max() : -1; - if (forIndex > maxIndex) - { - XException.NotFound.Throw(); - } - - // - var indexedIdentifier = GetIndexedProvidedID( - forIndex: forIndex, - providedForId: providedForId - ); - var result = await CategoryProvider.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(indexedIdentifier) - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - public async Task> GetAllReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await CategoryProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - public async Task>> GetAllReferencings( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - - // - var result = (await CategoryProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Select(x => x.References) - .ToList() - .SelectMany(x => x.ParseXReferenceList()) - .Where(x => x.ProvidedFor == Provider && $"{x.ReferencedTo}" == $"{providedForId}") - .OrderBy(x => x.Index) - .AsEnumerable(); - - // - return result; - } - - /// - /// Count References ... - /// - /// - /// - /// - public async Task CountReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = (await CategoryProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Count(); - - // - return result; - } - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - public async Task> QueryReferences( - XQuery query, - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (query.IsNull() || providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await CategoryProvider.QueryAsync( - query: query, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XCategoryDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !model.IsNullOrDefault() && - model.Id.IsValidIntId() && - !providedForId.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Model Exists ... - result = await CategoryProvider.IsExistsAsync(model.Id); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Update Model by Retrieving ... - model = await CategoryProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - // Retrieve all References ... - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check isReferenced or not ... - result = references - .Any(r => - r.Id == model.Id && - r.GetReferences() - .Any(rf => - rf.ProvidedFor == Provider && - rf.ReferencedTo == $"{providedForId}")); - if (result) - { - return result; - } - - // - // Here means there is not any reference to ProvidedForId ... - int forIndex = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - var modelReferences = model.GetReferences(); - modelReferences.Add(new XReference - { - Index = forIndex, - ProvidedFor = Provider, - ReferencedTo = $"{providedForId}" - }); - modelReferences = modelReferences - .OrderBy(r => r.Index) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update Data Base ... - model = await CategoryProvider.UpdateAsync( - id: model.Id, - item: model, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - - // - return result; - } - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XCategoryDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - // Since other Validations Handled in Calling, we Ignore them here ... - var result = - !model.IsNull() && - !reference.IsNullOrDefault() && - reference.ProvidedFor == Provider && - !reference.ReferencedTo.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await AddReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XCategoryDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !providedForId.IsNull() && - !model.IsNullOrDefault() && - model.Id.IsValidIntId(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Model ... - model = await CategoryProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Reading Referencing Indexes ... - var indexes = await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check Model Reference to ID ... - var referencesCount = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - result = referencesCount == 0; - if (result) - { - // - // There is not any Reference to Remove ... - return result; - } - - // - // Check Model is Trully Referenced to ProvidedForId or not ... - var reference = model - .GetReferences() - .FirstOrDefault(r => - r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}"); - result = !reference.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Remove Referenced Item from Model ... - var modelReferences = model - .GetReferences() - .Where(r => - !(r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}")) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update DataBase ... - model = await CategoryProvider.UpdateAsync( - item: model, - id: model.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - result = !model.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Get Max Exists Indexes ... - var maxIndex = indexes.Max(); - - // - // Here We Have to Re Arrange Indexed ... - if (reference.Index < maxIndex) - { - // - var startIndex = reference.Index + 1; - for (int i = startIndex; i <= maxIndex; i++) - { - // - var dto = await GetReference( - forIndex: i, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!dto.IsNullOrDefault()) - { - // - var dtoReferences = dto.GetReferences(); - dtoReferences - .ToList() - .ForEach(iref => - { - // - if ( - iref.Index == i && - iref.ProvidedFor == Provider && - iref.ReferencedTo == reference.ReferencedTo - ) - { - iref.Index = i - 1; - } - }); - dto = dto.UpdateReferences(dtoReferences); - - // - dto = await CategoryProvider.UpdateAsync( - item: dto, - id: dto.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - } - - // - return result; - } - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XCategoryDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - if (model.IsNullOrDefault() || - reference.IsNullOrDefault() || - reference.ReferencedTo.IsNull() || - reference.ProvidedFor != Provider) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await RemoveReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - public async Task RemoveReferences( - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = false; - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!references.IsNull() && references.HasChild()) - { - // - foreach (var reference in references) - { - // - // Remove Reference ... - var itemReferences = reference.GetReferences() - .Where(r => - r.ProvidedFor != Provider || - (r.ProvidedFor == Provider && - r.ReferencedTo != $"{providedForId}")) - .ToList(); - var updatedModel = reference.UpdateReferences(itemReferences); - updatedModel = await CategoryProvider.UpdateAsync( - saveChanges: true, - item: updatedModel, - id: updatedModel.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!updatedModel.IsNullOrDefault()) - { - result = true; - } - } - } - - // - return result; - } - #endregion - - // - #region Private ... - private string GetProvidedID( - TKey providedForId, - char splitter = '_' - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = $"{Provider}{splitter}{providedForId}"; - return result; - } - - private string GetIndexedProvidedID( - TKey providedForId, - int forIndex, - char splitter = '_' - ) - { - // - var result = $"{GetProvidedID(providedForId, splitter)}{splitter}{forIndex}"; - - // - return result; - } - - private async Task> GetReferencingIndexes( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = new List(); - var referencings = await GetAllReferencings( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - isValid = - !referencings.IsNull() && - referencings.HasChild(); - if (!isValid) - { - return result; - } - - // - result = - referencings - .OrderBy(r => r.Index) - .Select(r => r.Index) - .ToList(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategoryDescriptionResourceProvider.cs - -using xStringService.Providers; -using xCategoryService.Constants; -using xCategoryService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public class XCategoryDescriptionResourceProvider : XBaseItemResourceProvider, IXCategoryDescriptionResourceProvider - { - public XCategoryDescriptionResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XCategoryServiceConstants.CategoryDescriptionResourceIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategoryEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xCategoryService.Models.Entities; -using xCategoryService.Configurations.Entities; - -namespace xCategoryService.Providers -{ - public class XCategoryEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XCategoryEntityRegisterar() - : base(nameof(XCategoryEntityRegisterar)) - { - // - // Add XCategory Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XCategoryEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategoryProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xPushService.Constants; -using xPushService.Providers; -using System.Linq.Expressions; -using xCommons.Configurations; -using xDataService.Extensions; -using System.Collections.Generic; -using xDataService.Configuration; -using xCategoryService.Interfaces; -using xCategoryService.Models.Dtos; -using System.Runtime.CompilerServices; -using xCategoryService.Providers.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers -{ - public class XCategoryProvider : XBaseProvided, IXCategoryProvider - { - private readonly IXCategoryServiceProvider provider; - private readonly XAppConfiguration appConfiguration; - private readonly XDataServiceConfiguration dataServiceConfiguration; - private readonly IXCategoryTitleResourceProvider titleResourceProvider; - private readonly IXCategoryDescriptionResourceProvider descriptionResourceProvider; - private readonly IXCategorySubCategoryReferenceProvider categorySubCategoryReferenceProvider; - - public string Provider => categorySubCategoryReferenceProvider.Provider; - - public XCategoryProvider( - XAppConfiguration appConfiguration, - IXCategoryServiceProvider provider, - XDataServiceConfiguration dataServiceConfiguration, - IXCategoryTitleResourceProvider titleResourceProvider, - IXCategoryDescriptionResourceProvider descriptionResourceProvider, - IXCategorySubCategoryReferenceProvider categorySubCategoryReferenceProvider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { - // - this.provider = provider; - this.appConfiguration = appConfiguration; - this.titleResourceProvider = titleResourceProvider; - this.dataServiceConfiguration = dataServiceConfiguration; - this.descriptionResourceProvider = descriptionResourceProvider; - this.categorySubCategoryReferenceProvider = categorySubCategoryReferenceProvider; - } - - // - #region Overrides ... - public override bool IsOwned( - XCategoryDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XCategory item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - #endregion - - // - #region Actions ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - public async Task HasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - id.IsValidIntId() && - !language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Resource ... - var resource = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Check Result ... - var result = - !resource.IsNullOrDefault() && - resource.Titles.Locales - .Any(x => x.Language - .Equals(language, System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - public async Task GetResource( - int id, - CancellationToken cancellationToken = default - ) - { - // - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - var titleResource = await titleResourceProvider.GetResource( - identifier: id, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider.GetResource( - identifier: id, - cancellationToken: cancellationToken - ); - - // - var result = new XCategoryResourceDto - { - Item = item, - Titles = titleResource, - Descriptions = descriptionResource - }; - - // - return result; - } - - /// - /// Add an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - public async Task Add( - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize ... - language = - !language.IsNullOrEmpty() - ? language - : appConfiguration.DefaultLanguage; - - // - // Validate ... - var isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - try - { - // - var title = item.Title; - var description = item.Description; - - // - // Add Item Pure for ID Generating ... - item = await base.Add( - item: item, - userInfo: userInfo, - connectionId: null, // Since here We dont want notification ... - cancellationToken: cancellationToken - ); - isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - id = item.Id; - var titleResource = await titleResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = title, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = description, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Update Category Dto ... - item.Title = titleResource.Resource; - item.Description = descriptionResource.Resource; - item = await base.Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - catch - { - XException.InvalidArgs.Throw(); - } - - // - // Validate Id ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Retrieve Category Resourv=ce ... - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Sending Push Notification ... - isValid = - isValid && - !result.IsNullOrDefault(); - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Add Category by It's Locales ... - /// - /// - /// - /// - /// - /// - public async Task AddResource( - XCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !item.IsNullOrDefault() && - !item.Titles.IsNullOrDefault() && - item.Titles.Locales.HasChild() && - !item.Titles.Locales.Any(il => - il.Language.IsNullOrEmpty() || - il.Value.IsNullOrEmpty()); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (item.Item.IsNullOrDefault()) - { - item.Item = new XCategoryDto(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - try - { - // - // Add Category for ID Generation ... - item.Item = await base.Add( - item: item.Item, - userInfo: userInfo, - connectionId: null, // Since here We dont want notification ... - cancellationToken: cancellationToken - ); - isValid = !item.Item.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - id = item.Item.Id; - - // - foreach (var il in item.Titles.Locales) - { - // - var title = il.Value; - var language = il.Language; - - // - var descriptionItem = - item.Descriptions.IsNullOrDefault() || - !item.Descriptions.Locales.HasChild() - ? null - : item.Descriptions.Locales - .FirstOrDefault(ides => - ides.Language - .Equals( - language, - StringComparison.InvariantCultureIgnoreCase)); - var description = - descriptionItem.IsNullOrDefault() - ? string.Empty - : descriptionItem.Value; - - // - // Try to Add Resources ... - var titleResource = await titleResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = title, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = description, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Update Category Dto if not ... - if (item.Item.Title.IsNullOrEmpty() || - !item.Item.Title - .Equals( - titleResource.Resource, - StringComparison.InvariantCultureIgnoreCase) - ) - { - // - item.Item.Title = titleResource.Resource; - item.Item.Description = descriptionResource.Resource; - item.Item = await base.Update( - id: id, - item: item.Item, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - } - } - catch - { - XException.InvalidArgs.Throw(); - } - - // - // Validate Id ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Retrieve Category Resourv=ce ... - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Sending Push Notification ... - isValid = - isValid && - !result.IsNullOrDefault(); - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - public async Task Remove( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = id.IsValidIntId(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Item Exists ... - isValid = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Validate Locale if Provided ... - isValid = - language.IsNullOrEmpty() || - await HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - if (language.IsNullOrEmpty()) - { - // - // Remove All ... - - // - // Titles ... - await titleResourceProvider.RemoveLocales( - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Descriptions ... - await descriptionResourceProvider.RemoveLocales( - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Remove Entity ... - await provider.RemoveAsync( - id: id, - softDelete: false, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - isValid = true; - result.Titles.Locales = []; - result.Descriptions.Locales = []; - } - else - { - // - // Remove Only One Locale, and if there is one, Remove all ... - - // - // Remove Title if Exists ... - isValid = await titleResourceProvider.HasLocale( - identifier: id, - language: language, - cancellationToken: cancellationToken - ); - if (isValid) - { - // - await titleResourceProvider.RemoveLocale( - identifier: id, - language: language, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Remove Description if Exists ... - isValid = await descriptionResourceProvider.HasLocale( - identifier: id, - language: language, - cancellationToken: cancellationToken - ); - if (isValid) - { - // - await descriptionResourceProvider.RemoveLocale( - identifier: id, - language: language, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Retrieve Resource ... - result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Check Has Locales ... - isValid = result.Titles.Locales.HasChild(); - if (!isValid) - { - // - // Remove Item ... - await provider.RemoveAsync( - id: id, - softDelete: false, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - result.Titles.Locales = []; - result.Descriptions.Locales = []; - } - - // - isValid = true; - } - - // - if (isValid) - { - // - // Send Push ... - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: - result.Titles.Locales.HasChild() - ? "DeleteLocale" - : XBaseEntityHubAction.Delete.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task Update( - int id, - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - id.IsValidIntId() && - !item.IsNullOrDefault() && - !language.IsNullOrEmpty() && - !item.Title.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Category Exists ... - isValid = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Check Locale Exists ... - isValid = await HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Retrieve Category Dto for Validate Owining ... - var dto = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - - // - // Check Permission ... - isValid = - !dto.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - (IsOwned( - item: dto, - userInfo: userInfo - ) || HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - // Retrieve Exists Item Resource ... - var resource = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - var titleUpdated = false; - var descriptionUpdated = false; - - // - // Update Title ... - resource.Titles.Locales - .ToList() - .ForEach(tl => - { - // - if (tl.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)) - { - // - titleUpdated = true; - tl.Value = item.Title; - } - }); - - // - // Update Description ... - resource.Descriptions.Locales - .ToList() - .ForEach(dl => - { - // - if (dl.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)) - { - // - descriptionUpdated = true; - dl.Value = item.Description; - } - }); - - // - // Validate Title and Description Updated ... - isValid = titleUpdated && descriptionUpdated; - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - resource = await Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return resource; - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - public async Task Refresh( - XCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = - !resource.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - var isDelete = false; - XCategoryResourceDto result = null; - - // - // Check Item Exists ... - XCategoryDto dto = - (resource.Item.IsNullOrDefault() || - !resource.Item.Id.IsValidIntId()) - ? null - : await Get( - id: resource.Item.Id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - var isExists = !dto.IsNullOrDefault(); - - // - // Do Referesh Based on Existance ... - var isNew = - !isExists && - (resource.Item.IsNullOrDefault() || - !resource.Item.Id.IsValidIntId()); - if (isNew) - { - // - // Add ... - // In this Senario, for Add a Category by Providing Resource - // the item must clean, either Title and Description, and tge Locales Provided by Resource - // ust Contains Values ... - // the Add Starts by Titles and only Items Add Which has Titles, since Title is Mandatory - // and Description is Optional ... - isValid = - // - // Resource ... - (resource.Item.IsNullOrDefault() || - (!resource.Item.Id.IsValidIntId() && - resource.Item.Title.IsNullOrEmpty() && - resource.Item.Description.IsNullOrEmpty())) && - // - // Titles ... - !resource.Titles.IsNullOrDefault() && - resource.Titles.Locales.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Add Temp Category ... - var unique = Guid.NewGuid(); - var temp = new XCategoryDto - { - Title = $"TmpT_{unique}", - Description = $"TmpD_{unique}", - }; - temp = await provider.AddAsync( - item: temp, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - isValid = - !temp.IsNullOrDefault() && - temp.Id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - id = temp.Id; - - // - // Update Title and Description ... - var titleResource = titleResourceProvider.GetResourceTitle(id); - var descriptionResource = descriptionResourceProvider.GetResourceTitle(id); - temp.Title = titleResource; - temp.Description = descriptionResource; - temp = await provider.UpdateAsync( - id: id, - item: temp, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Loop through Titles ... - foreach (var locale in resource.Titles.Locales) - { - // - // Add Or Update Locale ... - await titleResourceProvider.AddOrUpdateLocale( - locale: locale, - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - var desLocale = resource.Descriptions.Locales.FirstOrDefault( - dl => - dl.Language == locale.Language); - if (!desLocale.IsNullOrDefault()) - { - // - // Add Descriptions ... - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: desLocale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - } - } - else if (isExists) - { - // - // Re State ... - id = resource.Item.Id; - - // - // Try to Refresh Resource State ... - - // - // Check Delete ... - isDelete = !resource.Titles.Locales.HasChild(); - if (isDelete) - { - // - // Handle Delete ... - await Remove( - id: id, - language: null, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - else - { - // - // Handle Update ... - result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - #region Remove ... - // - // Titles ... - var removeTitles = result.Titles.Locales.Where( - l => !resource.Titles.Locales.Any(r => r.Language.Equals(l.Language, System.StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in removeTitles) - { - // - await titleResourceProvider.RemoveLocale( - identifier: id, - connectionId: null, - language: locale.Language, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var removeDescriptions = result.Descriptions.Locales.Where( - l => !resource.Descriptions.Locales.Any(r => r.Language.Equals(l.Language, System.StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in removeDescriptions) - { - // - await descriptionResourceProvider.RemoveLocale( - identifier: id, - connectionId: null, - language: locale.Language, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Update ... - // - // Titles ... - var updateTitles = result.Titles.Locales.Where( - l => resource.Titles.Locales.Any(r => - r.Value - .Equals(l.Value, StringComparison.InvariantCultureIgnoreCase) && - r.Language - .Equals(l.Language, StringComparison.InvariantCultureIgnoreCase) - ) - ); - foreach (var locale in updateTitles) - { - // - await titleResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var updateDescriptions = result.Descriptions.Locales.Where( - l => resource.Descriptions.Locales.Any(r => - r.Value - .Equals(l.Value, StringComparison.InvariantCultureIgnoreCase) && - r.Language - .Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in updateDescriptions) - { - // - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region New ... - // - // Titles ... - var newTitles = resource.Titles.Locales.Where( - l => !result.Titles.Locales.Any(r => r.Language.Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in newTitles) - { - // - await titleResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var newDescriptions = resource.Descriptions.Locales.Where( - l => !result.Descriptions.Locales.Any(r => r.Language.Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in newDescriptions) - { - // - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - #endregion - } - } - - // - // Validate Action ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Get Result ... - result = - isDelete - ? resource - : await GetResource( - id: id, - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - - // - // Send Notification ... - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: isNew - ? XBaseEntityHubAction.Add.GetStringValue() - : isDelete - ? XBaseEntityHubAction.Delete.GetStringValue() - : XBaseEntityHubAction.Update.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - public async IAsyncEnumerable GetAllResourcesAsAsyncEnumerable( - [EnumeratorCancellation] CancellationToken cancellationToken = default - ) - { - // - var enumerable = provider.GetAllAsAsyncEnumerable( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id) - ); - - // - await foreach (var dto in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var resource = await GetResource( - id: dto.Id, - cancellationToken: cancellationToken - ); - yield return resource; - } - } - - /// - /// Get All Resources ... - /// - /// - /// - public async Task> GetAllResources( - CancellationToken cancellationToken = default - ) - { - // - var result = new List(); - - // - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - result.Add(item); - } - - // - return result; - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - public async Task FindOneResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ) - { - // - var isApproved = false; - XCategoryResourceDto result = null; - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Detect Predicate Condition ... - isApproved = predicate.Compile()(item); - if (isApproved) - { - // - result = item; - break; - } - } - - // - return result; - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - public async Task> FindManyResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var isApproved = false; - var result = new List(); - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Detect Predicate Condition ... - isApproved = predicate.Compile()(item); - if (isApproved) - { - result.Add(item); - } - } - - // - // Apply Order ... - if (!orderBuilder.IsNull()) - { - // - result = - orderBuilder(result.AsQueryable()) - .ToList(); - } - - // - return result; - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - public async Task> QueryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(dataServiceConfiguration); - - // - var items = await FindManyResource( - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = [.. items], - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region SubCategory References ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - public async Task GetReference( - int providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .GetReference( - forIndex: forIndex, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - public async Task> GetAllReferences( - int providedForId, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - public async Task>> GetAllReferencings( - int providedForId, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .GetAllReferencings( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Count References ... - /// - /// - /// - /// - public async Task CountReferences( - int providedForId, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - public async Task> QueryReferences( - XQuery query, - int providedForId, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .QueryReferences( - query: query, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XCategoryDto model, - int providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .AddReference( - model: model, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XCategoryDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .AddReference( - model: model, - reference: reference, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XCategoryDto model, - int providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .RemoveReference( - model: model, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XCategoryDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .RemoveReference( - model: model, - reference: reference, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - public async Task RemoveReferences( - int providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await categorySubCategoryReferenceProvider - .RemoveReferences( - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategoryService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using System.Collections.Generic; -using xCategoryService.Interfaces; -using xCategoryService.Models.Dtos; - -namespace xCategoryService.Providers -{ - /// - /// Completely Exported Service ... - /// - public class XCategoryService : IXCategoryService - { - private readonly IXCategoryProvider categoryProvider; - private readonly IXSubCategoryProvider subCategoryProvider; - - public XCategoryService( - IXCategoryProvider categoryProvider, - IXSubCategoryProvider subCategoryProvider - ) - { - this.categoryProvider = categoryProvider; - this.subCategoryProvider = subCategoryProvider; - } - - // - #region Category Provider ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - public virtual async Task CategoryHasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - public virtual async Task GetCategoryResource( - int id, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .GetResource( - id: id, - cancellationToken: cancellationToken - ); - } - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AddCategory( - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .Add( - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Add Item by It's Locales ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddCategoryResource( - XCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .AddResource( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - public virtual async Task RemoveCategory( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .Remove( - id: id, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateCategory( - int id, - XCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .Update( - id: id, - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - public virtual async Task RefreshCategory( - XCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Get All Resources ... - /// - /// - /// - public virtual async Task> GetAllCategoryResources( - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .GetAllResources( - cancellationToken: cancellationToken - ); - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - public virtual async Task FindOneCategoryResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .FindOneResource( - predicate: predicate, - cancellationToken: cancellationToken - ); - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - public virtual async Task> FindManyCategoryResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .FindManyResource( - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryCategoryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - return await categoryProvider - .QueryResources( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - public virtual IAsyncEnumerable GetAllCategoryResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ) - { - // - return categoryProvider - .GetAllResourcesAsAsyncEnumerable( - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region SubCategory Provider ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - public virtual async Task SubCategoryHasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - public virtual async Task GetSubCategoryResource( - int id, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .GetResource( - id: id, - cancellationToken: cancellationToken - ); - } - - /// - /// Add Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AddSubCategory( - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .Add( - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddSubCategoryResource( - XSubCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .AddResource( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - public virtual async Task RemoveSubCategory( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .Remove( - id: id, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateSubCategory( - int id, - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .Update( - id: id, - item: item, - language: language, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - public virtual async Task RefreshSubCategory( - XSubCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Get All Resources ... - /// - /// - /// - public virtual async Task> GetAllSubCategoryResources( - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .GetAllResources( - cancellationToken: cancellationToken - ); - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - public virtual async Task FindOneSubCategoryResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .FindOneResource( - predicate: predicate, - cancellationToken: cancellationToken - ); - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - public virtual async Task> FindManySubCategoryResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .FindManyResource( - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - public virtual async Task> QuerySubCategoryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - return await subCategoryProvider - .QueryResources( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - } - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - public virtual IAsyncEnumerable GetAllSubCategoryResourcesAsAsyncEnumerable( - CancellationToken cancellationToken = default - ) - { - // - return subCategoryProvider - .GetAllResourcesAsAsyncEnumerable( - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategorySubCategoryReferenceProvider.cs - -using xCategoryService.Constants; -using xCategoryService.Interfaces; -using xCategoryService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public class XCategorySubCategoryReferenceProvider : XBaseCategoryProvider, IXCategorySubCategoryReferenceProvider - { - public XCategorySubCategoryReferenceProvider( - IXCategoryServiceProvider categoryProvider - ) : base( - categoryProvider: categoryProvider, - providedFor: XCategoryServiceConstants.SubCategoryReference - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XCategoryTitleResourceProvider.cs - -using xStringService.Providers; -using xCategoryService.Constants; -using xCategoryService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public class XCategoryTitleResourceProvider : XBaseItemResourceProvider, IXCategoryTitleResourceProvider - { - public XCategoryTitleResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XCategoryServiceConstants.CategoryTitleResourceIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XSubCategoryDescriptionResourceProvider.cs - -using xStringService.Providers; -using xCategoryService.Constants; -using xCategoryService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public class XSubCategoryDescriptionResourceProvider : XBaseItemResourceProvider, IXSubCategoryDescriptionResourceProvider - { - public XSubCategoryDescriptionResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XCategoryServiceConstants.SubCategoryDescriptionResourceIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XSubCategoryEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xCategoryService.Models.Entities; -using xCategoryService.Configurations.Entities; - -namespace xCategoryService.Providers -{ - public class XSubCategoryEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XSubCategoryEntityRegisterar() - : base(nameof(XSubCategoryEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XSubCategoryEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XSubCategoryProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xPushService.Constants; -using xPushService.Providers; -using System.Linq.Expressions; -using xCommons.Configurations; -using xDataService.Extensions; -using System.Collections.Generic; -using xDataService.Configuration; -using xCategoryService.Interfaces; -using xCategoryService.Models.Dtos; -using System.Runtime.CompilerServices; -using xCategoryService.Providers.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers -{ - public class XSubCategoryProvider : XBaseProvided, IXSubCategoryProvider - { - private readonly XAppConfiguration appConfiguration; - private readonly IXCategoryProvider categoryProvider; - private readonly IXSubCategoryServiceProvider provider; - private readonly XDataServiceConfiguration dataServiceConfiguration; - private readonly IXSubCategoryTitleResourceProvider titleResourceProvider; - private readonly IXSubCategoryDescriptionResourceProvider descriptionResourceProvider; - - public XSubCategoryProvider( - XAppConfiguration appConfiguration, - IXCategoryProvider categoryProvider, - IXSubCategoryServiceProvider provider, - XDataServiceConfiguration dataServiceConfiguration, - IXSubCategoryTitleResourceProvider titleResourceProvider, - IXSubCategoryDescriptionResourceProvider descriptionResourceProvider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { - this.provider = provider; - this.appConfiguration = appConfiguration; - this.categoryProvider = categoryProvider; - this.titleResourceProvider = titleResourceProvider; - this.dataServiceConfiguration = dataServiceConfiguration; - this.descriptionResourceProvider = descriptionResourceProvider; - } - - // - #region Overrides ... - public override bool IsOwned( - XSubCategoryDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XSubCategory item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - #endregion - - // - #region Actions ... - /// - /// Check Has Specified Locale or not ... - /// - /// - /// - /// - /// - public async Task HasLocale( - int id, - string language, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - id.IsValidIntId() && - !language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Resource ... - var resource = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Check Result ... - var result = - !resource.IsNullOrDefault() && - resource.Titles.Locales - .Any(x => x.Language - .Equals(language, System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Load an Item by all of it's Related Translations ... - /// - /// - /// - /// - public async Task GetResource( - int id, - CancellationToken cancellationToken = default - ) - { - // - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - var titleResource = await titleResourceProvider.GetResource( - identifier: id, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider.GetResource( - identifier: id, - cancellationToken: cancellationToken - ); - - // - // Reading Category Resource ... - XCategoryResourceDto categoryResourceDto = null; - try - { - var categoryDto = await categoryProvider.GetReference( - providedForId: id, - cancellationToken: cancellationToken - ); - if (!categoryDto.IsNullOrDefault()) - { - categoryResourceDto = await categoryProvider.GetResource( - id: categoryDto.Id, - cancellationToken: cancellationToken - ); - } - } - catch { } - - // - var result = new XSubCategoryResourceDto - { - Item = item, - Titles = titleResource, - Category = categoryResourceDto, - Descriptions = descriptionResource - }; - - // - return result; - } - - /// - /// Add an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - public async Task Add( - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize ... - language = - !language.IsNullOrEmpty() - ? language - : appConfiguration.DefaultLanguage; - - // - // Validate ... - var isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - try - { - // - var title = item.Title; - var description = item.Description; - - // - // Add Item Pure for ID Generating ... - item = await base.Add( - item: item, - userInfo: userInfo, - connectionId: null, // Since here We dont want notification ... - cancellationToken: cancellationToken - ); - isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - id = item.Id; - var titleResource = await titleResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = title, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = description, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Update Category Dto ... - item.Title = titleResource.Resource; - item.Description = descriptionResource.Resource; - item = await base.Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - catch - { - XException.InvalidArgs.Throw(); - } - - // - // Validate Id ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Retrieve Category Resourv=ce ... - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Sending Push Notification ... - isValid = - isValid && - !result.IsNullOrDefault(); - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Add Item by it's Locales and Reference ... - /// - /// - /// - /// - /// - /// - public async Task AddResource( - XSubCategoryResourceDto item, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !item.IsNullOrDefault() && - !item.Titles.IsNullOrDefault() && - item.Titles.Locales.HasChild() && - !item.Titles.Locales.Any(tl => - tl.Value.IsNullOrEmpty() || - tl.Language.IsNullOrEmpty()); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (item.Item.IsNullOrDefault()) - { - item.Item = new XSubCategoryDto(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - try - { - // - // Handle Category Generation ... - if (!item.Category.IsNullOrDefault()) - { - // - // Handle Category ... - try - { - // Try to Add Category ... - item.Category = await categoryProvider.Refresh( - resource: item.Category, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - // - // Add SubCategory for ID Generation ... - item.Item = await base.Add( - item: item.Item, - userInfo: userInfo, - connectionId: null, // Since here We dont want notification ... - cancellationToken: cancellationToken - ); - isValid = !item.Item.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - id = item.Item.Id; - - // - foreach (var il in item.Titles.Locales) - { - // - var title = il.Value; - var language = il.Language; - - // - var descriptionItem = - item.Descriptions.IsNullOrDefault() || - !item.Descriptions.Locales.HasChild() - ? null - : item.Descriptions.Locales - .FirstOrDefault(ides => - ides.Language - .Equals( - language, - StringComparison.InvariantCultureIgnoreCase)); - var description = - descriptionItem.IsNullOrDefault() - ? string.Empty - : descriptionItem.Value; - - // - // Try to Add Resources ... - var titleResource = await titleResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = title, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - var descriptionResource = await descriptionResourceProvider - .AddOrUpdateLocale( - identifier: id, - locale: new XLocaleResourceDto - { - Value = description, - Language = language - }, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Update Category Dto if not ... - if (item.Item.Title.IsNullOrEmpty() || - !item.Item.Title - .Equals( - titleResource.Resource, - StringComparison.InvariantCultureIgnoreCase) - ) - { - // - item.Item.Title = titleResource.Resource; - item.Item.Description = descriptionResource.Resource; - item.Item = await base.Update( - id: id, - item: item.Item, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - } - } - catch - { - XException.InvalidArgs.Throw(); - } - - // - // Validate Id ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Add Resource Reference to Category ... - isValid = await categoryProvider.AddReference( - providedForId: id, - connectionId: null, - model: item.Category.Item, - cancellationToken: cancellationToken - ); - - // - // Retrieve Category Resourv=ce ... - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Sending Push Notification ... - isValid = - isValid && - !result.IsNullOrDefault(); - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Remove Item for Specified Language ... - /// - /// - /// if null, Remove All - /// - /// - /// - /// - public async Task Remove( - int id, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = id.IsValidIntId(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Item Exists ... - isValid = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Validate Locale if Provided ... - isValid = - language.IsNullOrEmpty() || - await HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - if (language.IsNullOrEmpty()) - { - // - // Remove All ... - - // - // Titles ... - await titleResourceProvider.RemoveLocales( - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Descriptions ... - await descriptionResourceProvider.RemoveLocales( - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Remove Entity ... - await provider.RemoveAsync( - id: id, - softDelete: false, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - isValid = true; - result.Titles.Locales = []; - result.Descriptions.Locales = []; - } - else - { - // - // Remove Only One Locale, and if there is one, Remove all ... - - // - // Remove Title if Exists ... - isValid = await titleResourceProvider.HasLocale( - identifier: id, - language: language, - cancellationToken: cancellationToken - ); - if (isValid) - { - // - await titleResourceProvider.RemoveLocale( - identifier: id, - language: language, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Remove Description if Exists ... - isValid = await descriptionResourceProvider.HasLocale( - identifier: id, - language: language, - cancellationToken: cancellationToken - ); - if (isValid) - { - // - await descriptionResourceProvider.RemoveLocale( - identifier: id, - language: language, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Retrieve Resource ... - result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - // Check Has Locales ... - isValid = result.Titles.Locales.HasChild(); - if (!isValid) - { - // - // Remove Item ... - await provider.RemoveAsync( - id: id, - softDelete: false, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - result.Titles.Locales = []; - result.Descriptions.Locales = []; - } - - // - isValid = true; - } - - // - // Remove all Referencings ... - if (isValid) - { - await categoryProvider.RemoveReferences( - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - if (isValid) - { - // - // Send Push ... - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: - result.Titles.Locales.HasChild() - ? "DeleteLocale" - : XBaseEntityHubAction.Delete.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Update an Item for Specified Language ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task Update( - int id, - XSubCategoryDto item, - string language = null, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - id.IsValidIntId() && - !item.IsNullOrDefault() && - !language.IsNullOrEmpty() && - !item.Title.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Category Exists ... - isValid = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Check Locale Exists ... - isValid = await HasLocale( - id: id, - language: language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Retrieve Category Dto for Validate Owining ... - var dto = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - - // - // Check Permission ... - isValid = - !dto.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - (IsOwned( - item: dto, - userInfo: userInfo - ) || HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - // Retrieve Exists Item Resource ... - var resource = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - var titleUpdated = false; - var descriptionUpdated = false; - - // - // Update Title ... - resource.Titles.Locales - .ToList() - .ForEach(tl => - { - // - if (tl.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)) - { - // - titleUpdated = true; - tl.Value = item.Title; - } - }); - - // - // Update Description ... - resource.Descriptions.Locales - .ToList() - .ForEach(dl => - { - // - if (dl.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)) - { - // - descriptionUpdated = true; - dl.Value = item.Description; - } - }); - - // - // Validate Title and Description Updated ... - isValid = titleUpdated && descriptionUpdated; - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - resource = await Refresh( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return resource; - } - - /// - /// Refresh a Resource ... - /// - /// - /// - /// - /// - /// - public async Task Refresh( - XSubCategoryResourceDto resource, - string connectionId = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = - !resource.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Permission ... - isValid = HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var id = -1; - var isDelete = false; - XSubCategoryResourceDto result = null; - - // - // Check Item Exists ... - XSubCategoryDto dto = - (resource.Item.IsNullOrDefault() || - !resource.Item.Id.IsValidIntId()) - ? null - : await Get( - id: resource.Item.Id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - var isExists = !dto.IsNullOrDefault(); - - // - // Do Referesh Based on Existance ... - var isNew = - !isExists && - (resource.Item.IsNullOrDefault() || - !resource.Item.Id.IsValidIntId()); - if (isNew) - { - // - // Add ... - // In this Senario, for Add a Category by Providing Resource - // the item must clean, either Title and Description, and tge Locales Provided by Resource - // ust Contains Values ... - // the Add Starts by Titles and only Items Add Which has Titles, since Title is Mandatory - // and Description is Optional ... - isValid = - // - // Resource ... - (resource.Item.IsNullOrDefault() || - (!resource.Item.Id.IsValidIntId() && - resource.Item.Title.IsNullOrEmpty() && - resource.Item.Description.IsNullOrEmpty())) && - // - // Titles ... - !resource.Titles.IsNullOrDefault() && - resource.Titles.Locales.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Add Temp Category ... - var unique = Guid.NewGuid(); - var temp = new XSubCategoryDto - { - Title = $"TmpT_{unique}", - Description = $"TmpD_{unique}", - }; - temp = await provider.AddAsync( - item: temp, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - isValid = - !temp.IsNullOrDefault() && - temp.Id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - id = temp.Id; - - // - // Update Title and Description ... - var titleResource = titleResourceProvider.GetResourceTitle(id); - var descriptionResource = descriptionResourceProvider.GetResourceTitle(id); - temp.Title = titleResource; - temp.Description = descriptionResource; - temp = await provider.UpdateAsync( - id: id, - item: temp, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - - // - // Loop through Titles ... - foreach (var locale in resource.Titles.Locales) - { - // - // Add Or Update Locale ... - await titleResourceProvider.AddOrUpdateLocale( - locale: locale, - identifier: id, - connectionId: null, - cancellationToken: cancellationToken - ); - var desLocale = resource.Descriptions.Locales.FirstOrDefault( - dl => - dl.Language == locale.Language); - if (!desLocale.IsNullOrDefault()) - { - // - // Add Descriptions ... - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: desLocale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - } - } - else if (isExists) - { - // - // Re State ... - id = resource.Item.Id; - - // - // Try to Refresh Resource State ... - - // - // Check Delete ... - isDelete = !resource.Titles.Locales.HasChild(); - if (isDelete) - { - // - // Handle Delete ... - await Remove( - id: id, - language: null, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - } - else - { - // - // Handle Update ... - result = await GetResource( - id: id, - cancellationToken: cancellationToken - ); - - // - #region Remove ... - // - // Titles ... - var removeTitles = result.Titles.Locales.Where( - l => !resource.Titles.Locales.Any(r => r.Language.Equals(l.Language, System.StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in removeTitles) - { - // - await titleResourceProvider.RemoveLocale( - identifier: id, - connectionId: null, - language: locale.Language, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var removeDescriptions = result.Descriptions.Locales.Where( - l => !resource.Descriptions.Locales.Any(r => r.Language.Equals(l.Language, System.StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in removeDescriptions) - { - // - await descriptionResourceProvider.RemoveLocale( - identifier: id, - connectionId: null, - language: locale.Language, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region Update ... - // - // Titles ... - var updateTitles = result.Titles.Locales.Where( - l => resource.Titles.Locales.Any(r => - r.Value - .Equals(l.Value, StringComparison.InvariantCultureIgnoreCase) && - r.Language - .Equals(l.Language, StringComparison.InvariantCultureIgnoreCase) - ) - ); - foreach (var locale in updateTitles) - { - // - await titleResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var updateDescriptions = result.Descriptions.Locales.Where( - l => resource.Descriptions.Locales.Any(r => - r.Value - .Equals(l.Value, StringComparison.InvariantCultureIgnoreCase) && - r.Language - .Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in updateDescriptions) - { - // - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - #endregion - - // - #region New ... - // - // Titles ... - var newTitles = resource.Titles.Locales.Where( - l => !result.Titles.Locales.Any(r => r.Language.Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in newTitles) - { - // - await titleResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - - // - // Descriptions ... - var newDescriptions = resource.Descriptions.Locales.Where( - l => !result.Descriptions.Locales.Any(r => r.Language.Equals(l.Language, StringComparison.InvariantCultureIgnoreCase)) - ); - foreach (var locale in newDescriptions) - { - // - await descriptionResourceProvider.AddOrUpdateLocale( - identifier: id, - locale: locale, - connectionId: null, - cancellationToken: cancellationToken - ); - } - #endregion - } - } - - // - // Handle Category ... - if ( - !isDelete && - (isNew || isExists) && - !resource.Category.IsNullOrDefault()) - { - // - // Refresh Category ... - var category = await categoryProvider.Refresh( - userInfo: userInfo, - resource: resource.Category, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Handle SubCategory Referencings ... - var references = await categoryProvider.GetAllReferences( - providedForId: id, - cancellationToken: cancellationToken - ); - var hasReference = - references.HasChild() && - references.Any(r => r.Id == category.Item.Id); - if (!hasReference) - { - await categoryProvider.AddReference( - providedForId: id, - model: category.Item, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - // - // Validate Action ... - isValid = id.IsValidIntId(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Get Result ... - result = - isDelete - ? resource - : await GetResource( - id: id, - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - - // - // Send Notification ... - if (isValid) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: isNew - ? XBaseEntityHubAction.Add.GetStringValue() - : isDelete - ? XBaseEntityHubAction.Delete.GetStringValue() - : XBaseEntityHubAction.Update.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Get All Resources as Async Enumerable ... - /// - /// - /// - public async IAsyncEnumerable GetAllResourcesAsAsyncEnumerable( - [EnumeratorCancellation] CancellationToken cancellationToken = default - ) - { - // - var enumerable = provider.GetAllAsAsyncEnumerable( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id) - ); - - // - await foreach (var dto in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var resource = await GetResource( - id: dto.Id, - cancellationToken: cancellationToken - ); - yield return resource; - } - } - - /// - /// Get All Resources ... - /// - /// - /// - public async Task> GetAllResources( - CancellationToken cancellationToken = default - ) - { - // - var result = new List(); - - // - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - result.Add(item); - } - - // - return result; - } - - /// - /// Find One Resource ... - /// - /// - /// - /// - public async Task FindOneResource( - Expression> predicate = null, - CancellationToken cancellationToken = default - ) - { - // - var isApproved = false; - XSubCategoryResourceDto result = null; - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Detect Predicate Condition ... - isApproved = predicate.Compile()(item); - if (isApproved) - { - // - result = item; - break; - } - } - - // - return result; - } - - /// - /// Find Many Resource ... - /// - /// - /// - /// - /// - public async Task> FindManyResource( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var isApproved = false; - var result = new List(); - var enumerable = GetAllResourcesAsAsyncEnumerable(cancellationToken); - await foreach (var item in enumerable) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Detect Predicate Condition ... - isApproved = predicate.Compile()(item); - if (isApproved) - { - result.Add(item); - } - } - - // - // Apply Order ... - if (!orderBuilder.IsNull()) - { - // - result = - orderBuilder(result.AsQueryable()) - .ToList(); - } - - // - return result; - } - - /// - /// Retrieve Resources by Query Pattern ... - /// - /// - /// - /// - /// - /// - public async Task> QueryResources( - XQuery query = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(dataServiceConfiguration); - - // - var items = await FindManyResource( - predicate: predicate, - orderBuilder: orderBuilder, - cancellationToken: cancellationToken - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = [.. items], - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\XSubCategoryTitleResourceProvider.cs - -using xStringService.Providers; -using xCategoryService.Constants; -using xCategoryService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xCategoryService.Providers -{ - public class XSubCategoryTitleResourceProvider : XBaseItemResourceProvider, IXSubCategoryTitleResourceProvider - { - public XSubCategoryTitleResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XCategoryServiceConstants.SubCategoryTitleResourceIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XCategoryDtoHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XCategoryDtoHub : XBaseDtoHub, IXCategoryDtoHub - { - public XCategoryDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XCategoryRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XCategoryRepositoryService : XBaseRepositoryService, IXCategoryRepositoryService - { - public XCategoryRepositoryService( - IXCategoryRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XCategoryServiceProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XCategoryServiceProvider : XBaseDtoProvider, IXCategoryServiceProvider - { - public XCategoryServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXCategoryRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XSubCategoryDtoHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XSubCategoryDtoHub : XBaseDtoHub, IXSubCategoryDtoHub - { - public XSubCategoryDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XSubCategoryRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XSubCategoryRepositoryService : XBaseRepositoryService, IXSubCategoryRepositoryService - { - public XSubCategoryRepositoryService( - IXSubCategoryRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Dtos\XSubCategoryServiceProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xCategoryService.Models.Dtos; -using xCategoryService.Interfaces.Dtos; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.Dtos -{ - public class XSubCategoryServiceProvider : XBaseDtoProvider, IXSubCategoryServiceProvider - { - public XSubCategoryServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXSubCategoryRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryEFRepository : XBaseEFRepository, IXCategoryRepository - where TContext : XDbContext - { - public XCategoryEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXCategoryKeyGenerator keyGenerator = null, - IXCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryEntityHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryEntityHub : XBaseEntityHub, IXCategoryEntityHub - { - public XCategoryEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryInMemoryRepository : XBaseInMemoryRepository, IXCategoryRepository - { - public XCategoryInMemoryRepository( - XDataServiceConfiguration configuration, - IXCategoryKeyGenerator keyGenerator = null, - IXCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryKeyGenerator.cs - -using xDataService.Providers; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryKeyGenerator : XIntKeyGenerator, IXCategoryKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryMongoRepository : XBaseMongoRepository, IXCategoryRepository - { - public XCategoryMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXCategoryKeyGenerator keyGenerator = null, - IXCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryRepositoryEvents.cs - -using xDataService.Providers; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryRepositoryEvents : XBaseRepositoryEvents, IXCategoryRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategoryRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XCategoryRepositoryProvider : XBaseEntityProvider, IXCategoryRepositoryProvider - { - public XCategoryRepositoryProvider( - IHubContext hub, - IXCategoryRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XCategorySeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public abstract class XCategorySeederBase : XBaseDbSeeder, IXCategorySeeder - { - protected XCategorySeederBase( - string entity, - string database, - IXCategoryRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryEFRepository : XBaseEFRepository, IXSubCategoryRepository - where TContext : XDbContext - { - public XSubCategoryEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXSubCategoryKeyGenerator keyGenerator = null, - IXSubCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryEntityHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryEntityHub : XBaseEntityHub, IXSubCategoryEntityHub - { - public XSubCategoryEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryInMemoryRepository : XBaseInMemoryRepository, IXSubCategoryRepository - { - public XSubCategoryInMemoryRepository( - XDataServiceConfiguration configuration, - IXSubCategoryKeyGenerator keyGenerator = null, - IXSubCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryKeyGenerator.cs - -using xDataService.Providers; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryKeyGenerator : XIntKeyGenerator, IXSubCategoryKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryMongoRepository : XBaseMongoRepository, IXSubCategoryRepository - { - public XSubCategoryMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXSubCategoryKeyGenerator keyGenerator = null, - IXSubCategoryRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryRepositoryEvents.cs - -using xDataService.Providers; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryRepositoryEvents : XBaseRepositoryEvents, IXSubCategoryRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategoryRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public class XSubCategoryRepositoryProvider : XBaseEntityProvider, IXSubCategoryRepositoryProvider - { - public XSubCategoryRepositoryProvider( - IHubContext hub, - IXSubCategoryRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\Entities\XSubCategorySeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.Entities -{ - public abstract class XSubCategorySeederBase : XBaseDbSeeder, IXSubCategorySeeder - { - protected XSubCategorySeederBase( - string entity, - string database, - IXSubCategoryRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XCategoryGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xCategoryService.Constants; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XCategoryGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXCategoryGraphQLTypeHelper - { - public XCategoryGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XCategoryServiceConstants.XCategoryCollectionName; - } - - public override string GetInQuerySingleName() - { - return XCategoryServiceConstants.XCategorySingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XCategoryGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XCategoryGraphQuery : XBaseGraphQLQuery - { - public XCategoryGraphQuery( - XDataServiceConfiguration configuration, - IXCategoryRepository repository, - IXCategoryGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XCategoryGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xCategoryService.Providers.GraphQL -{ - public class XCategoryGraphSchema : Schema - { - public XCategoryGraphSchema(IServiceProvider services) : base(services) - { - Query = (XCategoryGraphQuery)services.GetService(typeof(XCategoryGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XCategoryGraphType.cs - -using xDataService.GraphQL; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XCategoryGraphType : XBaseGraphObjectType - { - public XCategoryGraphType() : base() - { - Field(x => x.Title); - Field(x => x.Description); - Field(x => x.References); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XSubCategoryGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xCategoryService.Constants; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XSubCategoryGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXSubCategoryGraphQLTypeHelper - { - public XSubCategoryGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XCategoryServiceConstants.XSubCategoryCollectionName; - } - - public override string GetInQuerySingleName() - { - return XCategoryServiceConstants.XSubCategorySingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XSubCategoryGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xCategoryService.Models.Entities; -using xCategoryService.Interfaces.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XSubCategoryGraphQuery : XBaseGraphQLQuery - { - public XSubCategoryGraphQuery( - XDataServiceConfiguration configuration, - IXSubCategoryRepository repository, - IXSubCategoryGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XSubCategoryGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xCategoryService.Providers.GraphQL -{ - public class XSubCategoryGraphSchema : Schema - { - public XSubCategoryGraphSchema(IServiceProvider services) : base(services) - { - Query = (XSubCategoryGraphQuery)services.GetService(typeof(XSubCategoryGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCategoryService\Providers\GraphQL\XSubCategoryGraphType.cs - -using xDataService.GraphQL; -using xCategoryService.Models.Entities; - -namespace xCategoryService.Providers.GraphQL -{ - public class XSubCategoryGraphType : XBaseGraphObjectType - { - public XSubCategoryGraphType() : base() - { - Field(x => x.Title); - Field(x => x.Description); - Field(x => x.References); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xClient-20261109_153842.txt b/Documents/GeneratedContext/xDashboard-xClient-20261112_120855.txt similarity index 97% rename from Documents/GeneratedContext/xDashboard-xClient-20261109_153842.txt rename to Documents/GeneratedContext/xDashboard-xClient-20261112_120855.txt index ad15342..dedd36a 100644 --- a/Documents/GeneratedContext/xDashboard-xClient-20261109_153842.txt +++ b/Documents/GeneratedContext/xDashboard-xClient-20261112_120855.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-device\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-device\types\index.d.ts // Type definitions for Apache Cordova Device plugin // Project: https://github.com/apache/cordova-plugin-device @@ -38,7 +38,7 @@ interface Device { declare var device: Device; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\src\wp\ResolutionHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\src\wp\ResolutionHelper.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -80,7 +80,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\src\wp\SplashScreen.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\src\wp\SplashScreen.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -338,7 +338,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-splashscreen\types\index.d.ts // Type definitions for Apache Cordova Splashscreen plugin // Project: https://github.com/apache/cordova-plugin-splashscreen @@ -358,7 +358,7 @@ interface Navigator { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-statusbar\src\wp\StatusBar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-statusbar\src\wp\StatusBar.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -502,7 +502,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-statusbar\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\plugins\cordova-plugin-statusbar\types\index.d.ts // Type definitions for Apache Cordova StatusBar plugin // Project: https://github.com/apache/cordova-plugin-statusbar @@ -582,7 +582,7 @@ interface StatusBar { declare var StatusBar: StatusBar; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\global.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\global.d.ts interface MediaRecorderOptions { mimeType?: string; @@ -620,7 +620,7 @@ declare var MediaRecorder: { isTypeSupported?(type: string): boolean; }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\index.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\index.html @@ -669,7 +669,7 @@ declare var MediaRecorder: { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\main.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\main.ts import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @@ -684,7 +684,7 @@ if (environment.production) { platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\polyfills.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\polyfills.ts /** * This file includes polyfills needed by Angular and is loaded before the app. @@ -740,14 +740,14 @@ import 'zone.js'; // Included with Angular CLI. * APPLICATION IMPORTS */ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\typings.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\typings.d.ts interface Window { MediaRecorder: any; require: NodeRequire; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\app-routing.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\app-routing.module.ts import { NgModule } from '@angular/core'; import { HomePage } from './pages/home/home.page'; @@ -879,16 +879,16 @@ const routes: Routes = [ }) export class AppRoutingModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\app.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\app.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\app.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\app.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\app.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\app.component.ts import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; @@ -908,7 +908,7 @@ export class AppComponent { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\app.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\app.module.ts import { XCanDeactivateGuard, @@ -1068,7 +1068,7 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; }) export class AppModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\app.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\app.config.ts import { DefaultLocale, @@ -1280,7 +1280,7 @@ export const xSharedConfig: XSharedConfig = { ...xAppSharedConfig, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\audio.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\audio.config.ts import { XNotificationSound, XActionType } from 'x-framework-core'; @@ -1299,7 +1299,7 @@ export const NotificationAudioSources: XNotificationSound[] = [ }, ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\localization.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\localization.config.ts import { XLocale, XLanguageDescriptor } from 'x-framework-core'; import { TagLocalizationResources } from '../views/tags/v-tag.configs'; @@ -5127,7 +5127,7 @@ export const AvailableTranslationResources: XLanguageDescriptor[] = [ }, ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\page.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\page.config.ts import { XUserRoleInfo, @@ -5613,7 +5613,7 @@ export async function getNavPages( //#endregion //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\x-api.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\x-api.config.ts import { XCONFIG } from './x.config'; import { XApiConfiguration } from 'x-framework-identity-sdk'; @@ -5629,7 +5629,7 @@ export const XAPI_CONFIG = new XApiConfiguration({ revisionSecretKey: XCONFIG.secretKey, }); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\config\x.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\config\x.config.ts import { XConfig } from './app.config'; import { InjectionToken } from '@angular/core'; @@ -5641,7 +5641,7 @@ export const XCONFIG: XConfig = JSON.parse( export const X_CONFIG = new InjectionToken('x_config'); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\account.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\account.module.ts import { NgModule } from '@angular/core'; import { LoginPage } from './login/login.page'; @@ -5778,7 +5778,7 @@ import { SearchProfilesPage } from './search-profiles/search-profiles.page'; }) export class AccountPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\account.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\account.typings.ts export const LoginTasks = { Login: 'login', @@ -5786,7 +5786,7 @@ export const LoginTasks = { ResendEmailVerificationLink: 'resend_email_verification_link', }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.html @@ -5803,10 +5803,10 @@ export const LoginTasks = { Change Password ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\change-password\change-password.page.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -5829,7 +5829,7 @@ export class ChangePasswordPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.html @@ -5846,10 +5846,10 @@ export class ChangePasswordPage extends VPageComponent { Email Confirm ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\email-confirm\email-confirm.page.ts import { XSideType } from 'x-framework-components'; import { ChangeDetectionStrategy, Component } from '@angular/core'; @@ -5879,7 +5879,7 @@ export class EmailConfirmPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.html @@ -5905,10 +5905,10 @@ export class EmailConfirmPage extends VPageComponent { > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\login\login.page.ts import { XTask, @@ -6261,7 +6261,7 @@ export class LoginPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.html @@ -6277,10 +6277,10 @@ export class LoginPage extends VPageComponent { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\logout\logout.page.ts import { Pages } from 'src/app/config/page.config'; import { XSideType } from 'x-framework-components'; @@ -6357,7 +6357,7 @@ export class LogoutPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.html @@ -6374,10 +6374,10 @@ export class LogoutPage extends VPageComponent { Phone Confirm ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\phone-confirm\phone-confirm.page.ts import { XSideType } from 'x-framework-components'; import { ChangeDetectionStrategy, Component } from '@angular/core'; @@ -6407,7 +6407,7 @@ export class PhoneConfirmPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.html @@ -6424,10 +6424,10 @@ export class PhoneConfirmPage extends VPageComponent { Profile ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\profile\profile.page.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -6450,7 +6450,7 @@ export class ProfilePage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.html @@ -6474,10 +6474,10 @@ export class ProfilePage extends VPageComponent { > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\register\register.page.ts import { XSideType } from 'x-framework-components'; import { VPageComponent } from 'src/app/views/public-api'; @@ -6542,7 +6542,7 @@ export class RegisterPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.html @@ -6559,10 +6559,10 @@ export class RegisterPage extends VPageComponent { Reset Password ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\reset-password\reset-password.page.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -6592,7 +6592,7 @@ export class ResetPasswordPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.html @@ -6609,10 +6609,10 @@ export class ResetPasswordPage extends VPageComponent { Search Profiles ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\account\search-profiles\search-profiles.page.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -6635,7 +6635,7 @@ export class SearchProfilesPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.html @@ -6660,10 +6660,10 @@ export class SearchProfilesPage extends VPageComponent { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\error\error.page.ts import { Pages } from 'src/app/config/page.config'; import { XButtonType } from 'x-framework-components'; @@ -6745,7 +6745,7 @@ export class ErrorPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-page.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-page.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -6794,7 +6794,7 @@ import { FilesManagementPage } from './files-management/files-management.page'; }) export class FilesPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.html @@ -7063,7 +7063,7 @@ export class FilesPageModule {} > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.scss .v-item, .v-list-item, @@ -7086,7 +7086,7 @@ export class FilesPageModule {} } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-base\files-base.provider.page.ts import { Component, @@ -9349,14 +9349,14 @@ export abstract class FilesBaseProviderPage extends VQueryPresenterBasePage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.scss @import '../files-base//files-base.provider.page.scss'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-explorer\files-explorer.page.ts import { Observable } from 'rxjs'; import { ChangeDetectionStrategy, Component } from '@angular/core'; @@ -9401,14 +9401,14 @@ export class FilesExplorerPage extends FilesBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.scss @import '../files-base//files-base.provider.page.scss'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\files\files-management\files-management.page.ts import { Observable } from 'rxjs'; import { Component, ChangeDetectionStrategy } from '@angular/core'; @@ -9453,7 +9453,7 @@ export class FilesManagementPage extends FilesBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.html @@ -9469,10 +9469,10 @@ export class FilesManagementPage extends FilesBaseProviderPage { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\home\home.page.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -9531,7 +9531,7 @@ export class HomePage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.html @@ -9547,10 +9547,10 @@ export class HomePage extends VPageComponent { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.page.ts import { XStandardType } from 'x-framework-core'; import { XSideType } from 'x-framework-components'; @@ -9620,10 +9620,10 @@ export class LandingPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.typing.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\landing\landing.typing.ts -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.html @@ -9639,10 +9639,10 @@ export class LandingPage extends VPageComponent { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\not-authorized\not-authorized.page.ts import { Pages } from 'src/app/config/page.config'; import { Component, ChangeDetectionStrategy } from '@angular/core'; @@ -9680,7 +9680,7 @@ export class NotAuthorizedPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.html @@ -9696,10 +9696,10 @@ export class NotAuthorizedPage extends VPageComponent { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\startup\startup.page.ts import { XPage, @@ -9882,7 +9882,7 @@ export class StartupPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-page.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-page.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -9931,7 +9931,7 @@ import { TagsManagementPage } from './tags-management/tags-management.page'; }) export class TagsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.html @@ -10174,7 +10174,7 @@ export class TagsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.scss .v-item, .v-list-item, @@ -10184,7 +10184,7 @@ export class TagsPageModule {} width: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-base\tags-base.provider.page.ts import { Component, @@ -11954,14 +11954,14 @@ export abstract class TagsBaseProviderPage extends VQueryPresenterBasePage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.scss @import '../tags-base/tags-base.provider.page.scss'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-explorer\tags-explorer.page.ts import { Observable } from 'rxjs'; import { toNumber } from 'x-framework-core'; @@ -12007,14 +12007,14 @@ export class TagsExplorerPage extends TagsBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.scss @import '../tags-base/tags-base.provider.page.scss'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tags\tags-management\tags-management.page.ts import { Observable } from 'rxjs'; import { toNumber } from 'x-framework-core'; @@ -12060,7 +12060,7 @@ export class TagsManagementPage extends TagsBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\tools\common.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\tools\common.tools.ts import { XLocale } from 'x-framework-core'; import { AppResourceIDs } from 'src/app/config/localization.config'; @@ -12077,7 +12077,7 @@ export function getLocaleResourceID(locale: XLocale) { return locale; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-page.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-page.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -12131,7 +12131,7 @@ import { WebinarsManagementPage } from './webinars-management/webinars-managemen }) export class WebinarsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.html @@ -12402,10 +12402,10 @@ export class WebinarsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-base\webinars-base.provider.page.ts import { Component, @@ -14933,13 +14933,13 @@ export abstract class WebinarsBaseProviderPage extends VQueryPresenterBasePage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-explorer\webinars-explorer.page.ts import { Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; @@ -14990,13 +14990,13 @@ export class WebinarsExplorerPage extends WebinarsBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.page.ts import { Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; @@ -15047,7 +15047,7 @@ export class WebinarsManagementPage extends WebinarsBaseProviderPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\pages\webinars\webinars-management\webinars-management.typings.ts import { isValueInEnum } from 'src/app/views/public-api'; @@ -15062,7 +15062,7 @@ export function isWebinarsManagementTask(value: string, forceExactSames: boolean return isValueInEnum(value, Object.assign(WebinarsManagementTask, {}), forceExactSames); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\public-api.ts // //#region Services ... @@ -15084,7 +15084,7 @@ export * from './services/x-scrolling-provider.service' // Module ... export * from './shared.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\shared.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -15096,7 +15096,7 @@ import { CommonModule } from '@angular/common'; }) export class SharedModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\services\shared.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\services\shared.service.ts import { XParam, @@ -15360,7 +15360,7 @@ export class SharedService extends XLoggable { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\services\x-content-share-service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\services\x-content-share-service.ts import { Injectable } from '@angular/core'; import { isNullOrUndefined, XBaseService } from 'x-framework-core'; @@ -15410,7 +15410,7 @@ export class XContentShareService extends XBaseService { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\services\x-electron.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\services\x-electron.service.ts import { getMills, @@ -15675,7 +15675,7 @@ export class XElectronService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\services\x-media-devices.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\services\x-media-devices.service.ts import { Injectable } from '@angular/core'; import { isValueInEnum } from 'src/app/views/tools/v-base.tools'; @@ -15917,7 +15917,7 @@ export class XMediaDevicesService extends XLoggable { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\services\x-scrolling-provider.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\services\x-scrolling-provider.service.ts import { Injectable } from '@angular/core'; import { @@ -16004,13 +16004,13 @@ export class XScrollingProviderService extends XLoggable { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\typings\shared.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\typings\shared.typings.ts export const XSharedServiceKeys = { PushConnectionID: 'PCID', }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\shared\typings\x-electron.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\shared\typings\x-electron.typings.ts import * as Electron from 'electron'; import { XBaseDto } from 'x-framework-core'; @@ -16033,7 +16033,7 @@ export interface XElectronMessageDto extends XBaseDto { channel?: XElectronChannelIdentifier; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\public-api.ts // // Tools ... @@ -16217,7 +16217,7 @@ export * from './webinar/v-webinar-connect/v-webinar-connect.component'; // Module ... export * from './views.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\views.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\views.module.ts import { XFrameworkCoreModule, @@ -16587,7 +16587,7 @@ import { VRegisterComponent } from './account/v-register/v-register.component'; }) export class ViewsModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\account.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\account.configs.ts import { XIconNames } from 'x-framework-components'; import { XSimplePage } from '../typings/simple.page.typings'; @@ -17346,7 +17346,7 @@ export const Account: XSimplePage = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.scss @import "../../../../theme/theme.scss"; @@ -17513,7 +17513,7 @@ h6 { clip-path: circle(); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.component.ts import { Input, @@ -17695,7 +17695,7 @@ export class VAvatarComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-avatar\v-avatar.typings.ts export enum VAvatarModalContext { Modal = 'modal', @@ -17714,7 +17714,7 @@ export enum VAvatarReturnAction { export type VAvatarReturnActionIdentifier = VAvatarReturnAction | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.scss @import "../../../../theme/theme.scss"; @@ -17954,7 +17954,7 @@ export type VAvatarReturnActionIdentifier = VAvatarReturnAction | string; display: block; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.component.ts import { Input, @@ -18584,7 +18584,7 @@ export class VFriendshipComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.tools.ts import { isNullOrUndefined, @@ -19003,7 +19003,7 @@ export function isFriendshipTask(name: XFriendshipTasksIdentifier) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-friendship\v-friendship.typings.ts import { XColorIdentifier, @@ -19181,15 +19181,15 @@ export const defaultFriendshipUnblockDescriptor: FriendshipActionDescriptor = { color: XColorWithBrightness.PrimaryShade, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-login\v-login.component.ts import { Output, @@ -19571,7 +19571,7 @@ export class VLoginComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.html
    { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.scss @import "../../../../theme/theme.scss"; @@ -19739,7 +19739,7 @@ h6 { clip-path: circle(); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.component.ts import { Input, @@ -20025,7 +20025,7 @@ export class VProfileComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-profile\v-profile.typings.ts export enum VProfileModalContext { Modal = 'modal', @@ -20042,7 +20042,7 @@ export enum VProfileComponentTasks { GetProfile = 'egt_profile', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.html @@ -20117,10 +20117,10 @@ export enum VProfileComponentTasks { Terms and Conditions ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.component.ts import { XTask, @@ -20506,7 +20506,7 @@ export class VRegisterComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.tools.ts import { VRegistrationSteps } from './v-register.typings'; import { AccountLocalizationResourceIDs } from '../account.configs'; @@ -20551,7 +20551,7 @@ export function getRegistrationStepResourceID(step: VRegistrationSteps) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-register\v-register.typings.ts import { isValueInEnum } from '../../tools/v-base.tools'; import { hasChild, isNullOrUndefined } from 'x-framework-core'; @@ -20621,13 +20621,13 @@ export function isContainsRegistrationTask(value: string) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.component.ts import { Input } from '@angular/core'; import { @@ -20742,7 +20742,7 @@ export class VTermsComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-terms\v-terms.typings.ts import { isValueInEnum } from '../../tools/v-base.tools'; @@ -20763,7 +20763,7 @@ export function isVTermsPresentType(value: string) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.html @@ -21881,7 +21881,7 @@ export function isVTermsPresentType(value: string) { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.scss :host { --avatar-size: 40px; @@ -21962,7 +21962,7 @@ export function isVTermsPresentType(value: string) { direction: ltr; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.component.ts import { Input, @@ -23692,7 +23692,7 @@ export class VUserComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.tools.ts import { toNormalString, @@ -23949,7 +23949,7 @@ export function getUserGenderResourceId(user: XUserProfileDto) { return getGenderResourceId(user.gender); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\account\v-user\v-user.typings.ts import { XStandardType, @@ -24049,7 +24049,7 @@ export class VUserDtoContainer extends VBaseDtoContainer { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\classes\v-base.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\classes\v-base.component.ts import { Inject, @@ -24294,7 +24294,7 @@ export abstract class VBaseInCardComponent extends XComponentCardContainerCompon //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\constants\actionbar.defaults.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\constants\actionbar.defaults.ts import { XColorWithBrightness } from 'x-framework-core'; import { AppResourceIDs } from 'src/app/config/localization.config'; @@ -24461,7 +24461,7 @@ export const defaultStopRecordActionBar: XSimpleActionBarItem = { iconColor: XColorWithBrightness.Danger, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\constants\button.defaults.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\constants\button.defaults.ts import { XIconNames, @@ -24506,7 +24506,7 @@ export const defaultCopyToClipboardActionButton: VActionButtonConfig = { // iconColor: XColorWithBrightness.Tertiary // } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\constants\fab.defaults.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\constants\fab.defaults.ts import { XIconNames, @@ -24681,7 +24681,7 @@ export const defaultOptionsFabItem: XSimpleFabItem = { horizontal: XFabHorizontalSlot.END, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\constants\slide.options.defaults.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\constants\slide.options.defaults.ts import { XIconNames } from 'x-framework-components'; import { AppResourceIDs } from 'src/app/config/localization.config'; @@ -24759,7 +24759,7 @@ export const defaultConnectSlideOption = { color: XColorWithBrightness.Success, } as XSimpleListItemSlideOption; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\directives\x-focused-provider.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\directives\x-focused-provider.directive.ts import { isNullOrEmptyString, isNullOrUndefined } from 'x-framework-core'; import { Input, Directive, Renderer2, AfterViewInit } from '@angular/core'; @@ -24819,7 +24819,7 @@ export class XFocusedProviderDirective implements AfterViewInit { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\directives\x-html-include.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\directives\x-html-include.directive.ts import { Input, @@ -24877,7 +24877,7 @@ export class XHTMLIncludeDirective implements OnChanges { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\directives\x-insert-view-ref.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\directives\x-insert-view-ref.directive.ts import { Directive, Input, ViewContainerRef, ViewRef } from '@angular/core'; @@ -24900,7 +24900,7 @@ export class XInsertViewRefDirective { constructor(private container: ViewContainerRef) {} } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\directives\x-on-escape-pressed.global.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\directives\x-on-escape-pressed.global.directive.ts import { Directive, HostListener, Output, EventEmitter } from '@angular/core'; @@ -24922,7 +24922,7 @@ export class XOnEscapePressedGlobalDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\directives\x-render-component.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\directives\x-render-component.directive.ts import { Type, @@ -25046,7 +25046,7 @@ export class XRenderComponentDirective implements OnChanges { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file.configs.ts import { XIconNames } from "x-framework-components"; import { XSimplePage } from "../typings/simple.page.typings"; @@ -25368,7 +25368,7 @@ export const Files: XSimplePage = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file.tools.ts import { hasChild, @@ -25585,7 +25585,7 @@ export function getCanAddFileStatusByFilesCount( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.html @@ -25697,10 +25697,10 @@ export function getCanAddFileStatusByFilesCount( > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.component.ts import { Input, @@ -26666,7 +26666,7 @@ export class VFileComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file\v-file.typings.ts import { isValueInEnum } from '../../tools/v-base.tools'; @@ -26690,7 +26690,7 @@ export function isVFilePresentType(value: string) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.scss @import "../../../../theme/theme.scss"; @@ -26872,7 +26872,7 @@ h6 { overflow: scroll; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.component.ts import { Input, @@ -27145,7 +27145,7 @@ export class VFileInputComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-file-input\v-file-input.typings.ts import { VFileComponent } from '../v-file/v-file.component'; @@ -27184,7 +27184,7 @@ export type VFileInputFilePrperties = Pick< | 'fileUploadMinAllowedFileSizeException' >; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.html @@ -27337,7 +27337,7 @@ export type VFileInputFilePrperties = Pick< > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.scss .v-files-label { // @@ -27365,7 +27365,7 @@ export type VFileInputFilePrperties = Pick< } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.component.ts import { Input, @@ -28115,7 +28115,7 @@ export class VFilesPresenterComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-files-presenter\v-files-presenter.typings.ts import { XFileDto } from 'x-saherelm-api-sdk'; import { XBaseActionModel } from 'x-framework-components'; @@ -28171,7 +28171,7 @@ export interface VFilesPresenterModelState { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.html @@ -28387,7 +28387,7 @@ export interface VFilesPresenterModelState { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.scss :host { --thumbnail-size: 32px; @@ -28445,7 +28445,7 @@ export interface VFilesPresenterModelState { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.component.ts import { isImage, @@ -29091,7 +29091,7 @@ export class VMediaComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.config.ts // //#region Localization Configuration ... @@ -29145,7 +29145,7 @@ export const MediaLocalizationResources = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\files\v-media\v-media.typings.ts import { isString, @@ -29324,7 +29324,7 @@ export function isVMediaAction(value: string) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-string.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-string.tools.ts import { XLocale } from 'x-framework-core'; import { AppResourceIDs } from 'src/app/config/localization.config'; @@ -29341,7 +29341,7 @@ export function getLanguageResourceID(locale: XLocale | string) { return locale; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-string.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-string.typings.ts export enum StringTasks { Add = 'add_string_resource', @@ -29349,7 +29349,7 @@ export enum StringTasks { AddResource = 'add_resource_string', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.html @@ -29362,10 +29362,10 @@ export enum StringTasks { {{ item.data }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-locale\v-locale.component.ts import { Component, @@ -29991,7 +29991,7 @@ export class VLocaleComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.html @@ -30017,10 +30017,10 @@ export class VLocaleComponent extends VBaseDtoComponent { > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-resource\v-resource.component.ts import { Component, @@ -30319,7 +30319,7 @@ export class VResourceComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.html @@ -30332,10 +30332,10 @@ export class VResourceComponent extends VBaseDtoComponent { {{ item.data }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\string\v-string\v-string.component.ts import { Component, @@ -31024,7 +31024,7 @@ export class VStringComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag.configs.ts import { XIconNames } from 'x-framework-components'; import { XSimplePage } from '../typings/simple.page.typings'; @@ -31238,7 +31238,7 @@ export const Tags: XSimplePage = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag.tools.ts import { nameof, @@ -31280,7 +31280,7 @@ export function toXTagDto(value: any) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.html @@ -31346,7 +31346,7 @@ export function toXTagDto(value: any) {
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.scss .v-references-list { padding: { @@ -31356,7 +31356,7 @@ export function toXTagDto(value: any) { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.component.ts import { Input, @@ -31765,7 +31765,7 @@ export class VTagComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag\v-tag.typings.ts import { XBaseActionModel } from 'x-framework-components'; import { isValueInEnum } from '../../tools/v-base.tools'; @@ -31802,7 +31802,7 @@ export function isVTagAction(value: string) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.scss @import "../../../../theme/theme.scss"; @@ -31968,7 +31968,7 @@ h6 { overflow: scroll; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.component.ts import { Input, @@ -32175,7 +32175,7 @@ export class VTagInputComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tag-input\v-tag-input.typings.ts export enum VTagInputModalContext { Modal = 'modal', @@ -32193,7 +32193,7 @@ export enum VTagInputReturnAction { export type VTagInputReturnActionIdentifier = VTagInputReturnAction | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.html @@ -32397,7 +32397,7 @@ export type VTagInputReturnActionIdentifier = VTagInputReturnAction | string;
    {{ tag }}
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.scss .v-tags-label { // @@ -32418,7 +32418,7 @@ export type VTagInputReturnActionIdentifier = VTagInputReturnAction | string; } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.component.ts import { Input, @@ -33135,7 +33135,7 @@ export class VTagsPresenterComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tags\v-tags-presenter\v-tags-presenter.typings.ts import { isValueInEnum } from '../../tools/v-base.tools'; import { XBaseActionModel } from 'x-framework-components'; @@ -33191,7 +33191,7 @@ export interface VTagsPresenterModelState { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tests\test-video-player.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tests\test-video-player.html @@ -33271,7 +33271,7 @@ export interface VTagsPresenterModelState { poster="https://www.sony.co.jp/en/Products/di_photo-gallery/images/extralarge/1887.JPG" > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\template.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\template.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.html @@ -33356,10 +33356,10 @@ export interface VTagsPresenterModelState {
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tests\v-icons-presenter\v-icons-presenter.component.ts import { XIconIdentifier, XListItem } from 'x-framework-components'; import { VBaseInCardComponent } from '../../classes/v-base.component'; @@ -33446,7 +33446,7 @@ export class VIconsPresenterComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tools\action-provider.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tools\action-provider.tools.ts import { Subject } from 'rxjs'; import { XBaseActionModel } from 'x-framework-components'; @@ -33493,7 +33493,7 @@ export function sendAction(arg: { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tools\date.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tools\date.tools.ts import { XLocale, @@ -33579,7 +33579,7 @@ export function getEventDateTimeFromatString(locale?: XLocale) { return 'YYYY-MM-DD HH:mm'; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\tools\v-base.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\tools\v-base.tools.ts import { XLocale, @@ -33688,7 +33688,7 @@ export function isValueInEnum( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\common.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\common.typings.ts import { XKey, @@ -33758,7 +33758,7 @@ export function getQuerySelectorOfSpecifiedAttribute( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\dto.common.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\dto.common.typings.ts import { IVBaseDtoContainer } from "../v-dto/v-dto.typings"; @@ -33811,7 +33811,7 @@ export type VDtoCommonProperties = Partial< > >; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.actionbar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.actionbar.typings.ts import { XStandardType, @@ -33840,7 +33840,7 @@ export interface XSimpleActionBarItem { handler?: (model?: XActionBarActionFiredModel) => XStandardType; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.fab.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.fab.typings.ts import { hasChild, @@ -33978,7 +33978,7 @@ export async function toSimpleFabItems( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.form.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.form.typings.ts import { XLocale, @@ -34115,7 +34115,7 @@ export interface XSimpleFormConfig { errorHandlers?: Array; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.list-item.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.list-item.typings.ts import { toArray, @@ -34226,7 +34226,7 @@ export async function toSimpleListItem(item: XListItem) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.page.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\simple.page.typings.ts import { XResourceIdentifier } from "x-framework-core"; @@ -34241,7 +34241,7 @@ export interface XSimplePage { description?: XResourceIdentifier; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\v-base-form.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\v-base-form.typings.ts import { XBaseActionModel } from 'x-framework-components'; @@ -34284,7 +34284,7 @@ export interface VBaseFormViewCustomStates { payload?: any; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\typings\x.state.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\typings\x.state.enum.ts export enum XAppState { UserProfile = 'user_profile', @@ -34292,7 +34292,7 @@ export enum XAppState { export type AppStateIdentifier = XAppState | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.scss :host { --applied-color: var(--x-color-primary-contrast); @@ -35281,7 +35281,7 @@ export type AppStateIdentifier = XAppState | string; } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.component.ts import { Input, @@ -35577,7 +35577,7 @@ export class VDto extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-dto\v-dto.typings.ts import { Inject, @@ -38960,7 +38960,7 @@ export abstract class VBaseDtoComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.html @@ -39063,13 +39063,13 @@ export abstract class VBaseDtoComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.scss .v-error-title-text::after { content: ":"; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-error\v-error.component.ts import { isNullOrEmptyString, @@ -39188,7 +39188,7 @@ export class VErrorComponent extends VBaseInCardComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.html @@ -39312,14 +39312,14 @@ export class VErrorComponent extends VBaseInCardComponent { Nothing ... -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.scss .v-lazy-view-loader { text-align: center; min-height: 50px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.component.ts import { Type, @@ -39852,7 +39852,7 @@ export class VLazyView //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-lazy-view\v-lazy-view.typings.ts import { isValueInEnum } from "../tools/v-base.tools"; @@ -39870,7 +39870,7 @@ export function isLazyViewLoadingType(value: VLazyViewLoadingTypeIdentifier) { ); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.scss // :host ::ng-deep .app-page-content { // overflow: auto; @@ -40065,7 +40065,7 @@ export function isLazyViewLoadingType(value: VLazyViewLoadingTypeIdentifier) { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page\v-page.component.ts import { Input, @@ -41069,7 +41069,7 @@ export class VPageComponent extends XPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.component.ts import { Input, @@ -41266,7 +41266,7 @@ export class VPagePresenter extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-page-presenter\v-page-presenter.typings.ts import { isValueInEnum } from '../tools/v-base.tools'; import { XBaseActionModel } from 'x-framework-components'; @@ -41289,7 +41289,7 @@ export interface VBasePageActionModel extends XBaseActionModel {} //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.html @@ -41488,10 +41488,10 @@ export interface VBasePageActionModel > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.component.ts import { isNumber, @@ -41956,7 +41956,7 @@ export class VPaginatorComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-paginator\v-paginator.typings.ts import { XLocale, @@ -42011,7 +42011,7 @@ export interface VPaginatorOptions { ) => string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.html @@ -42176,7 +42176,7 @@ export interface VPaginatorOptions { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.scss .v-avatar-box, .v-avatar-image { @@ -42202,7 +42202,7 @@ export interface VPaginatorOptions { font-size: x-small; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.component.ts import { XPersonDto, @@ -42384,7 +42384,7 @@ export class VPersonComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.tools.ts import { XPersonDto } from 'x-saherelm-api-sdk'; import { defaultPersonAvatar, defaultPersonFullName } from './v-person.typings'; @@ -42420,7 +42420,7 @@ export function getPersonAvatar(model: XPersonDto) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-person\v-person.typings.ts import { isValueInEnum } from "../public-api"; @@ -42440,7 +42440,7 @@ export function isPersonPresentType(value: string) { export const defaultPersonFullName = '...'; export const defaultPersonAvatar = '/assets/image/default-user-image.png'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.base.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.base.page.ts import { Inject, @@ -43502,7 +43502,7 @@ export abstract class VQueryPresenterBasePage //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.html @@ -43865,10 +43865,10 @@ export abstract class VQueryPresenterBasePage
    List ...
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.component.ts import { Input, @@ -45957,7 +45957,7 @@ export class VQueryPresenterComponent //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-query-presenter\v-query-presenter.typings.ts import { hasChild, @@ -46518,16 +46518,16 @@ export class VQueryPresenterContainer } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.component.ts import { toXString, @@ -46757,7 +46757,7 @@ export class VReferenceComponent extends VBaseDtoComponent> { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.configs.ts // //#region Localization Configuration ... @@ -46851,7 +46851,7 @@ export const ReferenceLocalizationResources = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-reference\v-reference.typings.ts import { isValueInEnum } from '../tools/v-base.tools'; import { isNullOrUndefined, isString } from 'x-framework-core'; @@ -46905,7 +46905,7 @@ export function isVisibleVReferencePresentType( //#region Action Provider ... //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.html @@ -47220,7 +47220,7 @@ export function isVisibleVReferencePresentType( -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.scss .v-card { border-radius: 8px; @@ -47415,7 +47415,7 @@ export function isVisibleVReferencePresentType( } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.component.ts import { Input, @@ -50770,7 +50770,7 @@ export class VVideoComponent //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.configs.ts export enum VideoResourceIDs { play = 'play', @@ -51083,7 +51083,7 @@ export const VideoLocalizationResources = { }, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\v-video\v-video.typings.ts import { XSpinner, @@ -52342,7 +52342,7 @@ export class VVideoComponentContainer } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.configs.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.configs.ts import { XIconNames } from 'x-framework-components'; import { isValueInEnum } from '../tools/v-base.tools'; @@ -52776,7 +52776,7 @@ export function getXWebinarException(id: XWebinarExceptionIdentifier) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.tools.ts import { XLocale, @@ -53041,7 +53041,7 @@ export function getWebinarTypeValues() { return [XWebinarType.Public, XWebinarType.Private]; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar.typings.ts import { XBaseDto } from 'x-framework-core'; import { XPersonDto, XWebinarType } from 'x-saherelm-api-sdk'; @@ -53070,13 +53070,13 @@ export const defaultVWebinarViewDto: VWebinarViewDto = { createdOn: undefined, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.component.ts import { VBaseDtoComponent, @@ -53128,13 +53128,13 @@ export class VWebinarComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar\v-webinar.typings.ts export enum VWebinarAction { Refresh = 'Refresh', } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.scss @import "../../../../theme/theme.scss"; @@ -53396,7 +53396,7 @@ h6 { clip-path: circle(); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.component.ts import { Input, @@ -55585,7 +55585,7 @@ export class VWebinarConnectComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-connect\v-webinar-connect.typings.ts import { isValueInEnum } from '../../tools/v-base.tools'; @@ -55613,16 +55613,16 @@ export interface VWebinarSubscriber { export type VWebinarReturnActionIdentifier = VWebinarReturnAction | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-subscriber\v-webinar-subscriber.component.ts -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.html @@ -55717,10 +55717,10 @@ export type VWebinarReturnActionIdentifier = VWebinarReturnAction | string; > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\app\views\webinar\v-webinar-view\v-webinar-view.component.ts import { Input, @@ -56751,7 +56751,7 @@ export class VWebinarViewComponent extends VBaseDtoComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\environments\environment.prod.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\environments\environment.prod.ts import { XConfig, xSharedConfig } from '../app/config/app.config'; @@ -56784,7 +56784,7 @@ export const environment = { } as XConfig }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\environments\environment.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\environments\environment.ts import { XConfig, xSharedConfig } from '../app/config/app.config'; @@ -56819,7 +56819,7 @@ export const environment = { } as XConfig, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xClient\src\theme\theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xClient\src\theme\theme.scss // // XFramework Color Mechanism ... diff --git a/Documents/GeneratedContext/xDashboard-xCommons-20261109_152619.txt b/Documents/GeneratedContext/xDashboard-xCommons-20261109_152619.txt deleted file mode 100644 index 2e28174..0000000 --- a/Documents/GeneratedContext/xDashboard-xCommons-20261109_152619.txt +++ /dev/null @@ -1,8783 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Attributes\RequireXPoweredAttribute.cs - -using System.Linq; -using xCommons.Constants; -using xCommons.Extensions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authorization; - -namespace xCommons.Attributes { - public partial class RequireXPoweredAttribute : AuthorizeAttribute, IAuthorizationFilter { - - private readonly bool ignoreAnonymous; - - public RequireXPoweredAttribute (bool IgnoreAnonymous = true) { - ignoreAnonymous = IgnoreAnonymous; - } - - public void OnAuthorization (AuthorizationFilterContext context) { - // - var config = context.GetXAppConfiguration (); - - // - var isExistsXPowered = context.HttpContext.Request.Headers - .Any (h => h.Key - .ToNormalString () == XAuthorization.XPoweredBy.ToNormalString () && - h.Value == config.XPoweredValue); - - // - var isAnonymous = context.IsAnonymousAllowed (); - var handler = ignoreAnonymous ? isAnonymous ? false : true : true; - - // - if (handler && - !isExistsXPowered) { - context.Result = new UnauthorizedResult (); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Attributes\XRateLimitAttribute.cs - -using System; -using xCommons.Models; -using xCommons.Constants; -using xCommons.Extensions; -using xCommons.Interfaces; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.DependencyInjection; - -namespace xCommons.Attributes -{ - [AttributeUsage( - AttributeTargets.Class | AttributeTargets.Method, - AllowMultiple = false, - Inherited = true - )] - public partial class XRateLimitAttribute : Attribute, IActionFilter, IOrderedFilter - { - public int Limit { get; set; } = 0; - public int Order { get; set; } = -1000; - public int PeriodSeconds { get; set; } = 0; - public string KeyPrefix { get; set; } = null; - public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip; - - public void OnActionExecuting(ActionExecutingContext context) - { - // - var provider = context.HttpContext.RequestServices - .GetService(); - - var configuration = context.HttpContext.RequestServices - .GetService(); - - // - if (provider.IsNull() || - configuration.IsNull() || - !provider.IsEnabled) - { - return; - } - - // - var limit = Limit > 0 - ? Limit - : configuration.DefaultLimit; - - // - var periodSeconds = PeriodSeconds > 0 - ? PeriodSeconds - : configuration.DefaultPeriodSeconds; - - // - var key = context.HttpContext.GetXRateLimitKey(KeyMode); - if (!KeyPrefix.IsNullOrEmpty()) - { - key = string.Format("{0}:{1}", KeyPrefix, key); - } - - // - var result = provider.TryConsume( - key: key, - limit: limit, - periodSeconds: periodSeconds - ); - - // - context.HttpContext.Items[XRateLimitConstants.AppliedItemKey] = true; - WriteHeaders(context.HttpContext, result); - - // - if (!result.IsAllowed) - { - // - context.Result = new ObjectResult(new - { - resetOn = result.ResetOn, - retryAfter = result.RetryAfterSeconds, - message = "Too many requests. Please try again later.", - }) - { - StatusCode = configuration.StatusCode - }; - } - } - - public void OnActionExecuted(ActionExecutedContext context) - { } - - private static void WriteHeaders( - HttpContext context, - XRateLimitResult result - ) - { - // - context.Response.Headers[XRateLimitConstants.LimitHeader] = - result.Limit.ToString(); - - // - context.Response.Headers[XRateLimitConstants.RemainingHeader] = - result.Remaining.ToString(); - - // - context.Response.Headers[XRateLimitConstants.ResetHeader] = - result.ResetOn.ToUnixTimeSeconds().ToString(); - - // - if (!result.IsAllowed) - { - // - context.Response.Headers[XRateLimitConstants.RetryAfterHeader] = - result.RetryAfterSeconds.ToString(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Authorization\RequiredRolesHandler.cs - -using System.Linq; -using IdentityModel; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; - -namespace xCommons.Authorization { - public partial class RequiredRolesHandler : AuthorizationHandler { - protected override Task HandleRequirementAsync ( - AuthorizationHandlerContext context, - RequiredRolesRequirement requirement - ) { - // - var conatinsRole = context.User.HasClaim (c => c.Type == JwtClaimTypes.Role); - if (!conatinsRole) { - return Task.CompletedTask; - } - - // - var roleClaim = context.User.Claims.FirstOrDefault (c => c.Type == JwtClaimTypes.Role); - if (roleClaim == null || - !requirement.Roles.Contains (roleClaim.Value) - ) { - return Task.CompletedTask; - } - - // - context.Succeed (requirement); - return Task.CompletedTask; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Authorization\RequiredRolesRequirement.cs - -using Microsoft.AspNetCore.Authorization; - -namespace xCommons.Authorization { - public partial class RequiredRolesRequirement : IAuthorizationRequirement { - public string[] Roles { get; } - public RequiredRolesRequirement (params string[] Roles) { - this.Roles = Roles; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Configurations\XAppConfiguration.cs - -using System.Collections.Generic; - -namespace xCommons.Configurations { - /// - /// represent an xBackend Application - /// - public partial class XAppConfiguration { - public string Name { get; set; } - public string Version { get; set; } - public string Environment { get; set; } - public string XPoweredValue { get; set; } - public IEnumerable AllowedOrigins { get; set; } - public string WelcomeMessage { get; set; } - public string DefaultLanguage { get; set; } - public XMessageResourceTitles MessageResourceTitles { get; set; } - } - - public partial class XMessageResourceTitles { - public string Terms { get; set; } - public string Invite { get; set; } - public string RegistrationApprove { get; set; } - public string Registered { get; set; } - public string VerificationCode { get; set; } - public string ChangePassword { get; set; } - public string PasswordChanged { get; set; } - public string NewDeviceLoggedIn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Configurations\XFileTypeDetectorConfiguration.cs - -namespace xCommons.Configurations -{ - /// - /// Configuration options for XFileTypeDetector ... - /// - public sealed class XFileTypeDetectorConfiguration - { - /// - /// When true, magic bytes are always read first ... - /// - public bool PreferMagicBytes { get; set; } = true; - - /// - /// Number of bytes read from the stream header ... - /// - public int HeaderSize { get; set; } = 32; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Configurations\XRateLimitConfiguration.cs - -using xCommons.Constants; -using System.Collections.Generic; - -namespace xCommons.Configurations -{ - public class XRateLimitConfiguration - { - public bool Enabled { get; set; } = false; - public int StatusCode { get; set; } = 429; - public int DefaultLimit { get; set; } = 60; - public int DefaultPeriodSeconds { get; set; } = 60; - public bool ApplyToAllRoutes { get; set; } = false; - public ICollection Rules { get; set; } = []; - public XRateLimitKeyMode DefaultKeyMode { get; set; } = XRateLimitKeyMode.Ip; - } - - public partial class XRateLimitRule - { - public int Limit { get; set; } = 60; - public bool Enabled { get; set; } = true; - public int PeriodSeconds { get; set; } = 60; - public string PathPrefix { get; set; } = "/"; - public string Name { get; set; } = string.Empty; - public XRateLimitKeyMode KeyMode { get; set; } = XRateLimitKeyMode.Ip; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Configurations\XSwaggerConfiguration.cs - -using System.Collections.Generic; - -namespace xCommons.Configurations { - public partial class XSwaggerConfiguration { - public string Title { get; set; } = ""; - public string Version { get; set; } = "V1.0"; - public string Description { get; set; } = ""; - public string TermsOfServiceUrl { get; set; } = ""; - - public XSwaggerContact Contact { get; set; } = null; - public XSwaggerLicence License { get; set; } = null; - public Dictionary DefaultValues {get; set;} = null; - } - - public partial class XSwaggerContact { - public string Name { get; set; } - public string Email { get; set; } - public string Url { get; set; } - } - - public partial class XSwaggerLicence { - public string Name { get; set; } - public string Url { get; set; } - } - - public partial class XSwaggerDefaultValues - { - public Dictionary Values { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\CommonConstants.cs - -namespace xCommons.Constants { - public partial class CommonConstants { - public static char DEFAULT_LIST_SEPERATOR = ','; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\ConfigurationNodeNames.cs - -namespace xCommons.Constants { - public partial struct ConfigurationNodeNames { - public const string CERTIFICATES_NODE = "Certificates"; - public const string SWAGGER_NODE = "SwaggerConfiguration"; - public const string RATE_LIMIT_NODE = "RateLimitConfiguration"; - public const string FILE_TYPE_DETECTOR_NODE = "FileTypeDetectorConfiguration"; - public const string MESSAGE_RESOURCE_TITLES_NODE = "MessageResourceTitles"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XAuthentication.cs - -namespace xCommons.Constants { - public partial struct XAuthentication { - public const string JWT = "jwt"; - public const string TOKEN = "token"; - public const string BEARER = "Bearer"; - public const string SMART_SCHEME = "XSmartScheme"; - public const string INTROSPECTION = "introspection"; - public const string IDENTITY_SERVER_LOCAL_API = "IdentityServerAccessToken"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XAuthorization.cs - -namespace xCommons.Constants { - public partial struct XAuthorization { - public const string XApiKey = "X-Api-Key"; - public const string Header = "Authorization"; - public const string ExpiresAt = "expires_at"; - public const string XPoweredBy = "X-PoweredBy"; - public const string TokenIdentifier = "Bearer "; - public const string AccessToken = "access_token"; - public const string RefreshToken = "refresh_token"; - public const int ThresholdBeforeTokenExpiration = 600; - public const string RevisionChecksum = "revision_checksum"; - public const string AccessTokenExpired = "AccessToken-Expired"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XCustomClaims.cs - -namespace xCommons.Constants { - public partial struct XCustomClaims { - public const string Bio ="bio"; - public const string Role = "role"; - public const string UserId = "sub"; - public const string Issuer = "iss"; - public const string Scope = "scope"; - public const string Email = "email"; - public const string Audience = "aud"; - public const string Gender = "gender"; - public const string ExpiredOn = "exp"; - public const string Picture = "picture"; - public const string AuthType = "auth_type"; - public const string IsBanned = "is_banned"; - public const string ClientId = "client_id"; - public const string BrithDate = "birthdate"; - public const string IsEnabled = "is_enabled"; - public const string UserName = "unique_name"; - public const string FirstName = "given_name"; - public const string LastName = "family_name"; - public const string CoverImage = "cover_image"; - public const string PhoneNumber = "phone_number"; - public const string AuthenticatedOn = "auth_time"; - public const string OpenToSearch = "open_to_search"; - public const string EmailVerified = "email_verified"; - public const string ApplicationId = "application_id"; - public const string PhoneNumberVerified = "phone_number_verified"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XDeviceType.cs - -namespace xCommons.Constants { - /// - /// a collection of available Client Devices - /// - public enum XDeviceType { - Unknown, - Mobile, - Tablet, - Desktop - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileExtensions.cs - -using xExceptions.Attributes; - -namespace xCommons.Constants -{ - /// - /// File Extensions Enumerable ... - /// - /// Document: 100–133 - /// Archive: 200–202 - /// Internal Supports: 300–302 - /// Video: 400–405 - /// Audio: 500–505 - /// Image: 600–609 - /// - public enum XFileExtensions - { - // - #region Document ... - [StringValue(".txt")] - TEXT = 100, - - [StringValue(".pdf")] - PDF = 101, - - [StringValue(".ppt")] - PPT = 102, - - [StringValue(".pptx")] - PPTX = 103, - - [StringValue(".odp")] - ODP = 104, - - [StringValue(".pps")] - PPS = 105, - - [StringValue(".ods")] - ODS = 106, - - [StringValue(".xlr")] - XLR = 107, - - [StringValue(".xls")] - XLS = 108, - - [StringValue(".xlsx")] - XLSX = 109, - - [StringValue(".xml")] - XML = 110, - - [StringValue(".doc")] - DOC = 111, - - [StringValue(".docx")] - DOCX = 112, - - [StringValue(".odt")] - ODT = 113, - - [StringValue(".rtf")] - RTF = 114, - - [StringValue(".tex")] - TEX = 115, - - [StringValue(".wpd")] - WPD = 116, - - [StringValue(".md")] - MD = 117, - - [StringValue(".cs")] - CSHARP = 118, - - [StringValue(".py")] - PYTHON = 119, - - [StringValue(".js")] - JAVASCRIPT = 120, - - [StringValue(".ts")] - TYPESCRIPT = 121, - - [StringValue(".java")] - JAVA = 122, - - [StringValue(".go")] - GO = 123, - - [StringValue(".rs")] - RUST = 124, - - [StringValue(".rb")] - RUBY = 125, - - [StringValue(".php")] - PHP = 126, - - [StringValue(".csv")] - CSV = 127, - - [StringValue(".json")] - JSON = 128, - - [StringValue(".yml")] - YML = 129, - - [StringValue(".yaml")] - YAML = 130, - - [StringValue(".css")] - CSS = 131, - - [StringValue(".htm")] - HTM = 132, - - [StringValue(".html")] - HTML = 133, - #endregion - - // - #region Archive ... - [StringValue(".zip")] - ZIP = 200, - - [StringValue(".rar")] - RAR = 201, - - [StringValue(".7z")] - SEVENZIP = 202, - #endregion - - // - #region Internal Supports ... - [StringValue(".ttf")] - TTF = 300, - - [StringValue(".sdw")] - SAHER_DASHBOARD_WIDGET = 301, - - [StringValue(".sdwmanifest")] - SAHER_DASHBOARD_WIDGET_MANIFEST = 302, - #endregion - - // - #region Video ... - [StringValue(".mp4")] - MP4 = 400, - - [StringValue(".avi")] - AVI = 401, - - [StringValue(".mpg")] - MPG = 402, - - [StringValue(".mpeg")] - MPEG = 403, - - [StringValue(".wmv")] - WMV = 404, - - [StringValue(".webm")] - WEBM = 405, - #endregion - - // - #region Audio ... - [StringValue(".mp3")] - MP3 = 500, - - [StringValue(".ogg")] - OGG = 501, - - [StringValue(".wav")] - WAV = 502, - - [StringValue(".wma")] - WMA = 503, - - [StringValue(".aac")] - AAC = 504, - - [StringValue(".m4a")] - M4A = 505, - #endregion - - // - #region Image ... - [StringValue(".png")] - PNG = 600, - - [StringValue(".jpeg")] - JPEG = 601, - - [StringValue(".jpg")] - JPG = 602, - - [StringValue(".ico")] - ICON = 603, - - [StringValue(".gif")] - GIF = 604, - - [StringValue(".bmp")] - BITMAP = 605, - - [StringValue(".webp")] - WEBP = 606, - - [StringValue(".tif")] - TIF = 607, - - [StringValue(".tiff")] - TIFF = 608, - - [StringValue(".svg")] - SVG = 609, - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileMimeTypes.cs - -using xExceptions.Attributes; - -namespace xCommons.Constants -{ - /// - /// MIME Types mapped to XFileExtensions ... - /// - /// Document: 100–133 - /// Archive: 200–202 - /// Internal Supports: 300–302 - /// Video: 400–405 - /// Audio: 500–505 - /// Image: 600–609 - /// - public enum XFileMimeTypes - { - // - #region Document ... - [StringValue("text/plain")] - TEXT = 100, - - [StringValue("application/pdf")] - PDF = 101, - - [StringValue("application/vnd.ms-powerpoint")] - PPT = 102, - - [StringValue("application/vnd.openxmlformats-officedocument.presentationml.presentation")] - PPTX = 103, - - [StringValue("application/vnd.oasis.opendocument.presentation")] - ODP = 104, - - [StringValue("application/vnd.ms-powerpoint")] - PPS = 105, - - [StringValue("application/vnd.oasis.opendocument.spreadsheet")] - ODS = 106, - - [StringValue("application/vnd.ms-excel")] - XLR = 107, - - [StringValue("application/vnd.ms-excel")] - XLS = 108, - - [StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] - XLSX = 109, - - [StringValue("text/xml")] - XML = 110, - - [StringValue("application/msword")] - DOC = 111, - - [StringValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] - DOCX = 112, - - [StringValue("application/vnd.oasis.opendocument.text")] - ODT = 113, - - [StringValue("application/rtf")] - RTF = 114, - - [StringValue("application/x-tex")] - TEX = 115, - - [StringValue("application/vnd.wordperfect")] - WPD = 116, - - [StringValue("text/markdown")] - MD = 117, - - [StringValue("text/x-csharp")] - CSHARP = 118, - - [StringValue("text/x-python")] - PYTHON = 119, - - [StringValue("application/javascript")] - JAVASCRIPT = 120, - - [StringValue("application/typescript")] - TYPESCRIPT = 121, - - [StringValue("text/x-java")] - JAVA = 122, - - [StringValue("text/x-go")] - GO = 123, - - [StringValue("text/x-rust")] - RUST = 124, - - [StringValue("text/x-ruby")] - RUBY = 125, - - [StringValue("text/x-php")] - PHP = 126, - - [StringValue("text/csv")] - CSV = 127, - - [StringValue("application/json")] - JSON = 128, - - [StringValue("application/x-yaml")] - YML = 129, - - [StringValue("application/x-yaml")] - YAML = 130, - - [StringValue("text/css")] - CSS = 131, - - [StringValue("text/html")] - HTM = 132, - - [StringValue("text/html")] - HTML = 133, - #endregion - - // - #region Archive ... - [StringValue("application/zip")] - ZIP = 200, - - [StringValue("application/x-rar-compressed")] - RAR = 201, - - [StringValue("application/x-7z-compressed")] - SEVENZIP = 202, - #endregion - - // - #region Internal Supports ... - [StringValue("font/ttf")] - TTF = 300, - - [StringValue("application/x-sdw")] - SAHER_DASHBOARD_WIDGET = 301, - - [StringValue("application/x-sdwmanifest")] - SAHER_DASHBOARD_WIDGET_MANIFEST = 302, - #endregion - - // - #region Video ... - [StringValue("video/mp4")] - MP4 = 400, - - [StringValue("video/x-msvideo")] - AVI = 401, - - [StringValue("video/mpeg")] - MPG = 402, - - [StringValue("video/mpeg")] - MPEG = 403, - - [StringValue("video/x-ms-wmv")] - WMV = 404, - - [StringValue("video/webm")] - WEBM = 405, - #endregion - - // - #region Audio ... - [StringValue("audio/mpeg")] - MP3 = 500, - - [StringValue("audio/ogg")] - OGG = 501, - - [StringValue("audio/wav")] - WAV = 502, - - [StringValue("audio/x-ms-wma")] - WMA = 503, - - [StringValue("audio/aac")] - AAC = 504, - - [StringValue("audio/mp4")] - M4A = 505, - #endregion - - // - #region Image ... - [StringValue("image/png")] - PNG = 600, - - [StringValue("image/jpeg")] - JPEG = 601, - - [StringValue("image/jpeg")] - JPG = 602, - - [StringValue("image/x-icon")] - ICON = 603, - - [StringValue("image/gif")] - GIF = 604, - - [StringValue("image/bmp")] - BITMAP = 605, - - [StringValue("image/webp")] - WEBP = 606, - - [StringValue("image/tiff")] - TIF = 607, - - [StringValue("image/tiff")] - TIFF = 608, - - [StringValue("image/svg+xml")] - SVG = 609, - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileType.cs - -using xExceptions.Attributes; - -namespace xCommons.Constants -{ - public enum XFileType - { - Image, - ProfileImasge, - CoverImage, - Audio, - Video, - Document - } - - public enum XFileCategory - { - [StringValue("Document")] - Document = 100, - - [StringValue("Archive")] - Archive = 200, - - [StringValue("Internal")] - Internal = 300, - - [StringValue("Video")] - Video = 400, - - [StringValue("Audio")] - Audio = 500, - - [StringValue("Image")] - Image = 600 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XFileTypeDetectionSource.cs - -using xExceptions.Attributes; - -namespace xCommons.Constants -{ - /// - /// File Type Detection Source ... - /// - public enum XFileTypeDetectionSource - { - [StringValue("None")] - None = 0, - - [StringValue("MagicBytes")] - MagicBytes = 1, - - [StringValue("Extension")] - Extension = 2, - - [StringValue("ProvidedMime")] - ProvidedMime = 3, - - [StringValue("Fallback")] - Fallback = 4 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XPolicy.cs - -namespace xCommons.Constants { - public partial struct XPolicy { - public const string AllowedOrigins = "AllowedOrigins"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XRateLimitConstants.cs - -namespace xCommons.Constants -{ - /// - /// RateLimit Implementation Constants ... - /// - public partial struct XRateLimitConstants - { - public const string CacheKeyPrefix = "xratelimit"; - public const string ClientIdHeader = "X-ClientId"; - public const string RetryAfterHeader = "Retry-After"; - public const string LimitHeader = "X-RateLimit-Limit"; - public const string ResetHeader = "X-RateLimit-Reset"; - public const string AppliedItemKey = "X-RateLimit-Applied"; - public const string RemainingHeader = "X-RateLimit-Remaining"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Constants\XRateLimitKeyMode.cs - -using xExceptions.Attributes; - -namespace xCommons.Constants -{ - /// - /// RateLimiting Modes ... - /// - public enum XRateLimitKeyMode - { - [StringValue("Ip")] - Ip = 0, - - [StringValue("ClientId")] - ClientId = 1, - - [StringValue("User")] - User = 2, - - [StringValue("Route")] - Route = 3, - - [StringValue("Custom")] - Custom = 4 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseApiController.cs - -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; - -namespace xCommons.Controllers { - /// - /// Base Api Controller - /// - [ApiController] - [RequireXPowered(true)] - [Route("api/[controller]")] - [Produces("application/json")] - public abstract partial class XBaseApiController : XBaseController - { - protected XBaseApiController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseApiV1Controller.cs - -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; - -namespace xCommons.Controllers { - /// - /// Base Api V1 Controller - /// - [ApiController] - [ApiVersion("1.0")] - [RequireXPowered(true)] - [Route("api/v{version:apiVersion}/[controller]")] - public abstract partial class XBaseApiV1Controller : XBaseApiController - { - protected XBaseApiV1Controller( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Controllers\XBaseController.cs - -using System; -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Extensions; -using xExceptions.Constants; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xCommons.Controllers { - /// - /// Base Controller - /// - [Route ("[controller]")] - [Produces ("application/json")] - public abstract partial class XBaseController : ControllerBase { - public ILogger Logger { get; } - public XAppConfiguration AppConfiguration { get; } - public XValidationProvider ValidationProvider { get; } - - protected XBaseController ( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) { - Logger = logger; - AppConfiguration = appConfiguration; - ValidationProvider = validationProvider; - } - - /// - /// Check the Controller Up and Running - /// - /// string message - [HttpGet] - [Route ("Test/Hi")] - [AllowAnonymous] - public virtual IActionResult Hi () { - // - var controllerName = GetControllerName (); - var message = $"{controllerName} Controller is Up and running ..."; - - // - return Ok (message); - } - - /// - /// Check Controller ByPass XPowered Filter - /// - /// string message - [HttpGet] - [AllowAnonymous] - [RequireXPowered (false)] - [Route ("Test/PassRequireXPowered")] - public virtual IActionResult PassRequireXPowered () { - // - var controllerName = GetControllerName (); - var message = $"{controllerName} Controller bypass RequiredXPowered and Up and running ..."; - - // - return Ok (message); - } - - // - #region Non Actions ... - /// - /// Convert an Exception to Propper Error Result - /// - /// - /// - [NonAction] - public ActionResult GetExceptionActionResult (Exception ex) { - // - var exception = GetExceptionResult (ex); - var error = ex.Message.ToXError (); - - // - Logger.LogError ($"exception: {exception}, error: {error}"); - - // - try { - var xError = exception.Message.ToXError (); - var xException = (XException) xError.Id; - - // - switch (xException) { - // - case XException.NotFound: - return NotFound (error); - - // - case XException.NotAuthorized: - return Unauthorized (); - } - } catch { } - - // - return BadRequest (error); - } - - /// - /// Return Structured Exception - /// - /// - /// - [NonAction] - public Exception GetExceptionResult (Exception ex) { - // - // Log Exception Message ... - Logger.LogError (ex.Message); - - // - // if Happens Exception is Know Error - // catch it and return it in BadRequest Container ... - var isEr = ex.Message.IsXError (); - - // - if (isEr) { - return ex; - } - - // - // if catched Exception Contains Unknown Error - // return an Unknown Error ... - return XException.Unknown.ToException (); - } - - /// - /// Retrieve ControllerName - /// - /// - [NonAction] - public string GetControllerName () { - return this.ControllerContext.RouteData.Values["controller"].ToString (); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\DI\XDIHelperExtension.cs - -using xCommons.Providers; -using xCommons.Extensions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -public static partial class XDIHelperExtension -{ - /// - /// Register XCommons Module Services - /// - /// - public static void AddXCommons(this IServiceCollection services) - { - services.AddSingleton(); - } - - /// - /// Register XCommons Module Service ... - /// - /// - /// - public static void AddXCommons( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - services.AddXCommons(); - services.AddXFileTypeDetector(configuration); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\BackgroundServiceExtensions.cs - -using xCommons.Providers; -using Microsoft.Extensions.DependencyInjection; - -namespace xCommons.Extensions -{ - public static class BackgroundServiceExtensions - { - /// - /// Register Background Services ... - /// - /// - /// - public static void AddXBackgroundService( - this IServiceCollection source - ) - where TService : XBackgroundService - { - // - source.AddSingleton(); - source.AddHostedService(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\CertificateExtensions.cs - -using xCommons.Models; -using xCommons.Constants; -using Microsoft.Extensions.Configuration; - -namespace xCommons.Extensions { - public static partial class CertificateExtensions { - /// - /// Retrieve Specific Certificate From app Settings - /// - /// - /// - /// - public static XCertificate GetCertificate (this IConfiguration configuration, string name) { - // - var certificatesSection = configuration.GetSection (ConfigurationNodeNames.CERTIFICATES_NODE); - var certificateSection = certificatesSection.GetSection (name); - var certificate = certificateSection.Get (); - - // - return certificate; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\CommonExtensions.cs - -using System; -using System.IO; -using System.Web; -using System.Xml; -using AutoMapper; -using System.Linq; -using System.Text; -using Newtonsoft.Json; -using xCommons.Helpers; -using System.Threading; -using System.Reflection; -using xCommons.Constants; -using Newtonsoft.Json.Linq; -using System.Globalization; -using xExceptions.Constants; -using System.Threading.Tasks; -using xExceptions.Attributes; -using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Security.Cryptography; -using Newtonsoft.Json.Serialization; -using System.Collections.ObjectModel; -using System.Text.RegularExpressions; - -namespace xCommons.Extensions -{ - public static partial class CommonExtensions - { - /// - /// Conert XMLNode to String ... - /// - /// - /// - /// - public static string ToString(this XmlNode node, int indentation = 2) - { - // - using (var sw = new StringWriter()) - { - // - using (var xw = new XmlTextWriter(sw)) - { - xw.Formatting = System.Xml.Formatting.Indented; - xw.Indentation = indentation; - node.WriteContentTo(xw); - } - - // - return sw.ToString(); - } - } - - /// - /// Converts a Json String to Dictionary of String Mappings - /// - /// Json String - /// - public static Dictionary JSONToDictionary(this string source) - { - // - try - { - return JsonConvert.DeserializeObject>(source); - } - catch - { - return null; - } - } - - /// - /// Convert properties of specific Class instance to Dictionary ... - /// - /// class instance - /// - public static Dictionary ToDictionary(this T source) where T : class - { - // - var result = new Dictionary(); - - // - if (source.IsNull()) - { - return result; - } - - // - PropertyInfo[] propertyInfos = source.GetType().GetProperties(); - if (!propertyInfos.HasChild()) - { - return result; - } - - // - foreach (PropertyInfo propertyInfo in propertyInfos) - { - result.Add( - propertyInfo.Name, - propertyInfo - .GetValue(source, null) - .ToString() - ); - } - - // - return result; - } - - /// - /// run specific task and retrieve result ... - /// - /// - public static void RunTask(this Task source) - { - source. - GetAwaiter() - .GetResult(); - } - - /// - /// run specific task and retrieve result ... - /// - /// - public static T RunTask(this Task source) - { - return source. - GetAwaiter() - .GetResult(); - } - - /// - /// Convert XML String to Json Object ... - /// - /// - /// - public static string ToJSON(this string source) - { - // - var result = string.Empty; - try - { - // - result = XMLToJSONHelper.ToJSON(source); - - // - // Handle Removing Additional Values ... - result = result.Replace("s:", "").Replace("a:", ""); - } - catch { } - - // - return result; - } - - /// - /// Convert object to Json ... - /// - /// - /// - public static string ToJSON(this T value) - where T : class - { - // - if (value.IsNull()) - { - return string.Empty; - } - - // - var setting = new JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - PreserveReferencesHandling = PreserveReferencesHandling.None - }; - - // - return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); - } - - /// - /// Convert to Json With Support of Camel Casing - /// - /// - /// - /// - public static string ToJSON(this T value, bool camelCase = false) - { - // - if (value.IsNull()) - { - return string.Empty; - } - - // - var setting = new JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - PreserveReferencesHandling = PreserveReferencesHandling.None, - }; - - // - if (camelCase) - { - setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); - } - - // - return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None, setting); - } - - /// - /// Map to Dynamic Object ... - /// - /// - /// - public static dynamic ToDynamicObject(this string source) - { - return JsonConvert.DeserializeObject(source); - } - - /// - /// Map to Dynamic Object ... - /// - /// - /// - public static dynamic ToDynamicObject(this object source) - { - // - var dMapConfig = new MapperConfiguration(b => { }); - var dMapper = dMapConfig.CreateMapper(); - - // - return dMapper.Map(source); - } - - /// - /// Parse From Dynamic Object ... - /// - /// - /// - /// - public static T FromDynamicObject(this object source) - where T : class - { - // - var dMapConfig = new MapperConfiguration(b => { }); - var dMapper = dMapConfig.CreateMapper(); - dynamic dSource = source; - - // - return dMapper.Map(dSource); - } - - /// - /// Convert Type of Object to Safe Type - /// - /// - /// - /// - public static T ConvertTo(this object source) - { - // - T result = default(T); - - // - try - { - // - T item = (T)Convert.ChangeType(source, typeof(T)); - - // - result = item; - } - catch { } - - // - return result; - } - - /// - /// Convert an Instance to another Instance - /// using AutoMapper dynamic Convertion - /// - /// - /// - /// - public static T MapConvert(this T source) - where T : class - { - // - if (source.IsNull()) - { - return null; - } - - // - var dSource = (object)source.ToDynamicObject(); - return dSource.FromDynamicObject(); - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - /// - public static T MapConvert( - this E source, - Action cfgAction = null - ) - where T : class - where E : class - { - // - if (source.IsNull()) - { - return null; - } - - // - var dMapConfig = new MapperConfiguration(b => - { - // - b.CreateMap() - .ReverseMap(); - - // - // Use Specified Provided Actions if Exists ... - if (!cfgAction.IsNull()) - { - cfgAction.Invoke(b); - } - }); - var dMapper = dMapConfig.CreateMapper(); - - // - var dSource = (object)dMapper.Map(source); - var result = dMapper.Map(dSource); - - // - return result; - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - /// - public static IEnumerable MapConvert( - this IEnumerable source, - Action cfgAction = null - ) - { - // - if (source.IsNull()) - { - return null; - } - - // - var dMapConfig = new MapperConfiguration(b => - { - // - b.CreateMap() - .ReverseMap(); - - // - // Use Specified Provided Actions if Exists ... - if (!cfgAction.IsNull()) - { - cfgAction.Invoke(b); - } - }); - var dMapper = dMapConfig.CreateMapper(); - - // - var dSource = (object)dMapper.Map(source); - var result = dMapper.Map>(dSource); - - // - return result; - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - /// - public static ICollection MapConvert( - this ICollection source, - Action cfgAction = null - ) - { - // - if (source.IsNull()) - { - return null; - } - - // - var dMapConfig = new MapperConfiguration(b => - { - // - b.CreateMap() - .ReverseMap(); - - // - // Use Specified Provided Actions if Exists ... - if (!cfgAction.IsNull()) - { - cfgAction.Invoke(b); - } - }); - var dMapper = dMapConfig.CreateMapper(); - - // - var dSource = (object)dMapper.Map(source); - var result = dMapper.Map>(dSource); - - // - return result; - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - /// - public static IList MapConvert( - this IList source, - Action cfgAction = null - ) - { - // - if (source.IsNull()) - { - return null; - } - - // - var dMapConfig = new MapperConfiguration(b => - { - // - b.CreateMap() - .ReverseMap(); - - // - // Use Specified Provided Actions if Exists ... - if (!cfgAction.IsNull()) - { - cfgAction.Invoke(b); - } - }); - var dMapper = dMapConfig.CreateMapper(); - - // - var dSource = (object)dMapper.Map(source); - var result = dMapper.Map>(dSource); - - // - return result; - } - - /// - /// Convert Using Auto Mapper ... - /// - /// - /// - /// - /// - /// - /// - public static IDictionary MapConvert( - this IDictionary source, - Action cfgAction = null - ) - { - // - if (source.IsNull()) - { - return null; - } - - // - var dMapConfig = new MapperConfiguration(b => - { - // - b.CreateMap() - .ReverseMap(); - - // - // Use Specified Provided Actions if Exists ... - if (!cfgAction.IsNull()) - { - cfgAction.Invoke(b); - } - }); - var dMapper = dMapConfig.CreateMapper(); - - // - var dSource = (object)dMapper.Map(source); - var result = dMapper.Map>(dSource); - - // - return result; - } - - /// - /// Convert a Type to Static Type - /// - /// - /// - /// - public static T ToStatic(this object source) - { - // - var entity = Activator.CreateInstance(); - - // - var properties = source as IDictionary; - - // - if (properties == null) - { - return entity; - } - - // - foreach (var entry in properties) - { - // - var propertyInfo = entity.GetType().GetProperty(entry.Key); - if (propertyInfo != null) - { - propertyInfo.SetValue(entity, entry.Value, null); - } - } - - // - return entity; - } - - /// - /// Convert From Json String ... - /// - /// - /// - /// - public static T FromJSON(this string value) - { - return JsonConvert.DeserializeObject(value); - } - - /// - /// Convert From Json String ... - /// - /// - /// - /// - public static object FromJSON( - this string value, - Type type - ) - { - return JsonConvert - .DeserializeObject(value, type); - } - - /// - /// Search a Json String for Specific Node ... - /// - /// - /// - /// - public static List FindTokens(this JToken containerToken, string name) - { - List matches = new List(); - FindTokens(containerToken, name, matches); - return matches; - } - - /// - /// Convert to MD5 Bytes ... - /// - /// - /// - public static byte[] ToMd5Bytes(this string source) - { - return new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(source)); - } - - /// - /// Convert to MD5 String ... - /// - /// - /// - public static string ToMd5String(this string source) - { - // - // string representation (similar to UNIX format) - return BitConverter.ToString(source.ToMd5Bytes()) - // without dashes - .Replace("-", string.Empty) - // make lowercase - .ToLower(); - } - - /// - /// Check a String is MD5 String or not ... - /// - /// - /// - public static bool IsMD5String(this string source) - { - // - if (String.IsNullOrEmpty(source)) - { - return false; - } - - // - return Regex.IsMatch(source, "^[0-9a-fA-F]{32}$", RegexOptions.Compiled); - } - - /// - /// Convert an string to Byte array Representation ... - /// - /// - /// - public static byte[] ToBytes(this string source) - { - return Encoding.UTF8.GetBytes(source); - } - - /// - /// Converts Byte Array to String Value ... - /// - /// - /// - public static string FromBytes(this byte[] source) - { - // - var result = Encoding.UTF8.GetString(source, 0, source.Length); - return result; - } - - /// - /// Check object is Null ... - /// - /// - /// - public static bool IsNull(this object source) - { - return source == null; - } - - /// - /// Check collection Has Childs ... - /// - /// - /// - /// - public static bool HasChild(this IList source) - { - return !source.IsNull() && source.Count() > 0; - } - - /// - /// Check collection Has Childs ... - /// - /// - /// - /// - public static bool HasChild(this ICollection source) - { - return !source.IsNull() && source.Count() > 0; - } - - /// - /// Check collection Has Childs ... - /// - /// - /// - /// - public static bool HasChild(this IEnumerable source) - { - return !source.IsNull() && source.Count() > 0; - } - - /// - /// Select Async ... - /// - /// - /// - /// - /// - /// - public static async Task> SelectAsync( - this IEnumerable source, Func> method - ) - { - return await Task.WhenAll(source.Select(async s => await method(s))); - } - - /// - /// Converts an Enumerable to Async Enumerable ... - /// - /// - /// - /// - /// - public static async IAsyncEnumerable ToAsyncEnumerable( - this IEnumerable source, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - foreach (var item in source) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return item; - } - } - - /// - /// Converts an Stream to Model AsyncEnumerator ... - /// - /// - /// - /// - /// - public static async IAsyncEnumerable ToModelAsyncEnumerable( - this Stream source, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Stream ... - if (source.IsNull()) - { - yield break; - } - - // - while (source.CanRead) - { - // - var model = await source - .ReadModelFromStream(cancellationToken); - - // - yield return model; - } - } - - /// - /// Converts an Stream to String AsyncEnumerator ... - /// using Read Line of Stream Reader ...S - /// - /// - /// - /// - public static async IAsyncEnumerable ToStringAsyncEnumerable( - this Stream source, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate Stream ... - if (source.IsNull()) - { - yield break; - } - - // - while (source.CanRead) - { - // - var json = await source - .ReadJsonFromStream(cancellationToken); - - // - yield return json; - } - } - - /// - /// Write a Model to Stream ... - /// - /// an Stream to Write ... - /// a Model instance to Write ... - /// - /// - /// - public static async Task WriteModelToStream( - this Stream source, - T model, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (source.IsNull() || model.IsNull()) - { - return; - } - - // - // Extract Json of Model ... - var json = model.ToJSON(true); - - // - await source.WriteJsonToStream( - json: json, - cancellationToken: cancellationToken - ); - } - - /// - /// Write a Json String to Stream ... - /// - /// an Stream to Write ... - /// json string to write ... - /// - /// - public static async Task WriteJsonToStream( - this Stream source, - string json, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (source.IsNull() || json.IsNullOrEmpty()) - { - return; - } - - // - using (var streamWriter = new StreamWriter(stream: source)) - { - // - using (var jsonWriter = new JsonTextWriter(streamWriter)) - { - // - await jsonWriter.WriteRawAsync(json, cancellationToken); - await jsonWriter.FlushAsync(cancellationToken); - } - } - } - - /// - /// Read a Json Model From Stream ... - /// - /// - /// - /// - /// - public static async Task ReadModelFromStream( - this Stream source, - CancellationToken cancellationToken = default - ) - { - // - T result = default(T); - - // - var json = await source.ReadJsonFromStream(cancellationToken); - if (!json.IsNullOrEmpty()) - { - // - try - { - result = json.FromJSON(); - } - catch - { } - } - - // - return result; - } - - /// - /// Reading Json String From Stream ... - /// - /// an Stream to Write ... - /// - /// - public static async Task ReadJsonFromStream( - this Stream source, - CancellationToken cancellationToken = default - ) - { - // - var result = string.Empty; - - // - // Validate Args ... - if (source.IsNull()) - { - return result; - } - - // - using (var streamReader = new StreamReader(source)) - { - // - result = await Task.Run(() => - { - return streamReader.ReadLine(); - }, - cancellationToken); - } - - // - return result; - } - - /// - /// Update a Collection item ... - /// - /// - /// - /// - /// - /// - public static IList Update( - this IList source, - T sourceItem, - T updateWith - ) - { - // - var result = new List(); - - // - // Validate Args ... - if (!source.HasChild() || - updateWith.IsNull() || - sourceItem.IsNull() - ) - { - return result; - } - - // - // Extract Item from source ... - result = source - .Except(new List() { sourceItem }) - .ToList(); - result.Add(updateWith); - - // - return source; - } - - /// - /// Update a Collection item ... - /// - /// - /// - /// - /// - /// - public static ICollection Update( - this ICollection source, - T sourceItem, - T updateWith - ) - { - // - var result = new List(); - - // - // Validate Args ... - if (!source.HasChild() || - updateWith.IsNull() || - sourceItem.IsNull() - ) - { - return result; - } - - // - // Extract Item from source ... - result = source - .Except(new List() { sourceItem }) - .ToList(); - result.Add(updateWith); - - // - return source; - } - - /// - /// Update a Collection item ... - /// - /// - /// - /// - /// - /// - public static IEnumerable Update( - this IEnumerable source, - T sourceItem, - T updateWith - ) - { - // - var result = new List(); - - // - // Validate Args ... - if (!source.HasChild() || - updateWith.IsNull() || - sourceItem.IsNull() - ) - { - return result; - } - - // - // Extract Item from source ... - result = source - .Except(new List() { sourceItem }) - .ToList(); - result.Add(updateWith); - - // - return source; - } - - /// - /// Select and Retrieve Nth Childs of given List ... - /// - /// - /// - /// - /// - /// - public static IEnumerable GetNthItems(this IList source, int n, bool throwException = false) - { - // - var result = new List(); - if (n < 1 || n > source.Count || source.IsNull() || !source.HasChild()) - { - if (throwException) - { - throw XException.InvalidArgs.ToException(); - } - else - { - return result; - } - } - - // - var index = 0; - foreach (var item in source) - { - // - result.Add(item); - index++; - - // - if (index >= n) - { - break; - } - } - - // - return result; - } - - /// - /// Select and Retrieve Nth Childs of given List ... - /// - /// - /// - /// - /// - /// - public static IEnumerable GetNthItems(this ICollection source, int n, bool throwException = false) - { - return source.ToList().GetNthItems( - n: n, - throwException: throwException - ); - } - - /// - /// Select and Retrieve Nth Childs of given List ... - /// - /// - /// - /// - /// - /// - public static IEnumerable GetNthItems(this IEnumerable source, int n, bool throwException = false) - { - return source.ToList().GetNthItems( - n: n, - throwException: throwException - ); - } - - /// - /// Check an string is Null or Empty ... - /// - /// - /// - public static bool IsNullOrEmpty(this string sourse) - { - return string.IsNullOrEmpty(sourse); - } - - /// - /// Get string Value Attribute of an Enum ... - /// - /// - /// - public static string GetStringValue(this Enum source) - { - var type = source.GetType(); - var fieldInfo = type.GetField(source.ToString()); - var attributes = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[]; - - return attributes != null && attributes.Length > 0 ? - attributes[0].StringValue : null; - } - - /// - /// Extracts digit's of an string ... - /// - /// - /// - public static string GetDigits(this string source) - { - try - { - // - Regex regexObj = new Regex(@"[^\d]"); - return regexObj.Replace(source, ""); - } - catch - { - return null; - } - } - - /// - /// Check an string is contains only digits ... - /// - /// - /// - public static bool IsDigits(this string source) - { - return (source.GetDigits() != null && - source.GetDigits().ToString() == source); - } - - /// - /// Convert to normal string, Trim and ToLower ... - /// - /// - /// - public static string ToNormalString(this string source) - { - // - if (source.IsNullOrEmpty()) - { - return string.Empty; - } - - // - return source.Trim().ToLowerInvariant(); - } - - /// - /// Capitalize an string ... - /// - /// - /// - public static string Capitalize(this string source) - { - // - if (source.IsNullOrEmpty()) - { - return string.Empty; - } - - // - var result = ""; - if (source.Length > 1) - { - // - var firstCharr = source.Substring(0, 1); - var otherParts = source.Substring(1, source.Length - 1); - - // - result = firstCharr.ToUpperInvariant() + otherParts; - } - else - { - result = source.ToUpperInvariant(); - } - - // - return result; - } - - /// - /// Summarize a Text ... - /// - /// - /// - /// - /// - public static string SummarizeContent( - this string source, - int maxAllowedLength = 0, - string endsWith = "" - ) - { - // - var result = string.Empty; - if (source.IsNullOrEmpty() || maxAllowedLength <= 0) - { - // - result = source; - return result; - } - - // - // Pattern of Links ... - var pattern = @"(?:[!]\[(.*?)\]\(.*?\))"; - - // - // Apply Summarization ... - - // - // Replace Markdown Links using RegExp ... - result = Regex.Replace(source, pattern, ""); - - // - // Do Summarization if Length bigger than MaxLength ... - if (result.Length > maxAllowedLength) - { - result = result.Substring(0, maxAllowedLength); - } - - // - // Apply EndsWith if Provided ... - if (!endsWith.IsNullOrEmpty() && - !result.EndsWith(endsWith)) - { - result += endsWith; - } - - // - return result; - } - - /// - /// Check an string is a Valid Representation of PhoneNumber ... - /// - /// - /// - public static bool IsValidMobileNumber(this string source) - { - // - // Validating Mobile Numbers ... - var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance(); - try - { - // - var mPhoneNumber = phoneNumberUtil.Parse(source, null); - if (phoneNumberUtil.IsValidNumber(mPhoneNumber)) - { - // - return true; - } - - // - return false; - } - catch - { - - // - return false; - } - } - - /// - /// Check an string is Valid Representation of Email Address ... - /// - /// - /// - public static bool IsValidEmail(this string source) - { - try - { - var addr = new System.Net.Mail.MailAddress(source); - return addr.Address == source; - } - catch - { - return false; - } - } - - /// - /// Check an string is Valid Representation of URL Address ... - /// - /// - /// - public static bool IsValidUrl(this string url) - { - return Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute); - } - - /// - /// check a URL has / at the end, if not add one ... - /// - /// - /// - public static string NormalizeUrl(this string url) - { - return url.EndsWith("/") ? url : url + "/"; - } - - /// - /// Check an string is GUID or not ... - /// - /// - /// - public static bool IsGuid(this string source) - { - // - // Validate Args ... - if (source.IsNullOrEmpty()) - { - return false; - } - - // - Guid guid; - var result = Guid.TryParse(source, out guid); - - // - return result; - } - - /// - /// Check Specific Guid string is Default Guid or not ... - /// - /// - /// - public static bool IsDefaultGuid(this string guid) - { - // - if (!guid.IsGuid()) - { - return false; - } - - // - var empty = Guid.Empty.ToString(); - return guid == empty; - } - - /// - /// Check Specific Guid is Default Guid or not ... - /// - /// - /// - public static bool IsDefaultGuid(this Guid guid) - { - // - var empty = Guid.Empty; - return guid == empty; - } - - /// - /// Parse an String to related Enumerable Items ... - /// - /// - /// - /// - /// - public static IEnumerable ParseListString( - this string source, - char? separator = null - ) - { - // - if (!separator.HasValue) - { - separator = CommonConstants.DEFAULT_LIST_SEPERATOR; - } - - // - var list = source.Split(separator.Value); - var result = new Collection(); - - // - foreach (var s in list) - { - // - try - { - // - T item = (T)Convert.ChangeType(s, typeof(T)); - - // - result.Add(item); - } - catch { } - } - - // - return result; - } - - /// - /// Converts a List String Representation to GUid List ... - /// - /// - /// - /// - public static IEnumerable ParseListGuid( - this string list, - char? separator = null - ) - { - // - var result = new List(); - - // - if (!separator.HasValue) - { - separator = CommonConstants.DEFAULT_LIST_SEPERATOR; - } - - // - if (list.IsNullOrEmpty()) - { - return result; - } - - // - var items = list.Split(separator.Value); - items.ToList().ForEach(i => - { - // - if (!i.IsNullOrEmpty() && i.IsGuid() && !i.IsDefaultGuid()) - { - // - var gID = new Guid(i); - result.Add(gID); - } - }); - - // - return result; - } - - /// - /// Convert a List to List String ... - /// - /// - /// - /// - /// - public static string ToListString( - this IEnumerable source, - char? separator = null - ) - { - // - if (!separator.HasValue) - { - separator = CommonConstants.DEFAULT_LIST_SEPERATOR; - } - - // - if (!source.HasChild()) - { - return string.Empty; - } - - // - string result = String.Join( - separator - .ToString(), - source - ); - - // - return result; - } - - /// - /// get default value of a Type - /// - /// - /// - /// - public static T Default(this T source) - where T : class - { - return default(T); - } - - /// - /// Check if an object is Null or Default Value - /// - /// - /// - /// - public static bool IsNullOrDefault(this T source) - where T : class - { - return Equals(source, default(T)); - } - - /// - /// convert a timestamp to ISO String representation ... - /// - /// - /// - public static string ISODateString(this long timestamp) - { - // - var time = timestamp.FromTimestamp(); - var result = time.ToString("o"); - - // - return result; - } - - /// - /// Converts a DateTime to Unix Like Long ... - /// - /// - /// - public static long ToTimestamp( - this DateTime source - ) - { - return new DateTimeOffset(source) - .ToUnixTimeMilliseconds(); - } - - /// - /// convert timestamp to DateTime ... - /// - /// - /// - public static DateTime FromTimestamp(this long timestamp) - { - // - var result = DateTimeOffset.FromUnixTimeMilliseconds(timestamp); - return result.DateTime; - } - public static DateTime FromTimestamp(this string source) - { - // - var timestamp = Int64.Parse(source); - var time = timestamp.FromTimestamp(); - return time; - } - - /// - /// Check a Date Time is Expired or not - /// - /// - /// - public static bool IsExPired(this DateTime source) - { - // - if (source.IsNull()) - { - return true; - } - - // - var currentDate = DateTime.UtcNow; - var isExpired = currentDate >= source; - - // - return isExpired; - } - public static bool IsExpired(this long source) - { - var time = source.FromTimestamp(); - return time.IsExPired(); - } - public static bool IsExpired(this string source) - { - // - var time = DateTime.Parse(source); - return time.IsExPired(); - } - - /// - /// Determines a File Type is Image Kind or not - /// - /// - /// - public static bool IsImageKind(this XFileType source) - { - // - var imageKind = new Collection() { - XFileType.Image, - XFileType.CoverImage, - XFileType.ProfileImasge - }; - - // - return imageKind.Contains(source); - } - - /// - /// Encode String as Url - /// - /// - /// - public static string ToUrlEncoded(this string source) - { - return HttpUtility.UrlEncode(source); - } - - /// - /// Decode Url String - /// - /// - /// - public static string ToUrlDecoded(this string source) - { - return HttpUtility.UrlDecode(source); - } - - /// - /// Convert an Object to string for use in HttpParams - /// - /// - /// - /// - public static string ToHttpParamString(this object value, CultureInfo cultureInfo) - { - // - if (value is Enum) - { - // - string name = Enum.GetName(value.GetType(), value); - if (name != null) - { - // - var field = IntrospectionExtensions - .GetTypeInfo(value.GetType()) - .GetDeclaredField(name); - - // - if (field != null) - { - // - var attribute = CustomAttributeExtensions - .GetCustomAttribute(field, typeof(EnumMemberAttribute)) - as EnumMemberAttribute; - - // - if (attribute != null) - { - return attribute.Value != null ? attribute.Value : name; - } - } - } - } - else if (value is bool) - { - return System.Convert.ToString(value, cultureInfo).ToLowerInvariant(); - } - else if (value is byte[]) - { - return System.Convert.ToBase64String((byte[])value); - } - else if (value != null && value.GetType().IsArray) - { - // - var array = Enumerable.OfType((Array)value); - return string.Join(",", Enumerable - .Select( - array, - o => o.ToHttpParamString(cultureInfo))); - } - - // - return System.Convert.ToString(value, cultureInfo); - } - - /// - /// ReShape an Object as HttpParam String - /// - /// - /// - public static string AsHttpParamString(this object value) - { - return System.Uri - .EscapeDataString(value - .ToHttpParamString(CultureInfo.InvariantCulture)); - } - - /// - /// Calculating Date Difference Provider String - /// and Generate Date based on UTC Time in Milliseconds like unix Date ... - /// - /// - /// - public static long GenerateDateTimeOffset(this string offsetProvider) - { - // - if (offsetProvider.IsNullOrEmpty()) - { - return 0; - } - - // - var mExpireValue = 0; - var mExpireValueStr = offsetProvider.GetDigits(); - var mExpireUnit = offsetProvider.Replace(mExpireValueStr, ""); - if (mExpireValueStr.IsNullOrEmpty() || mExpireUnit.IsNullOrEmpty()) - { - return 0; - } - - // - var isParsed = int.TryParse(mExpireValueStr, out mExpireValue); - if (!isParsed) - { - return 0; - } - - // - DateTime? date = null; - switch (mExpireUnit) - { - case "d": - date = DateTime.UtcNow.AddDays(mExpireValue); - break; - - case "h": - date = DateTime.UtcNow.AddHours(mExpireValue); - break; - - case "m": - date = DateTime.UtcNow.AddMinutes(mExpireValue); - break; - - case "s": - date = DateTime.UtcNow.AddSeconds(mExpireValue); - break; - - case "ms": - default: - date = DateTime.UtcNow.AddMilliseconds(mExpireValue); - break; - } - - // - var result = !date.HasValue ? 0 : new DateTimeOffset(date.Value) - .ToUnixTimeMilliseconds(); - - // - return result; - } - - // - #region Int Id Extensions ... - public static bool IsValidIntId(this int source) - { - return source > 0; - } - - public static void ValidateIntId(this int source) - { - // - if (!source.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - } - #endregion - - // - #region Dictionary Extensions ... - /// - /// Converts to Meta Data Representation ... - /// - /// - /// - public static Dictionary AsMetadat(this string source) - { - // - // Validate ... - if (source.IsNullOrEmpty()) - { - return []; - } - - // - // JSON is expected to be like: [0.12, 0.34, ...] ... - var result = source.FromJSON>(); - if (!result.HasChild()) - { - result = []; - } - - // - return result; - } - - /// - /// Safe Metadata Reader ... - /// - /// - /// - /// - public static string GetMetadata( - this IDictionary source, - string key - ) - { - // - var result = string.Empty; - - // - if (!source.IsNullOrDefault() && - source.TryGetValue(key, out result)) - { - return result; - } - - // - return result; - } - #endregion - - // - #region StringExtensions for Identity Server ... - public static string EnsureTrailingSlash(this string input) - { - if (!input.EndsWith("/")) - { - return input + "/"; - } - - return input; - } - - public static bool IsMissing(this string value) - { - return string.IsNullOrWhiteSpace(value); - } - - public static bool IsPresent(this string value) - { - return !string.IsNullOrWhiteSpace(value); - } - - public static string Sha256(this string input) - { - if (input.IsMissing()) return string.Empty; - - using (var sha = SHA256.Create()) - { - var bytes = Encoding.UTF8.GetBytes(input); - var hash = sha.ComputeHash(bytes); - - return Convert.ToBase64String(hash); - } - } - #endregion - - // - #region Private ... - private static void FindTokens(JToken containerToken, string name, List matches) - { - if (containerToken.Type == JTokenType.Object) - { - foreach (JProperty child in containerToken.Children()) - { - if (child.Name == name) - { - matches.Add(child.Value); - } - FindTokens(child.Value, name, matches); - } - } - else if (containerToken.Type == JTokenType.Array) - { - foreach (JToken child in containerToken.Children()) - { - FindTokens(child, name, matches); - } - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\DIExtensions.cs - -using System; -using System.IO; -using System.Linq; -using xCommons.Filters; -using xCommons.Constants; -using xCommons.Providers; -using xCommons.Interfaces; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using System.Collections.Generic; -using Microsoft.AspNetCore.Builder; -using Swashbuckle.AspNetCore.SwaggerUI; -using Swashbuckle.AspNetCore.SwaggerGen; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using xExceptions.Constants; - -namespace xCommons.Extensions -{ - public static partial class DIExtensions - { - /// - /// Inject Specific Registered Service from IServiceCollection - /// - /// - /// - /// - public static T GetRegisteredService(this IServiceCollection source) - { - // - var serviceProvider = source.BuildServiceProvider(); - return serviceProvider.GetService(); - } - - /// - /// Register App Configuration as a Service - /// - /// - /// - /// - public static void AddXAppConfiguration( - this IServiceCollection services, - IConfiguration configuration, - string environment = null - ) - { - // - var appConfiguration = configuration.GetXAppConfiguration(); - appConfiguration.Environment = environment; - - // - services.AddSingleton(appConfiguration); - } - - /// - /// Retrieve Rate Limit Configurations and Register it ... - /// - /// - /// - public static void AddXRateLimitConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXRateLimitConfiguration(); - source.AddXRateLimitConfiguration(config); - } - - /// - /// Register Rate Limit Configuration ... - /// - /// - /// - public static void AddXRateLimitConfiguration( - this IServiceCollection source, - XRateLimitConfiguration configuration - ) - { - // - if (source.IsNull()) - { - XException.InvalidConfiguration.Throw(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Add Environment name to XAppConfiguration ... - /// - /// - /// - public static void AddEnvironmentToXAppConfiguration( - this IApplicationBuilder app, - string environmentName - ) - { - // - // Setting Environment in App Confiuration ... - using (var scope = app.ApplicationServices.CreateScope()) - { - // - // Inject AppConfiguration ... - var appConfiguration = scope.ServiceProvider - .GetRequiredService(); - if (!appConfiguration.IsNull()) - { - appConfiguration.Environment = environmentName; - } - } - } - - /// - /// Retrieve and Register File Type Detector Configuration ... - /// - /// - /// - public static void AddXFileTypeDetectorConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXFileTypeDetectorConfiguration(); - source.AddXFileTypeDetectorConfiguration(config); - } - - /// - /// Register File Type Detector Configuration ... - /// - /// - /// - public static void AddXFileTypeDetectorConfiguration( - this IServiceCollection source, - XFileTypeDetectorConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - configuration = new(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Search Assemblies, Extract XML Comments and - /// Integrate them inside swagger gen documents ... - /// - /// - public static void IncludeAssembliesXMLComments(this SwaggerGenOptions source) - { - // - // Extract all Exists .xml files ... - var basePath = AppContext.BaseDirectory; - var xmlFiles = Directory.GetFiles(basePath, "*.xml", SearchOption.TopDirectoryOnly); - var assemblies = AppDomain.CurrentDomain.GetAssemblies(); - - // - // Loop through Detected XML Files ... - foreach (var xmlFile in xmlFiles) - { - // - try - { - // - // Retrieve file name for Assembly Checking ... - var assemblyName = Path.GetFileNameWithoutExtension(xmlFile); - - // - // Try to retrieve Assembly ... - var assembly = assemblies - .FirstOrDefault(a => a.GetName().Name == assemblyName); - if (!assembly.IsNullOrDefault() || - File.Exists(Path.Combine(basePath, $"{assemblyName}.dll")) - ) - { - // - // Includes Selected XML Comments ... - source.IncludeXmlComments(xmlFile); - } - } - catch (Exception ex) - { - Console.WriteLine($"Warning: Could not include XML comments from {xmlFile}. Error: {ex.Message}"); - } - } - } - - /// - /// Add Required OperationFilters and Authorization Fields to Swagger Options - /// - /// - /// - /// - /// - /// - /// - public static void AddXSwaggerGenOptions( - this SwaggerGenOptions source, - string xmlFilePath = null, - bool addRequiredXPoweredFilter = true, - bool addXTokenAuthorization = true, - bool addXApiKeyAuthorization = true, - bool addDefaultValueFilter = true - ) - { - // - if (source.IsNull()) - { - source = new SwaggerGenOptions(); - } - - // - // Add Xml File Path ... - if (!xmlFilePath.IsNullOrEmpty()) - { - source.IncludeXmlComments(xmlFilePath); - } - - // - // Include all XML Documents ... - source.IncludeAssembliesXMLComments(); - - // - // Handle RequireXPowered Filter ... - if (addRequiredXPoweredFilter) - { - source.OperationFilter(); - } - - // - // Add Default Values Filter ... - if (addDefaultValueFilter) - { - source.OperationFilter(); - } - - // - // Handle XToken Authorizations ... - if (addXTokenAuthorization) - { - // - #region Bearer AccessToken ... - // - source.AddSecurityDefinition(nameof(XAuthorization.AccessToken), new OpenApiSecurityScheme - { - In = ParameterLocation.Header, - Description = "Bearer token", - Type = SecuritySchemeType.ApiKey, - Name = XAuthorization.Header - }); - - // - source.AddSecurityRequirement(new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme { - Reference = new OpenApiReference { - Id = nameof (XAuthorization.AccessToken), - Type = ReferenceType.SecurityScheme - } - }, Array.Empty () - } - }); - #endregion - - // - #region RefreshToken ... - // - source.AddSecurityDefinition(nameof(XAuthorization.RefreshToken), new OpenApiSecurityScheme - { - In = ParameterLocation.Header, - Description = "Refresh Token", - Type = SecuritySchemeType.ApiKey, - Name = XAuthorization.RefreshToken - }); - - // - source.AddSecurityRequirement(new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme { - Reference = new OpenApiReference { - Id = nameof(XAuthorization.RefreshToken), - Type = ReferenceType.SecurityScheme - } - }, Array.Empty () - } - }); - #endregion - - // - #region ExpiresAt ... - // - source.AddSecurityDefinition(nameof(XAuthorization.ExpiresAt), new OpenApiSecurityScheme - { - Description = "Expires at", - In = ParameterLocation.Header, - Type = SecuritySchemeType.ApiKey, - Name = XAuthorization.ExpiresAt - }); - - // - source.AddSecurityRequirement(new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme { - Reference = new OpenApiReference { - Id = nameof (XAuthorization.ExpiresAt), - Type = ReferenceType.SecurityScheme - } - }, Array.Empty () - } - }); - #endregion - } - - // - // Handle XApiKey Authorization ... - if (addXApiKeyAuthorization) - { - // - source.AddSecurityDefinition(nameof(XAuthorization.XApiKey), new OpenApiSecurityScheme - { - In = ParameterLocation.Header, - Name = XAuthorization.XApiKey, - Type = SecuritySchemeType.ApiKey, - Description = "Api Key for Authentication ...", - }); - - // - source.AddSecurityRequirement(new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme { - Reference = new OpenApiReference { - Id = nameof (XAuthorization.XApiKey), - Type = ReferenceType.SecurityScheme - } - }, Array.Empty () - } - }); - } - } - - /// - /// Register Swagger - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXSwagger( - this IServiceCollection source, - IConfiguration configuration, - SwaggerGenOptions settings = null, - string xmlFilePath = null, - bool addRequiredXPoweredFilter = true, - bool addXTokenAuthorization = true, - bool addXApiKeyAuthorization = true, - bool addDefaultValueFilter = true - ) - { - // - var xSwaggerConfig = configuration.GetXSwaggerConfiguration(); - if (xSwaggerConfig.IsNull()) - { - xSwaggerConfig = new XSwaggerConfiguration(); - } - - // - source.AddSingleton(xSwaggerConfig); - - // - #region Prepare SwaggerGenOptions ... - if (settings.IsNull()) - { - settings = new SwaggerGenOptions(); - } - settings.AddXSwaggerGenOptions( - xmlFilePath: xmlFilePath, - addDefaultValueFilter: addDefaultValueFilter, - addXTokenAuthorization: addXTokenAuthorization, - addXApiKeyAuthorization: addXApiKeyAuthorization, - addRequiredXPoweredFilter: addRequiredXPoweredFilter - ); - #endregion - - // - #region Prepare Swagger Doc ... - // - // Api Document Section ... - var apiDoc = new OpenApiInfo - { - Title = xSwaggerConfig.Title, - Version = xSwaggerConfig.Version, - Description = xSwaggerConfig.Description, - }; - - // - // Api Document TermsOfUse URL ... - if (!xSwaggerConfig.TermsOfServiceUrl.IsNullOrEmpty()) - { - apiDoc.TermsOfService = new Uri(xSwaggerConfig.TermsOfServiceUrl); - } - - // - // Contact Section ... - if (!xSwaggerConfig.Contact.IsNull()) - { - // - var apiContact = new OpenApiContact - { - Name = xSwaggerConfig.Contact.Name, - Email = xSwaggerConfig.Contact.Email - }; - - // - // Contact URL ... - if (!xSwaggerConfig.Contact.Url.IsNullOrEmpty()) - { - apiContact.Url = new Uri(xSwaggerConfig.Contact.Url); - } - - // - apiDoc.Contact = apiContact; - } - - // - // License Section ... - if (!xSwaggerConfig.License.IsNull()) - { - // - var apiLicense = new OpenApiLicense - { - Name = xSwaggerConfig.License.Name, - }; - - // - // License URL ... - if (!xSwaggerConfig.License.Url.IsNullOrEmpty()) - { - apiLicense.Url = new Uri(xSwaggerConfig.License.Url); - } - - // - apiDoc.License = apiLicense; - } - #endregion - - // - // Register Swagger ... - source.AddSwaggerGen( - opt => - { - // - opt.UpdateData(settings); - - // - opt.SwaggerDoc("v1", apiDoc); - } - ); - - // - // Register Swagger Operation Filters ... - } - - /// - /// Use Sagger - /// - /// - /// - public static void UseXSwagger( - this IApplicationBuilder source, - SwaggerUIOptions options = null - ) - { - // - source.UseSwagger(); - - // - if (options.IsNull()) - { - source.UseSwaggerUI(); - } - else - { - source.UseSwaggerUI(options: options); - } - } - - /// - /// Add Cross Origin Resource Sharings - /// - /// - /// - public static void AddXCors( - this IServiceCollection source, - IEnumerable allowedOrigins - ) - { - // - if (!allowedOrigins.HasChild()) - { - // - Console.WriteLine($"XCommons: there is no provided allowedOrigins, start app without any specific cors, this may be unsecure ..."); - - // - source.AddCors(options => - { - options.AddPolicy(XPolicy.AllowedOrigins, - builder => - { - builder - .AllowAnyOrigin() - .AllowAnyHeader() - .AllowAnyMethod() - .WithExposedHeaders("*"); - }); - }); - - // - return; - } - - // - source.AddCors(options => - { - options.AddPolicy(XPolicy.AllowedOrigins, - builder => - { - builder - .WithOrigins(allowedOrigins.ToArray()) - .AllowAnyHeader() - .AllowAnyMethod() - .AllowCredentials() - .WithExposedHeaders("*"); - }); - }); - } - - /// - /// Register RateLimit Service ... - /// - /// - public static void AddXRateLimit( - this IServiceCollection source - ) - { - // - source.AddMemoryCache(); - source.AddSingleton(); - } - - /// - /// Register RateLimit Service ... - /// Configs Retrieved from AppSettings ... - /// - /// - /// - public static void AddXRateLimit( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXRateLimitConfiguration(); - source.AddXRateLimit(config); - } - - /// - /// Register RateLimit Service ... - /// - /// - /// - public static void AddXRateLimit( - this IServiceCollection source, - XRateLimitConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - XException.InvalidConfiguration.Throw(); - } - - // - source.AddXRateLimitConfiguration(configuration); - source.AddXRateLimit(); - } - - public static void AddXFileTypeDetector( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - source.AddXFileTypeDetectorConfiguration(configuration); - source.AddSingleton(); - } - - /// - /// Use X Registered Cross Origin Resource Sharings - /// - /// - public static void UseXCors(this IApplicationBuilder sources) - { - // - sources.UseCors(XPolicy.AllowedOrigins); - } - - /// - /// Register Api V1 Versioning ... - /// - /// - public static void AddXApiV1Versioning(this IServiceCollection services) - { - // - // Register Api Versioning ... - services.AddApiVersioning(opt => - { - // - // Set Default Api Version ... - opt.DefaultApiVersion = new ApiVersion(1, 0); - - // - // Set Routing to Default API Version, if Version unspecified ... - opt.AssumeDefaultVersionWhenUnspecified = true; - - // - // Report All Available Api Versions on Response ... - opt.ReportApiVersions = true; - }); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\EnumExtensions.cs - -using System; -using System.Collections.Generic; - -namespace xCommons.Extensions { - public static partial class EnumExtensions { - public static string GetKey (this Enum source) { - return Enum.GetName (source.GetType (), source); - } - - public static T GetValue (this string source) { - return (T) Enum.Parse (typeof (T), source); - } - - public static void Iterate (this IEnumerator source, Action action) { - // - while (source.MoveNext ()) { - // - var current = source.Current; - action (current); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\ExceptionExtensions.cs - -using System; -using xExceptions.Models; -using xExceptions.Constants; - -namespace xCommons.Extensions { - /// - /// this is an extension pack for Exceptions - /// - public static partial class ExceptionExtensions { - - /// - /// determines an string contains an XError content or not - /// - /// - /// - public static bool IsXError (this string source) { - // - if (source.IsNullOrEmpty ()) { - return false; - } - - // - var xError = source.ToXError (); - if (xError != null) { - return true; - } - - // - // If Convert Proccess fails ... - var normalString = source.ToNormalString (); - - // - // Return result based on string values ... - return normalString.Contains ("id") && normalString.Contains ("message"); - } - - /// - /// deserialize an string to to XError class instance - /// - /// - /// - public static XError ToXError (this string source) { - // - if (source.IsNullOrEmpty ()) { - return null; - } - - // - try { - // - var err = source.FromJSON (); - - // - // if err is null we have to manually get value - if (err == null) { - // - var normalString = source.ToNormalString (); - var parts = normalString.Split (','); - if (parts.Length > 2) { - return null; - } - - // - var idContainer = parts[0]; - var messageContainer = parts[1]; - } - - // - return err; - } catch { - return null; - } - } - - public static XError ToXError (this XException source) { - // - var errorId = (int) source; - var errorMessage = source.GetStringValue (); - - // - return new XError { - Id = errorId, - Message = errorMessage - }; - } - - /// - /// Convert an XError instance to an Exception - /// - /// - /// - public static Exception ToException (this XError source) { - // - var jsonStr = source.ToJSON (); - return new Exception (jsonStr); - } - - public static Exception ToException (this XException source) { - return source - .ToXError () - .ToException (); - } - - /// - /// Convert an Exception to corresponding XError Object - /// - /// - /// - public static XError FromException (this Exception source) { - // - if (source == null || source.Message.IsNullOrEmpty ()) { - return null; - } - - // - return source.Message.ToXError (); - } - - /// - /// Add Content to Contentable XException member and return XError Object - /// - /// - /// - /// - public static XError AddContentToError (this XException exception, string value) { - // - var xError = exception.ToXError (); - xError.Message = string.Format (xError.Message, value); - - // - return xError; - } - - /// - /// Add Content to Contentable XException member and return Exception Object - /// - /// - /// - /// - public static Exception AddContentToException (this XException exception, string value) { - // - var xError = exception.ToXError (); - xError.Message = string.Format (xError.Message, value); - - // - return xError.ToException (); - } - - /// - /// Throw Specific Exception ... - /// - /// - /// - public static void Throw ( - this XException source, - string content = null - ) { - // - Exception exception = null; - if (content.IsNullOrEmpty ()) { - exception = source.ToException (); - } else { - exception = source.AddContentToException (content); - } - - // - throw exception; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\FilterExtensions.cs - -using System.Linq; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc.Authorization; - -namespace xCommons.Extensions { - public static partial class FilterExtensions { - public static XAppConfiguration GetXAppConfiguration (this ActionExecutingContext source) { - // - var services = source.HttpContext.RequestServices; - return (XAppConfiguration) services.GetService (typeof (XAppConfiguration)); - } - - public static XAppConfiguration GetXAppConfiguration (this AuthorizationFilterContext source) { - // - var services = source.HttpContext.RequestServices; - return (XAppConfiguration) services.GetService (typeof (XAppConfiguration)); - } - - public static bool IsAnonymousAllowed (this AuthorizationFilterContext source) { - // - var result = source.Filters - .Any (f => f.GetType () == typeof (AllowAnonymousFilter)) || - source.ActionDescriptor.FilterDescriptors - .Any (f => f.GetType () == typeof (AllowAnonymousFilter)) || - source.ActionDescriptor.EndpointMetadata - .Any (f => f.GetType () == typeof (AllowAnonymousAttribute)); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\IConfigurationExtensions.cs - -using System.Linq; -using xCommons.Constants; -using xCommons.Configurations; -using System.Collections.Generic; -using Microsoft.Extensions.Configuration; - -namespace xCommons.Extensions -{ - public static partial class IConfigurationExtensions - { - /// - /// Retrieve AppConfiguration from Configurations - /// - /// - /// - public static XAppConfiguration GetXAppConfiguration(this IConfiguration source) - { - // - var xMessageResourceTitlesConfigSection = source - .GetSection(ConfigurationNodeNames.MESSAGE_RESOURCE_TITLES_NODE); - - // - var result = new XAppConfiguration - { - Name = source[nameof(XAppConfiguration.Name)], - Version = source[nameof(XAppConfiguration.Version)], - XPoweredValue = source[nameof(XAppConfiguration.XPoweredValue)], - WelcomeMessage = source[nameof(XAppConfiguration.WelcomeMessage)], - AllowedOrigins = source - .GetSection(nameof(XAppConfiguration.AllowedOrigins)) - .Get>(), - DefaultLanguage = source[nameof(XAppConfiguration.DefaultLanguage)], - MessageResourceTitles = xMessageResourceTitlesConfigSection - .Get() - }; - - // - return result; - } - - /// - /// Retrieve Swagger Configurations - /// - /// - /// - public static XSwaggerConfiguration GetXSwaggerConfiguration(this IConfiguration source) - { - // - var xSwaggerConfigSection = source - .GetSection(ConfigurationNodeNames.SWAGGER_NODE); - return xSwaggerConfigSection.Get(); - } - - /// - /// Retrieve RateLimit Configurations ... - /// - /// - /// - public static XRateLimitConfiguration GetXRateLimitConfiguration(this IConfiguration source) - { - // - var section = source - .GetSection(ConfigurationNodeNames.RATE_LIMIT_NODE); - - // - var result = section.Get(); - return result; - } - - /// - /// Retrieve File Type Detector Configuration ... - /// - /// - /// - public static XFileTypeDetectorConfiguration GetXFileTypeDetectorConfiguration(this IConfiguration source) - { - // - var section = source - .GetSection(ConfigurationNodeNames.FILE_TYPE_DETECTOR_NODE); - - // - var result = section.Get(); - if (result.IsNull()) - { - result = new(); - } - - // - return result; - } - - /// - /// Converts a ConfigurationSection to object Representation ... - /// - /// - /// - public static object ToObject(this IConfigurationSection section) - { - // - // an Inner Function for Create Recursive Parsing ... - object ConvertSection(IConfigurationSection sec) - { - // - var children = sec - .GetChildren() - .ToList(); - if (!children.Any()) - { - return sec.Value ?? string.Empty; - } - - // - // Detect Array Like Sections ... - bool isArray = children.All(ch => int.TryParse(ch.Key, out _)); - if (isArray) - { - // - return children - .OrderBy(c => int.Parse(c.Key)) - .Select(ConvertSection) - .ToList(); - } - - // - // Otherwise ... - return children - .ToDictionary( - c => c.Key, - c => ConvertSection(c) - ); - } - - // - // Try to Parse using Inner Function ... - var result = ConvertSection(section); - - // - return result; - } - - /// - /// Converts a ConfigurationSection to Json Representation ... - /// - /// - /// - public static string ToJSON(this IConfigurationSection section) - { - // - // Try to Parse using Inner Function ... - var obj = section.ToObject(); - - // - // Convert it to Json ... - var result = obj.ToJSON(); - - // - return result; - } - - /// - /// Get a Configuration Section as Object ... - /// - /// - /// - /// - public static object GetSectionAsObject( - this IConfiguration source, - string section - ) - { - // - object result = null; - - // - if (!section.IsNullOrEmpty()) - { - // - var sec = source.GetSection(section); - if (!sec.IsNull()) - { - result = sec.ToObject(); - } - } - - // - return result; - } - - /// - /// Retrieve a Configuration Section as Json String ... - /// - /// - /// - /// - public static string GetSectionAsJson( - this IConfiguration source, - string section - ) - { - // - var result = string.Empty; - - // - // Retrieve Secion as Object ... - var obj = source.GetSectionAsObject(section); - if (!obj.IsNull()) - { - // - // Converts Section Object to Json ... - result = obj.ToJSON(); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\IFormFileExtensions.cs - -using System; -using System.IO; -using System.Text; -using UglyToad.PdfPig; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; - -namespace xAiModels.Extensions -{ - public static class IFormFileExtensions - { - /// - /// Read a IFormFile Content as byte array ... - /// - /// - /// - /// - public static async Task ReadAsBytes( - this IFormFile source, - CancellationToken cancellationToken = default - ) - { - // - // Create and use a Memory Stream ... - using var stream = new MemoryStream(); - - // - // Copy File Content to Stream ... - await source.CopyToAsync( - target: stream, - cancellationToken: cancellationToken - ); - - // - // Read Stream Content as byte array ... - var result = stream.ToArray(); - - // - return result; - } - - /// - /// Read a File Content by it's Path as byte array ... - /// - /// - /// - /// - /// - /// - public static async Task ReadAsBytes( - this string filePath, - int bufferSize = 81920, - CancellationToken cancellationToken = default - ) - { - // - if (string.IsNullOrWhiteSpace(filePath)) - { - throw new Exception("Invalid Args ..."); - } - - // - // Create and use a Memory Stream ... - using var memStream = new MemoryStream(); - - // - using var stream = new FileStream( - path: filePath, - mode: FileMode.Open, - access: FileAccess.Read, - share: FileShare.ReadWrite - ); - - // - // Copy File Content to Stream ... - await stream.CopyToAsync( - destination: memStream, - bufferSize: bufferSize, - cancellationToken: cancellationToken - ); - - // - // Read Stream Content as byte array ... - var result = memStream.ToArray(); - - // - return result; - } - - /// - /// Read Text Content of Document ... - /// - /// - /// - /// - public static async Task ReadContent( - this IFormFile source, - CancellationToken cancellationToken = default - ) - { - // - // Check if File PDF or not ... - var isPDF = source.ContentType - .ToNormalString() - .Contains("pdf" - .ToNormalString()); - - // - var result = string.Empty; - - // - var isValidFileType = isPDF; - if (!isValidFileType) - { - return result; - } - - // - if (isPDF) - { - // - // Reading File Content as Byte array ... - var fileBytes = await source.ReadAsBytes(cancellationToken); - - // - // Create a PDF Document ... - using var stream = new MemoryStream(fileBytes); - using var document = PdfDocument.Open(stream); - - // - // Extract PDF Text ... - var textBuilder = new StringBuilder(); - foreach (var page in document.GetPages()) - { - textBuilder.Append(page.Text); - } - - // - result = textBuilder.ToString(); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\ModelExtensions.cs - -using System; -using System.Linq; -using System.Reflection; -using System.Linq.Expressions; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace xCommons.Extensions -{ - public static partial class ModelExtensions - { - /// - /// Retrieve a Binding Flag for Retrieve all Instance Members including - /// Priate and Public ... - /// - /// - public static BindingFlags GetDefaultBindingFlag() - { - return BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - } - - /// - /// Update an Instance of a Typed Object with Data Provided by another Instance of Typed Object - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static T UpdateData( - this T source, - D updateWith, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueProviders = null, - bool updateWithNullOrEmptyValues = false, - bool throwExceptionOnFails = false - ) - where T : class - where D : class - { - // - var hasWhiteList = propertyWhiteList.HasChild(); - var hasBlackList = propertyBlackList.HasChild(); - var hasValueProvider = propertyValueProviders.HasChild>>(); - - // - var fullPropertyList = updateWith.GetType().GetProperties().Select(prop => prop.Name); - var mustSetProps = (hasWhiteList ? propertyWhiteList : fullPropertyList); - - // - if (hasBlackList) - { - mustSetProps = mustSetProps.Where(propName => !propertyBlackList.Contains(propName)); - } - - // - mustSetProps.ToList().ForEach(propName => - { - // - try - { - // - var sourceProp = source.GetType().GetProperty(propName); - var sourceValue = sourceProp.GetValue(source); - var sourceValueType = sourceValue.IsNull() ? null : sourceValue.GetType(); - - // - var updateWithProp = updateWith.GetType().GetProperty(propName); - var updateWithValue = updateWithProp.GetValue(updateWith); - var updateWithValueType = updateWithValue.IsNull() ? null : updateWithValue.GetType(); - - // - var valueProviderValue = hasValueProvider ? propertyValueProviders - .FirstOrDefault(p => p.Key == propName).Value : null; - var updateVal = !valueProviderValue.IsNull() ? - valueProviderValue.Invoke(updateWith) : - (updateWithValue.IsNull() && !updateWithNullOrEmptyValues) ? - sourceValue : updateWithValue; - var updateValType = updateVal.IsNull() ? null : updateVal.GetType(); - - // - Type t = Nullable.GetUnderlyingType(sourceProp.PropertyType) ?? sourceProp.PropertyType; - object safeValue = - (updateVal == null) ? - null : - !updateValType.IsCollectionType() ? - Convert.ChangeType(updateVal, t) : - updateVal; - - // - sourceProp.SetValue(source, safeValue); - } - catch (Exception ex) - { - // - if (throwExceptionOnFails) - { - throw ex; - } - } - }); - - // - return source; - } - - /// - /// Check a Class is Contains a Property or not ... - /// - /// - /// - /// - /// - /// - public static bool HasProperty( - this T source, - string property, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - var result = source - .GetType() - .GetProperties(bindingAttr) - .Any(prop => prop.Name == property); ; - - // - return result; - } - - /// - /// Check a Class is Contains a field or not ... - /// - /// - /// - /// - /// - /// - public static bool HasField( - this T source, - string field, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - var result = source - .GetType() - .GetFields(bindingAttr) - .Any(fld => fld.Name == field); - - // - return result; - } - - /// - /// Check a Class is Contains a Method or not ... - /// - /// - /// - /// - /// - /// - public static bool HasMethod( - this T source, - string method, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - var result = source - .GetType() - .GetMethods(bindingAttr) - .Any(mthd => mthd.Name == method); - - // - return result; - } - - /// - /// Retrieve a Class Properties Names ... - /// - /// - /// - /// - /// - public static string[] GetPropertiesNames( - this T source, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - { - // - var result = source - .GetType() - .GetProperties(bindingAttr) - .Select(p => p.Name) - .ToArray(); - - // - return result; - } - - /// - /// Retrieve a Class Fields Names ... - /// - /// - /// - /// - /// - public static string[] GetFieldsNames( - this T source, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - { - // - var result = source - .GetType() - .GetFields(bindingAttr) - .Select(p => p.Name) - .ToArray(); - - // - return result; - } - - /// - /// Retrieve a Class Methods Names ... - /// - /// - /// - /// - /// - public static string[] GetMethodsNames( - this T source, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - { - // - var result = source - .GetType() - .GetMethods(bindingAttr) - .Select(p => p.Name) - .ToArray(); - - // - return result; - } - - /// - /// Retrieve a Class Members Names ... - /// - /// - /// - /// - /// - public static string[] GetMembersNames( - this T source, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - { - // - var result = source - .GetType() - .GetMembers(bindingAttr) - .Select(p => p.Name) - .ToArray(); - - // - return result; - } - - /// - /// Get a Class Property Value using Generic Concept ... - /// - /// - /// - /// - /// - /// - /// - public static TProp GetProperty( - this T source, - string property, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - TProp result = default; - - // - // Check if T Has Property ... - if (source.HasProperty(property)) - { - // - // Access Property ... - var prop = source - .GetType() - .GetProperty( - property, - bindingAttr - ); - - // - // Retrieve Property Value as Object ... - var propVal = prop.GetValue(source); - - // - result = (TProp)propVal; - } - - // - return result; - } - - /// - /// Get a Class Field Value using Generic Concept ... - /// - /// - /// - /// - /// - /// - /// - public static TField GetField( - this T source, - string field, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - TField result = default; - - // - if (source.HasField(field)) - { - // - var fld = source - .GetType() - .GetField( - field, - bindingAttr - ); - - // - var fieldVal = fld.GetValue(source); - result = (TField)fieldVal; - } - - // - return result; - } - - /// - /// Set a Class Property Value using Generic Concept ... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool SetProperty( - this T source, - string property, - TProp value, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - // Check T Has Property ... - var result = source.HasProperty(property); - if (!result) - { - return result; - } - - // - // Access Property ... - var prop = source - .GetType() - .GetProperty( - property, - bindingAttr - ); - - // - // Set Property ... - try - { - // - result = true; - prop.SetValue(source, value); - } - catch - { - result = false; - } - - // - return result; - } - - /// - /// Set a Class Field Value using Generic Concept ... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool SetField( - this T source, - string field, - TField value, - BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic - ) - where T : class - { - // - // Check T Has Field ... - var result = source.HasField(field); - if (!result) - { - return result; - } - - // - // Access Field ... - var fld = source - .GetType() - .GetField( - field, - bindingAttr - ); - - // - // Set Value ... - try - { - // - result = true; - fld.SetValue(source, value); - } - catch - { - result = false; - } - - // - return result; - } - - /// - /// Check two Instance of Typed Object Values are Same or not - /// - /// - /// - /// - /// - /// - /// - /// /// - /// - /// - public static bool IsSameContent( - this T source, - D dest, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueCheckers = null, - bool throwExceptionOnFails = false - ) - where T : class - where D : class - { - // - var hasWhiteList = propertyWhiteList.HasChild(); - var hasBlackList = propertyBlackList.HasChild(); - var hasCheckerProvider = propertyValueCheckers.HasChild>>(); - - // - var fullPropertyList = dest.GetType().GetProperties().Select(prop => prop.Name); - var mustCheckProps = (hasWhiteList ? propertyWhiteList : fullPropertyList); - if (hasBlackList) - { - mustCheckProps = mustCheckProps.Where(propName => !propertyBlackList.Contains(propName)); - } - - // - var result = true; - mustCheckProps.ToList().ForEach(propName => - { - // - try - { - // - var sourceProp = source.GetType().GetProperty(propName); - var destProp = dest.GetType().GetProperty(propName); - - // - // Check Types ... - var isSameType = true; - - // - // Check - var isSameValue = false; - var mustDoCustomCheck = hasCheckerProvider && propertyValueCheckers.Any(p => p.Key == propName); - if (mustDoCustomCheck) - { - // - // Check Values ... - var valueChecker = propertyValueCheckers.FirstOrDefault(p => p.Key == propName).Value; - isSameValue = valueChecker.Invoke(source, dest); - } - else - { - // // - // isSameType = (sourceProp.PropertyType == destProp.PropertyType && - // sourceProp.ReflectedType == destProp.ReflectedType); - - // - // Check Values ... - isSameValue = Equals(sourceProp.GetValue(source), destProp.GetValue(dest)); - } - - // - if (!isSameType || !isSameValue) - { - result = false; - } - } - catch (Exception ex) - { - // - if (throwExceptionOnFails) - { - throw ex; - } - } - }); - - // - return result; - } - - /// - /// Check specific type is Collection Type or not - /// - /// - /// - public static bool IsCollectionType(this Type source) - { - // - if (source.IsNull() || !source.IsGenericType) - { - return false; - } - - // - var genericTypeDefinition = source.GetGenericTypeDefinition(); - var result = genericTypeDefinition == typeof(List<>) || - genericTypeDefinition == typeof(HashSet<>) || - genericTypeDefinition == typeof(Collection<>) || - genericTypeDefinition == typeof(ICollection<>) || - genericTypeDefinition == typeof(IEnumerable<>); - - // - return result; - } - - /// - /// Retrieve a Property Value in Generic - /// - /// - /// - /// - public static string GetPropValues(this T item) - where T : class - { - // - var props = item.GetType().GetProperties(); - var vals = props.Select(p => p.GetValue(item)); - - // - return vals.ToJSON(); - } - - /// - /// Check a Property Value Contains specific value - /// - /// - /// - /// - /// - public static bool PropValuesContains(this T item, string value) - where T : class - { - // - return item.GetPropValues() - .ToNormalString() - .Contains(value - .ToNormalString()); - } - - /// - /// Generate Default Column Map - /// - /// - /// - /// - public static IDictionary>> GetDefaultColumnsMap(this T item) - where T : class - { - // - if (item.IsNull()) - { - return null; - } - - // - var result = new Dictionary>>(); - var props = item.GetType().GetProperties(); - - // - foreach (var prop in props) - { - result.Add(prop.Name, t => t.GetType().GetProperty(prop.Name).GetValue(t, null)); - } - - // - return result; - } - - /// - /// Generate Default Column Map - /// - /// - /// - /// - public static IDictionary GetPropValuesDictionary(this T item) - where T : class - { - // - if (item.IsNull()) - { - return null; - } - - // - var result = new Dictionary(); - var props = item.GetType().GetProperties(); - - // - foreach (var prop in props) - { - result.Add(prop.Name, prop.GetValue(item).ToJSON()); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\ServiceProviderExtensions.cs - -using System; -using xCommons.Helpers; -using System.Collections; -using System.Collections.Generic; -using Microsoft.Extensions.DependencyInjection; - -namespace xCommons.Extensions { - public static class ServiceProviderExtensions { - /// - /// Get all registered - /// - /// - /// - public static Dictionary GetAllServiceDescriptors (this IServiceProvider provider) { - // - if (provider is ServiceProvider serviceProvider) { - // - var result = new Dictionary (); - - // - var engine = serviceProvider.GetFieldValue ("_engine"); - var callSiteFactory = engine.GetPropertyValue ("CallSiteFactory"); - var descriptorLookup = callSiteFactory.GetFieldValue ("_descriptorLookup"); - if (descriptorLookup is IDictionary dictionary) { - foreach (DictionaryEntry entry in dictionary) { - result.Add ((Type) entry.Key, (ServiceDescriptor) entry.Value.GetPropertyValue ("Last")); - } - } - - // - return result; - } - - // - throw new NotSupportedException ($"Type '{provider.GetType()}' is not supported!"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\XCommonsExtensions.cs - -using System.Linq; -using xCommons.Configurations; - -namespace xCommons.Extensions -{ - public static class XCommonsExtensions - { - /// - /// Extract RateLimit Rule based on given Path ... - /// - /// - /// - /// - public static XRateLimitRule GetMatchingRule( - this XRateLimitConfiguration source, - string path - ) - { - // - if (!source.Enabled) - { - return null; - } - - // - var normalizedPath = path.IsNullOrEmpty() - ? "/" - : path.ToNormalString(); - - // - var rule = source.Rules.IsNull() - ? null - : source.Rules - .Where(r => - !r.IsNull() && - r.Enabled && - !r.PathPrefix.IsNullOrEmpty() && - normalizedPath.StartsWith(r.PathPrefix.ToNormalString())) - .OrderByDescending(r => r.PathPrefix.Length) - .FirstOrDefault(); - - // - if (!rule.IsNull()) - { - return rule; - } - - // - if (source.ApplyToAllRoutes) - { - // - return new XRateLimitRule - { - Enabled = true, - Name = "Default", - PathPrefix = "/", - Limit = source.DefaultLimit, - KeyMode = source.DefaultKeyMode, - PeriodSeconds = source.DefaultPeriodSeconds, - }; - } - - // - return null; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\XHttpContextExtensions.cs - -using System.IO; -using xCommons.Constants; -using Microsoft.AspNetCore.Http; - -namespace xCommons.Extensions -{ - public static partial class XHttpContextExtensions - { - /// - /// Convert IFormFile to Bytes Array - /// - /// - /// - public static byte[] ToByteArray(this IFormFile source) - { - // - byte[] data; - using (var br = new BinaryReader(source.OpenReadStream())) - { - data = br.ReadBytes((int)source.OpenReadStream().Length); - } - - // - return data; - } - - /// - /// Extract Rate Limit Key ... - /// - /// - /// - /// - public static string GetXRateLimitKey( - this HttpContext source, - XRateLimitKeyMode keyMode - ) - { - // - if (source.IsNull()) - { - return "unknown"; - } - - // - switch (keyMode) - { - // - case XRateLimitKeyMode.ClientId: - { - // - var clientId = source.Request.Headers[XRateLimitConstants.ClientIdHeader].ToString(); - return clientId.IsNullOrEmpty() - ? "anonymous" - : clientId.ToNormalString(); - } - - // - case XRateLimitKeyMode.User: - { - // - var userId = source.User?.FindFirst(XCustomClaims.UserId)?.Value; - if (userId.IsNullOrEmpty()) - { - userId = source.User?.Identity?.Name; - } - - // - return userId.IsNullOrEmpty() - ? "anonymous" - : userId.ToNormalString(); - } - - // - case XRateLimitKeyMode.Route: - { - // - return string.Format( - "{0}:{1}", - source.Request.Method, - source.Request.Path - ).ToNormalString(); - } - - // - case XRateLimitKeyMode.Custom: - { - return "custom"; - } - - // - case XRateLimitKeyMode.Ip: - default: - { - // - return source.Connection.RemoteIpAddress - .IsNull() - ? "unknown" - : source.Connection.RemoteIpAddress - .ToString() - .ToNormalString(); - } - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\XHttpExtensions.cs - -using System; -using System.Net; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.AspNetCore.Hosting.Server.Features; - -namespace xCommons.Extensions -{ - /// - /// All Extensions around Http ... - /// - public static class XHttpExtensions - { - /// - /// Write Response as JSON ... - /// - /// - /// - /// - /// - public static async Task WriteResponseAsJsonAsync( - this HttpContext source, - HttpStatusCode status, - object data - ) - { - // - await source.Response.WriteJsonAsync( - data: data, - status: status - ); - } - - /// - /// Write JSON ... - /// - /// - /// - /// - /// - public static async Task WriteJsonAsync( - this HttpResponse source, - HttpStatusCode status, - object data - ) - { - // - source.StatusCode = (int)status; - source.ContentType = "application/json; charset=utf-8"; - var json = data.ToJSON(); - - // - await source.WriteAsync(json); - } - - /// - /// Copy Request Headers ... - /// - /// - /// - /// - public static void CopyRequestHeaders( - this HttpContext source, - HttpContent dest, - string[] exceptions = null - ) - { - // - if (dest.IsNull() || source.IsNull()) - { - return; - } - - // - source.Request.CopyHeaders( - dest: dest, - exceptions: exceptions - ); - } - - /// - /// Copy Request Headers ... - /// - /// - /// - /// - public static void CopyRequestHeaders( - this HttpContext source, - HttpRequestMessage dest, - string[] exceptions = null - ) - { - // - if (dest.IsNull() || source.IsNull()) - { - return; - } - - // - source.Request.CopyHeaders( - dest: dest, - exceptions: exceptions - ); - } - - /// - /// Copy Headers ... - /// - /// - /// - /// - public static void CopyHeaders( - this HttpRequest source, - HttpContent dest, - string[] exceptions = null - ) - { - // - if (dest.IsNull() || source.IsNull()) - { - return; - } - - // - foreach (var header in source.Headers) - { - // - if ( - exceptions.HasChild() && - exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) - ) - { - continue; - } - - // - dest.Headers.TryAddWithoutValidation( - name: header.Key, - values: [.. header.Value] - ); - } - } - - /// - /// Copy Headers ... - /// - /// - /// - /// - public static void CopyHeaders( - this HttpRequest source, - HttpRequestMessage dest, - string[] exceptions = null - ) - { - // - if (dest.IsNull() || source.IsNull()) - { - return; - } - - // - foreach (var header in source.Headers) - { - // - if ( - exceptions.HasChild() && - exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) - ) - { - continue; - } - - // - dest.Headers.TryAddWithoutValidation( - name: header.Key, - values: [.. header.Value] - ); - } - } - - /// - /// Copy Headers ... - /// - /// - /// - /// - public static void CopyHeaders( - this HttpResponseMessage source, - HttpContext context, - string[] exceptions = null - ) - { - // - // Validate ... - if (source.IsNull() || context.IsNull()) - { - return; - } - - // - source.CopyHeaders( - exceptions: exceptions, - response: context.Response - ); - } - - /// - /// Copy Headers ... - /// - /// - /// - /// - public static void CopyHeaders( - this HttpResponseMessage source, - HttpResponse response, - string[] exceptions = null - ) - { - // - // Validate ... - if (source.IsNull() || response.IsNull()) - { - return; - } - - // - foreach (var header in source.Headers) - { - // - if ( - exceptions.HasChild() && - exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) - ) - { - continue; - } - - // - response.Headers[header.Key] = header.Value.ToArray(); - } - - // - foreach (var header in source.Content.Headers) - { - // - if ( - exceptions.HasChild() && - exceptions.Any(xh => xh.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)) - ) - { - continue; - } - - // - response.Headers[header.Key] = header.Value.ToArray(); - } - } - - /// - /// Extract Application Urls ... - /// - /// - /// - public static ICollection GetApplicationUrls( - this IServiceProvider services - ) - { - // - var server = services.GetService(); - var addresses = server?.Features.Get(); - var result = addresses?.Addresses ?? Array.Empty(); - - // - return result; - } - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Extensions\XMiddlewareExtensions.cs - -using xCommons.Middlewares; -using Microsoft.AspNetCore.Builder; - -namespace xCommons.Extensions -{ - public static partial class XMiddlewareExtensions - { - /// - /// Use XRateLimit Middleware ... - /// - /// - /// - public static IApplicationBuilder UseXRateLimit( - this IApplicationBuilder source - ) - { - return source.UseMiddleware(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Filters\RequireXPoweredOperationFilter.cs - -using xCommons.Constants; -using xCommons.Extensions; -using Microsoft.OpenApi.Any; -using xCommons.Configurations; -using Microsoft.OpenApi.Models; -using System.Collections.Generic; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace xCommons.Filters { - /// - /// RequireXPowered for NGSwag - /// - public partial class RequireXPoweredOperationFilter : IOperationFilter { - private readonly XAppConfiguration config; - - public RequireXPoweredOperationFilter (XAppConfiguration config) { - this.config = config; - } - - public void Apply (OpenApiOperation operation, OperationFilterContext context) { - // - if (operation.Parameters.IsNull ()) { - operation.Parameters = new List (); - } - - // - operation.Parameters.Add (new OpenApiParameter { - In = ParameterLocation.Header, - Name = XAuthorization.XPoweredBy, - Description = "a Basic Authorization Filter", - Required = false, - Schema = new OpenApiSchema { - Type = "String", - Default = new OpenApiString (config.XPoweredValue) - } - }); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Filters\SwaggerDefaultValuesOperationFilter.cs - -using System.Linq; -using xCommons.Extensions; -using Microsoft.OpenApi.Any; -using xCommons.Configurations; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace xCommons.Filters -{ - public class SwaggerDefaultValuesOperationFilter : IOperationFilter - { - private readonly XSwaggerConfiguration config; - - public SwaggerDefaultValuesOperationFilter( - XSwaggerConfiguration config - ) - { - this.config = config; - } - - public void Apply( - OpenApiOperation operation, - OperationFilterContext context - ) - { - // - // Validate Configuration ... - if ( - !config.IsNull() && - !config.DefaultValues.IsNull() && - config.DefaultValues.HasChild() - ) - { - // - foreach (var prv in config.DefaultValues) - { - // - // Detect Parameter ... - var swaggerParam = operation.Parameters.FirstOrDefault(p => p.Name == prv.Key); - if (!swaggerParam.IsNull()) - { - swaggerParam.Schema.Default = new OpenApiString(prv.Value); - } - } - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\ObjectHelper.cs - -using System; -using System.Linq; -using System.Collections.Generic; - -namespace xCommons.Helpers { - public partial class ObjectHelper { - /// - /// Convert Enum Keys to Array - /// - /// - /// - public static Array GetKeys () { - // - ValidateEnumbType (); - var type = typeof (T); - - // - var result = Enum.GetNames (type); - - // - return result; - } - - /// - /// Convert EnumValues to Array - /// - /// - /// - public static Array GetValues () { - // - ValidateEnumbType (); - var type = typeof (T); - - // - var result = Enum.GetValues (type); - - // - return result; - } - - /// - /// Convert an Enum to IEnumerable of it's Childs - /// - /// - /// - public static IEnumerable ToEnumerableValues () { - // - ValidateEnumbType (); - var type = typeof (T); - - // - var result = GetValues () - .Cast (); - - // - return result; - } - - /// - /// Retrieve Keys of an Enumerable - /// - /// - /// - public static IEnumerable ToEnumerableKeys () { - // - ValidateEnumbType (); - var type = typeof (T); - - // - var result = GetKeys () - .Cast (); - - // - return result; - } - - public static IDictionary ToDictionary () { - // - ValidateEnumbType (); - - // - var result = new Dictionary (); - foreach (var name in Enum.GetNames (typeof (T))) { - result.Add (name, (int) Enum.Parse (typeof (T), name)); - } - - // - return result; - } - - private static void ValidateEnumbType () { - // - var type = typeof (T); - if (!type.IsEnum) { - throw new InvalidCastException (); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XDateHelper.cs - -using System; - -namespace xCommons.Helpers { - public partial class XDateHelper { - /// - /// retrieve utc now timestam unix like representation ... - /// - /// - public static long UtcNowTimespan () { - return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XFileHelper.cs - -using System; -using System.Linq; -using xCommons.Models; -using System.Reflection; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Attributes; -using System.Collections.Generic; - -namespace xCommons.Helpers -{ - /// - /// File Helper ... - /// - public static class XFileHelper - { - /// - /// Cache Data ... - /// - private static readonly Lazy> _cache = - new(Build, isThreadSafe: true); - - /// - /// Retrieve List ... - /// - /// - public static IReadOnlyList GetAll() => _cache.Value; - - /// - /// Normalize File Extension ... - /// - /// - /// - public static string NormalizeExtension(string extension) - { - // - var result = extension; - - // - if (result.IsNullOrEmpty()) - { - return result; - } - - // - result = result.Trim(); - if (result.IsNullOrEmpty()) - { - return result; - } - - // - if (result == ".") - { - // - result = string.Empty; - return result; - } - - // - result = result.StartsWith(".") - ? result.ToLowerInvariant() - : "." + result.ToLowerInvariant(); - - // - return result; - } - - /// - /// Check a File Extension is Supported or not ... - /// - /// - /// - public static bool IsSupported(string extension) - { - // - var info = GetByExtension(extension); - var result = !info.IsNull(); - - // - return result; - } - - /// - /// Detect File Info based On Extension ... - /// - /// - /// - public static XFileTypeInfo GetByExtension(string extension) - { - // - XFileTypeInfo result = null; - - // - // Validate ... - if (extension.IsNullOrEmpty()) - { - return result; - } - - // - var normalized = NormalizeExtension(extension); - - // - // Detect Item ... - result = GetAll() - .FirstOrDefault(x => - x.Extension.Equals( - normalized, - StringComparison.OrdinalIgnoreCase)); - - // - return result; - } - - /// - /// Detect File Info based on Mime Type ... - /// - /// - /// - public static XFileTypeInfo GetByMimeType(string mimeType) - { - // - XFileTypeInfo result = null; - - // - // Validate ... - if (mimeType.IsNullOrEmpty()) - { - return result; - } - - // - result = GetAll() - .FirstOrDefault(x => - x.MimeType.Equals( - mimeType.Trim(), - StringComparison.OrdinalIgnoreCase)); - - // - return result; - } - - /// - /// Detect File Info based on Enum Member Name ... - /// - /// - /// - public static XFileTypeInfo GetByName(string name) - { - // - XFileTypeInfo result = null; - - // - // Validate ... - if (name.IsNullOrEmpty()) - { - return result; - } - - // - result = GetAll() - .FirstOrDefault(x => - x.Name.Equals( - name.Trim(), - StringComparison.OrdinalIgnoreCase)); - - // - return result; - } - - /// - /// Detect File Info based on Enum Member Value ... - /// - /// - /// - public static XFileTypeInfo GetByValue(int value) - { - // - var result = GetAll() - .FirstOrDefault(x => x.Value == value); - - // - return result; - } - - /// - /// Try Get File Info By Extension ... - /// - /// - /// - /// - public static bool TryGetByExtension( - string extension, - out XFileTypeInfo result - ) - { - result = GetByExtension(extension); - return result != null; - } - - /// - /// Try Get File Info By Mime Type ... - /// - /// - /// - /// - public static bool TryGetByMimeType( - string mimeType, - out XFileTypeInfo result - ) - { - result = GetByMimeType(mimeType); - return result != null; - } - - /// - /// Get Mime Type based on Extension ... - /// - /// - /// - public static string GetMimeType(string extension) - { - // - var result = string.Empty; - var info = GetByExtension(extension); - if (!info.IsNull()) - { - result = info.MimeType; - } - - // - return result; - - } - - /// - /// Get Extension based on Mime Type ... - /// - /// - /// - public static string GetExtension(string mimeType) - { - // - var result = string.Empty; - var info = GetByMimeType(mimeType); - if (!info.IsNull()) - { - result = info.Extension; - } - - // - return result; - } - - /// - /// Get File Category based on Value ... - /// - /// - /// - public static XFileCategory? GetCategory(int value) - { - // - if (value >= 100 && value < 200) return XFileCategory.Document; - if (value >= 200 && value < 300) return XFileCategory.Archive; - if (value >= 300 && value < 400) return XFileCategory.Internal; - if (value >= 400 && value < 500) return XFileCategory.Video; - if (value >= 500 && value < 600) return XFileCategory.Audio; - if (value >= 600 && value < 700) return XFileCategory.Image; - - // - return null; - } - - /// - /// Get File Category based on Extension ... - /// - /// - /// - public static XFileCategory? GetCategory(string extension) - { - // - var info = GetByExtension(extension); - var result = !info.IsNull() - ? GetCategory(info.Value) - : null; - - // - return result; - } - - /// - /// Get all Specified Category File Type Info ... - /// - /// - /// - public static IReadOnlyList GetByCategory(XFileCategory category) - { - // - var min = (int)category; - var max = min + 100; - - // - var result = GetAll() - .Where(x => x.Value >= min && x.Value < max) - .ToList() - .AsReadOnly(); - - // - return result; - } - - /// - /// Get All Supported Extensions ... - /// - /// - public static IReadOnlyList GetExtensions() - { - // - var result = GetAll() - .Select(x => x.Extension) - .ToList() - .AsReadOnly(); - - // - return result; - } - - /// - /// Get All Supported Mime Types ... - /// - /// - public static IReadOnlyList GetMimeTypes() - { - // - var result = GetAll() - .Select(x => x.MimeType) - .Where(m => !string.IsNullOrWhiteSpace(m)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList() - .AsReadOnly(); - - // - return result; - } - - // - #region Private ... - /// - /// Build List ... - /// - /// - private static IReadOnlyList Build() - { - // - var extensions = ReadEnum(); - var mimeTypes = ReadEnum(); - - // - var list = new List(extensions.Count); - foreach (var ext in extensions.Values.OrderBy(e => e.Value)) - { - // - mimeTypes.TryGetValue(ext.Value, out var mime); - list.Add(new XFileTypeInfo - { - Name = ext.Name, - Value = ext.Value, - Extension = ext.StringValue, - MimeType = mime.StringValue ?? string.Empty - }); - } - - // - var result = list.AsReadOnly(); - return result; - } - - /// - /// Read Enum ... - /// - /// - /// - private static Dictionary ReadEnum() - where TEnum : struct, Enum - { - // - var map = new Dictionary(); - foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)) - { - // - var attr = field.GetCustomAttribute(); - if (attr == null) continue; - var value = Convert.ToInt32(field.GetValue(null)); - - // - map[value] = new EnumEntry - { - Value = value, - Name = field.Name, - StringValue = attr.StringValue - }; - } - - // - return map; - } - - /// - /// Enum Entries for Read ... - /// - private struct EnumEntry - { - public int Value { get; set; } - public string Name { get; set; } - public string StringValue { get; set; } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XGenericHelper.cs - -using System; -using System.Linq; -using System.Reflection; -using xCommons.Extensions; -using System.Collections.Generic; - -namespace xCommons.Helpers -{ - public static class XGenericHelper - { - /// - /// Invoke a Generic Method of Specified Type ... - /// - /// - /// - /// - /// - public static void InvokeGenericMethod( - this Type source, - string methodName, - Type runtimeType, - params object[] args - ) - { - // - source.InvokeGenericMethod( - args: args, - methodName: methodName, - runtimeType: runtimeType - ); - } - - /// - /// Invoke a Generic Method of Specified Type ... - /// - /// - /// - /// - /// - /// - /// - public static TResponse InvokeGenericMethod( - this Type source, - string methodName, - Type runtimeType, - params object[] args - ) - { - // - var overLoads = source.GetGenericMethodInfo( - methodName: methodName - ); - if (!overLoads.HasChild()) - { - return default; - } - - // - var method = overLoads.ElementAt(0); - MethodInfo genericMethod = method.MakeGenericMethod(runtimeType); - - // - var resultObj = genericMethod.Invoke(null, args); - var result = (TResponse)resultObj; - - // - return result; - } - - /// - /// Invoke a Generic Method of Specified Type ... - /// - /// - /// - /// - /// - public static void InvokeGenericMethod( - this Type source, - string methodName, - Type[] runtimeTypes, - params object[] args - ) - { - // - source.InvokeGenericMethod( - args: args, - methodName: methodName, - runtimeTypes: runtimeTypes - ); - } - - /// - /// Invoke a Generic Method of Specified Type ... - /// - /// - /// - /// - /// - /// - /// - public static TResponse InvokeGenericMethod( - this Type source, - string methodName, - Type[] runtimeTypes, - params object[] args - ) - { - // - var overLoads = source.GetGenericMethodInfo( - methodName: methodName - ); - if (!overLoads.HasChild()) - { - return default; - } - - // - // Detect a Method by Generic Types ... - // var method = overLoads.ElementAt(0); - var method = overLoads.First(m => m.GetGenericArguments().Length == runtimeTypes.Length); - MethodInfo genericMethod = method.MakeGenericMethod(runtimeTypes); - - // - var resultObj = genericMethod.Invoke(null, args); - var result = resultObj.ConvertTo(); - - // - return result; - } - - /// - /// Extract a Generic Method's Overloads ... - /// - /// - /// - /// - public static List GetGenericMethodInfo( - this Type source, - string methodName - ) - { - // - var methods = source - .GetMethods(); - - // - var result = methods - .Where(mi => - mi.Name == methodName && - mi.IsGenericMethodDefinition) - .ToList(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XMLToJSONHelper.cs - -using System; -using System.Xml; -using System.Text; -using System.Collections.Generic; - -namespace xCommons.Helpers { - public partial class XMLToJSONHelper { - // - #region Actions ... - public static string ToJSON (string xml) { - // - XmlDocument doc = new XmlDocument (); - doc.LoadXml (xml); - - // - return XmlToJSON (doc); - } - - public static string XmlToJSON (XmlDocument xmlDoc) { - // - StringBuilder sbJSON = new StringBuilder (); - - // - sbJSON.Append ("{ "); - XmlToJSONnode (sbJSON, xmlDoc.DocumentElement, true); - sbJSON.Append ("}"); - - // - return sbJSON.ToString (); - } - #endregion - - // - #region Private ... - // - private static void XmlToJSONnode (StringBuilder sbJSON, XmlElement node, bool showNodeName) { - // - if (showNodeName) { - sbJSON.Append ("\"" + SafeJSON (node.Name) + "\": "); - } - - // - sbJSON.Append ("{"); - - // - // Build a sorted list of key-value pairs - // where key is case-sensitive nodeName - // value is an ArrayList of string or XmlElement - // so that we know whether the nodeName is an array or not. - SortedList childNodeNames = new SortedList (); - - // - // Add in all node attributes - if (node.Attributes != null) - foreach (XmlAttribute attr in node.Attributes) - StoreChildNode (childNodeNames, attr.Name, attr.InnerText); - - // - // Add in all nodes - foreach (XmlNode cnode in node.ChildNodes) { - // - if (cnode is XmlText) { - StoreChildNode (childNodeNames, "value", cnode.InnerText); - } else if (cnode is XmlElement) { - StoreChildNode (childNodeNames, cnode.Name, cnode); - } - } - - // - // Now output all stored info - foreach (string childname in childNodeNames.Keys) { - // - List alChild = (List) childNodeNames[childname]; - if (alChild.Count == 1) { - OutputNode (childname, alChild[0], sbJSON, true); - } else { - // - sbJSON.Append (" \"" + SafeJSON (childname) + "\": [ "); - - // - foreach (object Child in alChild) { - OutputNode (childname, Child, sbJSON, false); - } - - // - sbJSON.Remove (sbJSON.Length - 2, 2); - sbJSON.Append (" ], "); - } - } - - // - sbJSON.Remove (sbJSON.Length - 2, 2); - sbJSON.Append (" }"); - } - - // - // StoreChildNode: Store data associated with each nodeName - // so that we know whether the nodeName is an array or not. - private static void StoreChildNode (SortedList childNodeNames, string nodeName, object nodeValue) { - // - // Pre-process contraction of XmlElement-s - if (nodeValue is XmlElement) { - // - // Convert into "aa":null - // xx into "aa":"xx" - XmlNode cnode = (XmlNode) nodeValue; - if (cnode.Attributes.Count == 0) { - // - XmlNodeList children = cnode.ChildNodes; - if (children.Count == 0) { - nodeValue = null; - } else if (children.Count == 1 && (children[0] is XmlText)) { - nodeValue = ((XmlText) (children[0])).InnerText; - } - } - } - - // - // Add nodeValue to ArrayList associated with each nodeName - // If nodeName doesn't exist then add it - List ValuesAL; - - // - if (childNodeNames.ContainsKey (nodeName)) { - ValuesAL = (List) childNodeNames[nodeName]; - } else { - // - ValuesAL = new List (); - childNodeNames[nodeName] = ValuesAL; - } - - // - ValuesAL.Add (nodeValue); - } - - // - private static void OutputNode (string childname, object alChild, StringBuilder sbJSON, bool showNodeName) { - if (alChild == null) { - if (showNodeName) - sbJSON.Append ("\"" + SafeJSON (childname) + "\": "); - sbJSON.Append ("null"); - } else if (alChild is string) { - if (showNodeName) - sbJSON.Append ("\"" + SafeJSON (childname) + "\": "); - string sChild = (string) alChild; - sChild = sChild.Trim (); - sbJSON.Append ("\"" + SafeJSON (sChild) + "\""); - } else - XmlToJSONnode (sbJSON, (XmlElement) alChild, showNodeName); - sbJSON.Append (", "); - } - - // - // Make a string safe for JSON - private static string SafeJSON (string sIn) { - // - StringBuilder sbOut = new StringBuilder (sIn.Length); - foreach (char ch in sIn) { - // - if (Char.IsControl (ch) || ch == '\'') { - // - int ich = (int) ch; - sbOut.Append (@"\u" + ich.ToString ("x4")); - continue; - } else if (ch == '\"' || ch == '\\' || ch == '/') { - sbOut.Append ('\\'); - } - - // - sbOut.Append (ch); - } - - // - return sbOut.ToString (); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XNetworkHelper.cs - -using System.Net; -using System.Linq; -using xCommons.Models; -using System.Net.Sockets; -using System.Collections.Generic; -using System.Net.NetworkInformation; - -namespace xCommons.Helpers { - public static class XNetworkHelper { - /// - /// Retrieve Application Host's Machin IP Addresses ... - /// - /// string - public static string GetIp () { - // - var name = Dns.GetHostName (); // get container id - var result = Dns.GetHostEntry (name) - .AddressList - .FirstOrDefault ( - x => x.AddressFamily == AddressFamily.InterNetwork - ) - .MapToIPv4 () - .ToString (); - - // - return result; - } - - /// - /// Retrieve All Available IP's in Application Host's Machin ... - /// - /// a Collection of XNetworkInfo class instances - public static IEnumerable GetNetworkInfos () { - // - var result = System.Net.NetworkInformation.NetworkInterface - .GetAllNetworkInterfaces () - .Where ( - ni => - !ni.IsReceiveOnly && - ni.OperationalStatus == OperationalStatus.Up && - ni.NetworkInterfaceType != NetworkInterfaceType.Loopback - ) - .SelectMany (ni => - ni - .GetIPProperties () - .GatewayAddresses - .Select (ga => - new { - Name = ni.Name, - Description = ni.Description, - Gateway = ga.Address - .MapToIPv4 () - .ToString (), - NI = ni - } - ) - ) - .SelectMany (data => - data.NI - .GetIPProperties () - .UnicastAddresses - .Select (ip => - new XNetworkInfo { - Name = data.Name, - Gateway = data.Gateway, - Description = data.Description, - NetworkInterface = data.NI, - IP = ip.Address - .MapToIPv4 () - .ToString () - } - ) - ); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XOsHelper.cs - -using System; -using System.Diagnostics; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xExceptions.Attributes; -using System.Runtime.InteropServices; - -namespace xCommons.Helpers -{ - /// - /// Several OS Type ... - /// - public enum XOSType - { - [StringValue("Unknown")] - XUnknown, - - [StringValue("Mac")] - XMacOs, - - [StringValue("Linux")] - XLinux, - - [StringValue("Windows")] - XWindows, - - [StringValue("FreeBSD")] - XFreeBSD, - } - - /// - /// OS Command Execution Result ... - /// - public class XOSCMDResult - { - /// - /// Execution Result ... - /// - /// - public string Result { get; set; } - - /// - /// Execution Error ... - /// - /// - public string Error { get; set; } - } - - /// - /// a Helper Class which Provides OS Command Executions ... - /// - public static partial class XOsHelper - { - /// - /// Retrieve OS Type ... - /// - /// - public static XOSType GetOSType() - { - // - XOSType result = XOSType.XUnknown; - - // - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - result = XOSType.XMacOs; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - result = XOSType.XLinux; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - result = XOSType.XWindows; - } - // else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) - // { - // result = XOSType.XFreeBSD; - // } - - // - return result; - } - - /// - /// Retrieve OS Description ... - /// - /// - public static string GetOSDescription() - { - // - var result = RuntimeInformation.OSDescription; - return result; - } - - /// - /// Execute an Specified Command ... - /// - /// Specified Command - /// Command Arguments - /// - public static async Task Execute( - string cmd, - string args - ) - { - // - var result = new XOSCMDResult - { - Error = "Unknown", - }; - - // - try - { - // - // Validate CMD ... - var isValid = !cmd.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Validate OS Type ... - XOSType osType = GetOSType(); - isValid = osType != XOSType.XUnknown; - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - return await Task.Run(() => - { - // - ProcessStartInfo psi = new ProcessStartInfo(); - - // - psi.FileName = cmd; - psi.Arguments = args; - psi.UseShellExecute = false; - psi.RedirectStandardError = true; - psi.RedirectStandardOutput = true; - - // - Process process = Process.Start(psi); - - // - // Read the output - string output = process.StandardOutput.ReadToEnd(); - string error = process.StandardError.ReadToEnd(); - - // - process.WaitForExit(); - - // - result = new XOSCMDResult - { - Error = error, - Result = output, - }; - - // - return result; - }); - } - catch (Exception ex) - { - result.Error = ex.Message; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Helpers\XReflectionHelper.cs - -using System; -using System.Reflection; - -namespace xCommons.Helpers { - public static class XReflectionHelper { - public static object GetFieldValue (this object obj, string fieldName) { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - Type objType = obj.GetType (); - var fieldInfo = GetFieldInfo (objType, fieldName); - if (fieldInfo == null) - throw new ArgumentOutOfRangeException (fieldName, - $"Couldn't find field {fieldName} in type {objType.FullName}"); - return fieldInfo.GetValue (obj); - } - - public static void SetFieldValue (this object obj, string fieldName, object val) { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - Type objType = obj.GetType (); - var fieldInfo = GetFieldInfo (objType, fieldName); - if (fieldInfo == null) - throw new ArgumentOutOfRangeException (fieldName, - $"Couldn't find field {fieldName} in type {objType.FullName}"); - fieldInfo.SetValue (obj, val); - } - - private static FieldInfo GetFieldInfo (Type type, string fieldName) { - FieldInfo fieldInfo = null; - do { - fieldInfo = type.GetField (fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - type = type.BaseType; - } while (fieldInfo == null && type != null); - - return fieldInfo; - } - - public static object GetPropertyValue (this object obj, string propertyName) { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - Type objType = obj.GetType (); - var propertyInfo = GetPropertyInfo (objType, propertyName); - if (propertyInfo == null) - throw new ArgumentOutOfRangeException (propertyName, - $"Couldn't find property {propertyName} in type {objType.FullName}"); - return propertyInfo.GetValue (obj, null); - } - - public static void SetPropertyValue (this object obj, string propertyName, object val) { - if (obj == null) - throw new ArgumentNullException (nameof (obj)); - Type objType = obj.GetType (); - var propertyInfo = GetPropertyInfo (objType, propertyName); - if (propertyInfo == null) - throw new ArgumentOutOfRangeException (propertyName, - $"Couldn't find property {propertyName} in type {objType.FullName}"); - propertyInfo.SetValue (obj, val, null); - } - - private static PropertyInfo GetPropertyInfo (Type type, string propertyName) { - PropertyInfo propertyInfo = null; - do { - propertyInfo = type.GetProperty (propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - type = type.BaseType; - } while (propertyInfo == null && type != null); - - return propertyInfo; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXCipher.cs - -namespace xCommons.Interfaces -{ - public interface IXCipher - { - string Encrypt(string plainText); - string Decrypt(string cipherText); - string EncryptFromBytes(byte[] textBytes); - string DecryptFromBytes(byte[] cipherBytes); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXFileTypeDetector.cs - -using System.IO; -using xCommons.Models; -using System.Threading; -using xCommons.Constants; -using System.Threading.Tasks; - -namespace xCommons.Interfaces -{ - public interface IXFileTypeDetector - { - /// - /// Detect MIME Type based on File Name ... - /// - /// - /// - string DetectFromExtension(string fileName); - - /// - /// Detect XFileExtensions based on File Name ... - /// - /// - /// - XFileExtensions? DetectExtension(string fileName); - - /// - /// Detect Type based on File's Magic Byte ... - /// - /// - /// - /// - Task DetectFromMagicBytesAsync( - Stream stream, - CancellationToken cancellationToken = default - ); - - /// - /// Complexity Detect Type ... - /// - /// - /// - /// - /// - /// - Task DetectAsync( - string fileName, - string providedMimeType, - Stream stream, - CancellationToken cancellationToken = default - ); - - /// - /// Check a File Extension is Known or not ... - /// - /// - /// - bool IsKnownExtension(string fileName); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Interfaces\IXRateLimitProvider.cs - -using xCommons.Models; -using xCommons.Configurations; - -namespace xCommons.Interfaces -{ - public interface IXRateLimitProvider - { - bool IsEnabled { get; } - - XRateLimitResult TryConsume( - string key, - int limit, - int periodSeconds - ); - - XRateLimitResult TryConsume( - string key, - XRateLimitRule rule - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Middlewares\XRateLimitMiddleware.cs - -using System.Net; -using xCommons.Models; -using xCommons.Constants; -using xCommons.Attributes; -using xCommons.Extensions; -using xCommons.Interfaces; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; - -namespace xCommons.Middlewares -{ - public class XRateLimitMiddleware - { - // - private readonly RequestDelegate next; - private readonly IXRateLimitProvider provider; - private readonly XRateLimitConfiguration configuration; - - public XRateLimitMiddleware( - RequestDelegate next, - IXRateLimitProvider provider, - XRateLimitConfiguration configuration - ) - { - // - this.next = next; - this.provider = provider; - this.configuration = configuration; - } - - public async Task InvokeAsync(HttpContext context) - { - // - if (!provider.IsEnabled) - { - await next(context); - return; - } - - // - var endpoint = context.Features.Get()?.Endpoint; - if (!endpoint.IsNull() && - !endpoint.Metadata - .GetMetadata() - .IsNull() - ) - { - // - await next(context); - return; - } - - // - var rule = configuration.GetMatchingRule(context.Request.Path); - if (rule.IsNull()) - { - await next(context); - return; - } - - // - var key = context.GetXRateLimitKey(rule.KeyMode); - var result = provider.TryConsume(key, rule); - - // - WriteHeaders(context, result); - - // - if (!result.IsAllowed) - { - // - await context.WriteResponseAsJsonAsync( - status: (HttpStatusCode)configuration.StatusCode, - data: new - { - message = "Too many requests. Please try again later.", - retryAfter = result.RetryAfterSeconds, - resetOn = result.ResetOn - } - ); - return; - } - - // - await next(context); - } - - private static void WriteHeaders( - HttpContext context, - XRateLimitResult result - ) - { - // - context.Response.Headers[XRateLimitConstants.LimitHeader] = - result.Limit.ToString(); - - // - context.Response.Headers[XRateLimitConstants.RemainingHeader] = - result.Remaining.ToString(); - - // - context.Response.Headers[XRateLimitConstants.ResetHeader] = - result.ResetOn.ToUnixTimeSeconds().ToString(); - - // - if (!result.IsAllowed) - { - context.Response.Headers[XRateLimitConstants.RetryAfterHeader] = - result.RetryAfterSeconds.ToString(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XCertificate.cs - -namespace xCommons.Models { - public partial class XCertificate { - public string Path { get; set; } - public string Secret { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XFileTypeDetectionResult.cs - -using xCommons.Constants; - -namespace xCommons.Models -{ - public class XFileTypeDetectionResult - { - /// - /// File Mime Type ... - /// - public string MimeType { get; set; } - - /// - /// File Extension ... - /// - public string Extension { get; set; } - - /// - /// Type Detection Source ... - /// - public XFileTypeDetectionSource Source { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XFileTypeInfo.cs - -namespace xCommons.Models -{ - public class XFileTypeInfo - { - /// - /// Enum Value ... - /// - public int Value { get; set; } - - /// - /// Enum Item Name as String ... - /// - public string Name { get; set; } = string.Empty; - - /// - /// Extension as String ... - /// - public string Extension { get; set; } = string.Empty; - - /// - /// Mime Type as String ... - /// - public string MimeType { get; set; } = string.Empty; - - /// - /// Override To String ... - /// - /// - public override string ToString() - { - // - var result = $"{Name} ({Extension}) -> {MimeType} [{Value}]"; - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XLoggerModel.cs - -using System; -using Microsoft.AspNetCore.Http; - -namespace xCommons.Models { - public class XLoggerModel { - public string Host { get; set; } - public string Path { get; set; } - public string Schema { get; set; } - public string Method { get; set; } - public string UserID { get; set; } - public string Request { get; set; } - public int StatusCode { get; set; } - public bool IsSucceed { get; set; } - public string Response { get; set; } - public string QueryString { get; set; } - public DateTime RequestedOn { get; set; } - public DateTime RespondedOn { get; set; } - public IHeaderDictionary Headers { get; set; } - public Exception Exception { get; set; } = null; - public XLoggerHttpConnection Connection { get; set; } - } - - public class XLoggerHttpConnection { - public string Id { get; set; } - public string RemoteIpAddress { get; set; } - public string RemotePort { get; set; } - public string LocalIpAddress { get; set; } - public string LocalPort { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XNetworkInfo.cs - -using System; -using System.Linq; -using System.Threading.Tasks; -using System.Collections.Generic; -using System.Net.NetworkInformation; - -namespace xCommons.Models { - public class XNetworkInfo { - /// - /// Network Name ... - /// - /// - public string Name { get; set; } - - /// - /// Network Description ... - /// - /// - public string Description { get; set; } - - /// - /// IP Address which Exists on Current Network ... - /// - /// - public string IP { get; set; } - - /// - /// Current Networks Gateway Address ... - /// - /// - public string Gateway { get; set; } - - /// - /// Network Interface Object ... - /// - /// - public NetworkInterface NetworkInterface { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XRateLimitCounter.cs - -using System; - -namespace xCommons.Models -{ - public class XRateLimitCounter - { - public int Count { get; set; } - public int Limit { get; set; } - public DateTimeOffset ResetOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XRateLimitResult.cs - -using System; - -namespace xCommons.Models -{ - public class XRateLimitResult - { - public int Limit { get; set; } - public string Key { get; set; } - public int Remaining { get; set; } - public bool IsAllowed { get; set; } - public int RetryAfterSeconds { get; set; } - public DateTimeOffset ResetOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Models\XServiceDescriptor.cs - -using System; - -namespace xCommons.Models -{ - public class XServiceDescriptor - { - public Type Service { get; set; } - public Type Implementation { get; set; } - } - - public class XServiceDescriptor : XServiceDescriptor - { - public XServiceDescriptor() : base() - { - Service = typeof(TService); - Implementation = typeof(TImplmentation); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XBackgroundService.cs - -using System; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace xCommons.Providers -{ - /// - /// Default Background Service ... - /// - public abstract class XBackgroundService : BackgroundService - { - // - protected readonly IServiceProvider serviceProvider; - protected readonly ILogger logger; - - protected XBackgroundService( - IServiceProvider serviceProvider, - ILogger logger - ) - { - // - this.logger = logger; - this.serviceProvider = serviceProvider; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XCipher.cs - -using System; -using System.IO; -using System.Text; -using xCommons.Extensions; -using xCommons.Interfaces; -using System.Security.Cryptography; - -namespace xCommons.Providers -{ - public class XCipher : IXCipher - { - // - #region Props ... - private readonly string secretKey; - private readonly byte[] iv; - private readonly byte[] key; - private readonly XValidationProvider validationProvider; - #endregion - - // - #region Constructor ... - public XCipher( - string cipherKey, - XValidationProvider validationProvider - ) - { - // - this.secretKey = cipherKey.ToMd5String(); - this.validationProvider = validationProvider; - - // - var ivBytes = new byte[16]; - var keyBytes = new byte[32]; - var secretBytes = Encoding.UTF8.GetBytes(this.secretKey); - - // - Array.Copy( - secretBytes, - ivBytes, - secretBytes.Length < ivBytes.Length ? - secretBytes.Length : - ivBytes.Length - ); - this.iv = ivBytes; - - // - Array.Copy( - secretBytes, - keyBytes, - secretBytes.Length < keyBytes.Length ? - secretBytes.Length : - keyBytes.Length - ); - this.key = keyBytes; - - // Encoding.UTF8.GetBytes (this.secretKey); - } - #endregion - - // - #region Actions ... - public string Encrypt(string plainText) - { - // - validationProvider.NotEmpty(plainText); - - // - var textBytes = Encoding.UTF8.GetBytes(plainText); - var result = EncryptFromBytes(textBytes); - - // - return result; - } - - public string Decrypt(string cipherText) - { - // - validationProvider.NotEmpty(cipherText); - - // - var cipherBytes = Convert.FromBase64String(cipherText); - var result = DecryptFromBytes(cipherBytes); - - // - return result; - } - - public string EncryptFromBytes(byte[] textBytes) - { - // - // Validate Args ... - validationProvider.NotNull(textBytes); - - // Declare the string used to hold - // the decrypted text. - byte[] encryptedBytes = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged()) - { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // - using (var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)) - { - encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length); - } - } - - // - return Convert.ToBase64String(encryptedBytes); - } - - public string DecryptFromBytes(byte[] cipherBytes) - { - // - // Validate Args ... - validationProvider.NotNull(cipherBytes); - - // Declare the string used to hold - // the decrypted text. - string plaintext = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged()) - { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // Create a decrytor to perform the stream transform. - var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); - - // Create the streams used for decryption. - using (var msDecrypt = new MemoryStream(cipherBytes)) - { - using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) - { - using (var srDecrypt = new StreamReader(csDecrypt)) - { - // Read the decrypted bytes from the decrypting stream - // and place them in a string. - plaintext = srDecrypt.ReadToEnd(); - } - } - } - } - - // - return plaintext; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XFileTypeDetector.cs - -using System; -using System.IO; -using xCommons.Models; -using xCommons.Helpers; -using System.Threading; -using xCommons.Constants; -using xCommons.Interfaces; -using xCommons.Extensions; -using System.Threading.Tasks; -using xCommons.Configurations; -using System.Collections.Generic; - -namespace xCommons.Providers -{ - public class XFileTypeDetector : IXFileTypeDetector - { - private readonly XFileTypeDetectorConfiguration configuration; - - private readonly Dictionary MagicSignatures = - new(StringComparer.OrdinalIgnoreCase) - { - ["image/png"] = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, - ["image/jpeg"] = new byte[] { 0xFF, 0xD8, 0xFF }, - ["image/gif"] = new byte[] { 0x47, 0x49, 0x46, 0x38 }, - ["image/bmp"] = new byte[] { 0x42, 0x4D }, - ["image/x-icon"] = new byte[] { 0x00, 0x00, 0x01, 0x00 }, - ["application/pdf"] = new byte[] { 0x25, 0x50, 0x44, 0x46 }, - ["application/zip"] = new byte[] { 0x50, 0x4B, 0x03, 0x04 }, - ["application/x-rar-compressed"] = new byte[] { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07 }, - ["application/x-7z-compressed"] = new byte[] { 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C }, - ["audio/mpeg"] = new byte[] { 0xFF, 0xFB }, - ["audio/ogg"] = new byte[] { 0x4F, 0x67, 0x67, 0x53 }, - ["font/ttf"] = new byte[] { 0x00, 0x01, 0x00, 0x00 } - }; - - public XFileTypeDetector( - XFileTypeDetectorConfiguration configuration - ) - { - this.configuration = configuration; - } - - /// - /// Detect Type based on File Name ... - /// - /// - /// - public string DetectFromExtension(string fileName) - { - // - var result = string.Empty; - - // - // Validate ... - if (fileName.IsNullOrEmpty()) - { - return result; - } - - // - var extension = Path.GetExtension(fileName); - if (extension.IsNullOrEmpty()) - { - return result; - } - - // - result = XFileHelper.GetMimeType(extension); - - // - return result; - } - - /// - /// Detect XFileExtensions based on File Name ... - /// - /// - /// - public XFileExtensions? DetectExtension(string fileName) - { - // - XFileExtensions? result = null; - if (fileName.IsNullOrEmpty()) - { - return result; - } - - // - var extension = Path.GetExtension(fileName); - var info = XFileHelper.GetByExtension(extension); - if (info.IsNull()) - { - return result; - } - - // - result = (XFileExtensions)info.Value; - - // - return result; - } - - /// - /// Check a File Extension is Known or not ... - /// - /// - /// - public bool IsKnownExtension(string fileName) - { - // - var result = !fileName.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - var extension = Path.GetExtension(fileName); - result = XFileHelper.IsSupported(extension); - - // - return result; - } - - /// - /// Detect Type based on File's Magic Byte ... - /// - /// - /// - /// - public async Task DetectFromMagicBytesAsync( - Stream stream, - CancellationToken cancellationToken = default - ) - { - // - var result = string.Empty; - - // - // Validate ... - if (stream == null || !stream.CanRead) - { - return result; - } - - // - var originalPosition = stream.CanSeek ? stream.Position : 0L; - try - { - // - var header = new byte[configuration.HeaderSize]; - var read = await ReadHeaderAsync(stream, header, cancellationToken); - if (read < 2) - { - return result; - } - - // - foreach (var signature in MagicSignatures) - { - // - if (MatchesSignature(header, read, signature.Value)) - { - // - result = signature.Key; - return result; - } - } - - // - return result; - } - finally - { - // - if (stream.CanSeek) - { - stream.Position = originalPosition; - } - } - } - - /// - /// Complexity Detect Type ... - /// - /// - /// - /// - /// - /// - public async Task DetectAsync( - string fileName, - string providedMimeType, - Stream stream, - CancellationToken cancellationToken = default - ) - { - // - var result = new XFileTypeDetectionResult - { - Source = XFileTypeDetectionSource.None - }; - - // - if (configuration.PreferMagicBytes) - { - // - var magicMime = await DetectFromMagicBytesAsync(stream, cancellationToken); - if (!magicMime.IsNullOrEmpty()) - { - // - result.MimeType = magicMime; - result.Extension = XFileHelper.GetExtension(magicMime); - result.Source = XFileTypeDetectionSource.MagicBytes; - - // - return result; - } - } - - // - var extensionMime = DetectFromExtension(fileName); - if (!extensionMime.IsNullOrEmpty()) - { - // - result.MimeType = extensionMime; - result.Extension = Path.GetExtension(fileName)?.ToLowerInvariant(); - result.Source = XFileTypeDetectionSource.Extension; - - // - return result; - } - - // - if (!string.IsNullOrWhiteSpace(providedMimeType)) - { - // - var info = XFileHelper.GetByMimeType(providedMimeType); - if (info != null) - { - // - result.MimeType = info.MimeType; - result.Extension = info.Extension; - result.Source = XFileTypeDetectionSource.ProvidedMime; - } - } - - // - return result; - } - - // - #region Private ... - private static async Task ReadHeaderAsync( - Stream stream, byte[] buffer, - CancellationToken ct = default - ) - { - // - var totalRead = 0; - while (totalRead < buffer.Length) - { - // - var read = await stream.ReadAsync( - buffer, totalRead, buffer.Length - totalRead, ct); - - if (read == 0) break; - totalRead += read; - } - - // - return totalRead; - } - - private static bool MatchesSignature(byte[] header, int length, byte[] signature) - { - // - if (length < signature.Length) return false; - for (var i = 0; i < signature.Length; i++) - { - if (header[i] != signature[i]) return false; - } - - // - return true; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XRateLimitProvider.cs - -using System; -using xCommons.Models; -using xCommons.Constants; -using xCommons.Extensions; -using xCommons.Interfaces; -using xExceptions.Constants; -using xCommons.Configurations; -using System.Collections.Concurrent; -using Microsoft.Extensions.Caching.Memory; - -namespace xCommons.Providers -{ - public class XRateLimitProvider : IXRateLimitProvider - { - // - private readonly IMemoryCache cache; - private readonly XRateLimitConfiguration configuration; - private readonly ConcurrentDictionary syncRoots = new(); - - public XRateLimitProvider( - IMemoryCache cache, - XRateLimitConfiguration configuration - ) - { - // - this.cache = cache; - this.configuration = configuration; - } - - public bool IsEnabled - { - get - { - return !configuration.IsNull() && configuration.Enabled; - } - } - - public XRateLimitResult TryConsume( - string key, - XRateLimitRule rule - ) - { - // - if (rule.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - return TryConsume( - key: key, - limit: rule.Limit, - periodSeconds: rule.PeriodSeconds - ); - } - - public XRateLimitResult TryConsume( - string key, - int limit, - int periodSeconds - ) - { - // - if (limit <= 0 || periodSeconds <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - var normalizedKey = BuildCacheKey(key); - var now = DateTimeOffset.UtcNow; - - // - if (!IsEnabled) - { - // - return new XRateLimitResult - { - Limit = limit, - IsAllowed = true, - Remaining = limit, - Key = normalizedKey, - RetryAfterSeconds = 0, - ResetOn = now.AddSeconds(periodSeconds) - }; - } - - // - var syncRoot = syncRoots.GetOrAdd( - key: normalizedKey, - valueFactory: _ => new object() - ); - - // - lock (syncRoot) - { - // - var counter = cache.Get(normalizedKey); - if (counter.IsNull() || counter.ResetOn <= now) - { - // - counter = new XRateLimitCounter - { - Count = 0, - Limit = limit, - ResetOn = now.AddSeconds(periodSeconds) - }; - } - - // - counter.Count++; - counter.Limit = limit; - - // - var remaining = Math.Max(0, limit - counter.Count); - var isAllowed = counter.Count <= limit; - var retryAfter = isAllowed - ? 0 - : (int)Math.Ceiling((counter.ResetOn - now).TotalSeconds); - - // - var options = new MemoryCacheEntryOptions - { - AbsoluteExpiration = counter.ResetOn - }; - - // - options.RegisterPostEvictionCallback((cacheKey, value, reason, state) => - { - syncRoots.TryRemove(cacheKey.ToString(), out _); - }); - - // - cache.Set(normalizedKey, counter, options); - - // - return new XRateLimitResult - { - Limit = limit, - Key = normalizedKey, - IsAllowed = isAllowed, - Remaining = remaining, - ResetOn = counter.ResetOn, - RetryAfterSeconds = retryAfter, - }; - } - } - - private static string BuildCacheKey(string key) - { - // - var normalized = key.IsNullOrEmpty() - ? "anonymous" - : key.ToNormalString(); - - // - return string.Format( - "{0}:{1}", - XRateLimitConstants.CacheKeyPrefix, - normalized - ); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XResumableBackgroundService.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; - -namespace xCommons.Providers -{ - /// - /// Resumable Background Task ... - /// - public abstract class XResumableBackgroundService : XBackgroundService - { - /// - /// Check is Paused ... - /// - protected bool paused = false; - - protected XResumableBackgroundService( - IServiceProvider serviceProvider, - ILogger logger - ) : base( - logger: logger, - serviceProvider: serviceProvider - ) - { } - - protected override async Task ExecuteAsync( - CancellationToken stoppingToken = default - ) - { - // - if (paused) - { - return; - } - - // - await DoWorkAsync( - payload: null, - cancellationToken: stoppingToken - ); - } - - /// - /// do all required works here ... - /// - /// - /// - /// - public abstract Task DoWorkAsync( - object payload = null, - CancellationToken cancellationToken = default - ); - - /// - /// Pause Consuming ... - /// - /// - public bool Pause() - { - // - var result = !paused; - if (!result) - { - return result; - } - - // - paused = true; - result = paused; - return result; - } - - /// - /// Resume Consuming ... - /// - /// - public bool Resume() - { - // - var result = paused; - if (!result) - { - return result; - } - - // - paused = false; - result = !paused; - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XTimeBasedBackgroundService.cs - -using System; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; - -namespace xCommons.Providers -{ - /// - /// Do Background Jobs based on Time Intervals ... - /// - public abstract class XTimeBasedBackgroundService : XBackgroundService - { - // - private bool isWorking = false; - private readonly TimeSpan restartInterval; - private readonly SemaphoreSlim mlock = new(1, 1); - public DateTime? LastRunTime { get; private set; } - private CancellationTokenSource cancellationTokenSource; - - protected XTimeBasedBackgroundService( - IServiceProvider serviceProvider, - ILogger logger, - int intervalInMinutes = 10 - ) : base( - logger: logger, - serviceProvider: serviceProvider - ) - { - // - // Validate Interval ... - if (intervalInMinutes <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - restartInterval = TimeSpan.FromMinutes(intervalInMinutes); - } - - /// - /// Override base action to Implement timing ... - /// - /// - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - // - while (!stoppingToken.IsCancellationRequested) - { - try - { - if (!isWorking) - { - // - // Enable Working ... - await mlock.WaitAsync(stoppingToken); - try - { - isWorking = true; - } - finally - { - mlock.Release(); - } - - // - // Start a new work task ... - cancellationTokenSource = CancellationTokenSource - .CreateLinkedTokenSource(stoppingToken); - - // - // Execute the work ... - await ExecuteWorkAsync(cancellationTokenSource.Token); - - // - // Disable Working ... - await mlock.WaitAsync(stoppingToken); - try - { - isWorking = false; - } - finally - { - mlock.Release(); - } - - // - // Wait for the restart interval ... - await Task.Delay(restartInterval, stoppingToken); - } - else - { - // - // Prevent tight error loops ... - await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); - } - } - catch (OperationCanceledException) - { - // - // Disable Working ... - await mlock.WaitAsync(stoppingToken); - try - { - isWorking = false; - } - finally - { - mlock.Release(); - } - break; - } - catch (Exception) - { - // - // Disable Working ... - await mlock.WaitAsync(stoppingToken); - try - { - isWorking = false; - } - finally - { - mlock.Release(); - } - - // - // Prevent tight error loops ... - await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); - } - } - } - - /// - /// Override Stop Background Worker ... - /// - /// - /// - public override async Task StopAsync(CancellationToken cancellationToken) - { - // - // Cancel the current work session - cancellationTokenSource.Cancel(); - await base.StopAsync(cancellationToken); - } - - /// - /// Dispose all Objects ... - /// - public override void Dispose() - { - mlock.Dispose(); - cancellationTokenSource.Dispose(); - GC.SuppressFinalize(this); - base.Dispose(); - } - - /// - /// do all required works here ... - /// - /// - /// - public abstract Task DoWorkAsync( - CancellationToken cancellationToken = default - ); - - /// - /// Refresh Worker ... - /// - /// - /// - public async Task Refresh( - CancellationToken cancellationToken = default - ) - { - // - // Cancel current work if running - cancellationTokenSource.Cancel(); - - // - // Wait a moment for cancellation - await Task.Delay(100, cancellationToken); - - // - // Start new work immediately - cancellationTokenSource = CancellationTokenSource - .CreateLinkedTokenSource(cancellationToken); - await ExecuteWorkAsync(cancellationTokenSource.Token); - } - - // - #region Private ... - private async Task ExecuteWorkAsync(CancellationToken cancellationToken) - { - // - LastRunTime = DateTime.UtcNow; - try - { - await DoWorkAsync(cancellationToken); - } - catch (OperationCanceledException) - { - } - catch (Exception) - { - } - finally - { - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xCommons\Providers\XValidationProvider.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xCommons.Providers { - public partial class XValidationProvider { - private ICollection validationGroup; - - // - #region Simple Validators ... - /// - /// given objects must not null - /// - /// - public void NotNull ( - params object[] values) { - // - foreach (var o in values) { - // - if (o == null) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// given strings must not empty or null - /// - /// - public void NotEmpty ( - params string[] values) { - // - foreach (var s in values) { - // - if (s.IsNullOrEmpty ()) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a numeric value is bigger than 0 - /// - /// - public void NotZero ( - params int[] values) { - // - foreach (var s in values) { - // - if (s == 0) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a numeric value is bigger than 0 - /// - /// - public void NotZero ( - params long[] values) { - // - foreach (var s in values) { - // - if (s == 0) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a numeric value is bigger than 0 - /// - /// - public void NotZero ( - params decimal[] values) { - // - foreach (var s in values) { - // - if (s == 0) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a Value is a Valid Guid ... - /// - /// - public void IsGuid (params string[] values) { - // - foreach (var s in values) { - // - if (!s.IsGuid () || s.IsDefaultGuid ()) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a Value is a Valid Guid ... - /// - /// - public void IsGuid (params Guid[] values) { - // - foreach (var s in values) { - // - if (s.IsNull () || s.IsDefaultGuid ()) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// Check a Value is an MD5 ... - /// - /// - public void IsMD5 (params string[] values) { - // - foreach (var s in values) { - // - if (!s.IsMD5String ()) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// non zero childs - /// - /// - public void NotZeroChilds ( - params IEnumerable[] values) { - // - foreach (var s in values) { - // - if (s == null || - s.Count () == 0) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// non zero childs - /// - /// - public void NotZeroChilds ( - params ICollection[] values) { - // - foreach (var s in values) { - // - if (s == null || - s.Count == 0) { - XException.InvalidArgs.Throw (); - } - } - } - - /// - /// given string must be a valid URL ... - /// - /// - /// - public void Url ( - string url, - Exception exception = null - ) { - // - NotEmpty (url); - - // - if (exception == null) { - exception = XException.InavlidUrl.ToException (); - } - - // - if (!url.IsValidUrl ()) { - throw exception; - } - } - - /// - /// given string must be a valid Email Address ... - /// - /// - /// - public void EmailAddress ( - string emailAdress, - Exception exception = null - ) { - // - NotEmpty (emailAdress); - - // - if (exception == null) { - exception = XException.InvalidEmailAddress.ToException (); - } - - // - if (!emailAdress.IsValidEmail ()) { - throw exception; - } - } - - /// - /// given string must be a valid Mobile Number ... - /// - /// - /// - public void MobileNumber ( - string mobileNumber, - Exception exception = null - ) { - // - NotEmpty (mobileNumber); - - // - if (exception == null) { - exception = XException.InvalidMobileNumber.ToException (); - } - - // - if (!mobileNumber.IsValidMobileNumber ()) { - throw exception; - } - } - #endregion - - // - #region Group Validatos ... - public XValidationProvider GroupValidationBuilder () { - // - validationGroup = new List (); - - // - return this; - } - - public XValidationProvider AddNotEmpty (params string[] values) { - // - this.validationGroup.Add (() => - this.NotEmpty (values) - ); - - // - return this; - } - - public XValidationProvider AddNotNull (params object[] values) { - // - this.validationGroup.Add (() => - this.NotNull (values) - ); - - // - return this; - } - - public XValidationProvider AddNotZero (params int[] values) { - // - this.validationGroup.Add (() => - this.NotZero (values) - ); - - // - return this; - } - - public XValidationProvider AddNotZero (params long[] values) { - // - this.validationGroup.Add (() => - this.NotZero (values) - ); - - // - return this; - } - - public XValidationProvider AddNotZero (params decimal[] values) { - // - this.validationGroup.Add (() => - this.NotZero (values) - ); - - // - return this; - } - - public XValidationProvider AddIsGuid (params string[] values) { - // - this.validationGroup.Add (() => - this.IsGuid (values) - ); - - // - return this; - } - - public XValidationProvider AddIsGuid (params Guid[] values) { - // - this.validationGroup.Add (() => - this.IsGuid (values) - ); - - // - return this; - } - - public XValidationProvider AddIsMD5 (params string[] values) { - // - this.validationGroup.Add (() => - this.IsMD5 (values) - ); - - // - return this; - } - - public XValidationProvider AddNotZeroChilds (params IEnumerable[] values) { - // - this.validationGroup.Add (() => - this.NotZeroChilds (values) - ); - - // - return this; - } - - public XValidationProvider AddNotZeroChilds (params ICollection[] values) { - // - this.validationGroup.Add (() => - this.NotZeroChilds (values) - ); - - // - return this; - } - - public XValidationProvider AddEmailAddress ( - string emailAdress, - Exception exception = null) { - // - this.validationGroup.Add (() => - this.EmailAddress (emailAdress, exception) - ); - - // - return this; - } - - public XValidationProvider AddMobileNumber ( - string mobileNumber, - Exception exception = null) { - // - this.validationGroup.Add (() => - this.MobileNumber (mobileNumber, exception) - ); - - // - return this; - } - - public XValidationProvider AddUrl ( - string url, - Exception exception = null) { - // - this.validationGroup.Add (() => - this.Url (url, exception) - ); - - // - return this; - } - - public void ValidateGroup () { - // - // Run each Tasks ... - foreach (var action in validationGroup) { - action.Invoke (); - } - - // - // Clear Task List ... - validationGroup.Clear (); - } - - public async Task ValidateGroupAsync () { - // - // Run each Tasks ... - foreach (var action in validationGroup) { - await Task.Run (action); - } - - // - // Clear Task List ... - validationGroup.Clear (); - } - #endregion - - } -} diff --git a/Documents/GeneratedContext/xDashboard-xContentService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xContentService-20261109_152621.txt deleted file mode 100644 index 44ebe81..0000000 --- a/Documents/GeneratedContext/xDashboard-xContentService-20261109_152621.txt +++ /dev/null @@ -1,2675 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Configuration\Entities\XContentEntityConfiguration.cs - -using System; -using xDataService.Providers; -using xContentService.Constants; -using Microsoft.EntityFrameworkCore; -using xContentService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xContentService.Configuration.Entities -{ - public class XContentEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XContentServiceConstants.XContentTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Constants\XContentServiceConstants.cs - -using xContentService.Models.Entities; - -namespace xContentService.Constants -{ - public struct XContentServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XContentServiceDILogTag = "XContentService"; - - // - // Table Mapping Identifiers ... - public const string XContentTable = "Contents"; - - // - // GraphQL Collection Mappings ... - public const string XContentSingleName = "content"; - public const string XContentCollectionName = "contents"; - - // - // Hubs ... - public const string XContentDtoHub = "contentDto"; - public const string XContentEntityHub = "contentEntity"; - - // - // EF Repositories Helper Extensions ... - public const string GetXContentEFRepositoryDescriptor = "GetXContentEFRepositoryDescriptor"; - - // - // Custome Constants ... - public const string XAdminRole = "admin"; - - public const string XContentTagProvided = nameof(XContent); - - public const string XContentTitleIdentifier = "CntnT"; - public const string XContentDescriptionIdentifier = "CntnD"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Controllers\XContentRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xContentService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xContentService.Interfaces.Entities; - -namespace xContentService.Controllers -{ - public abstract class XContentRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XContentRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXContentRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Controllers\XContentRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xPushService.Interfaces; -using xCommons.Configurations; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xContentService.Models.Entities; -using xContentService.Providers.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xContentService.Interfaces.Entities; - -namespace xContentService.Controllers -{ - public abstract class XContentRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XContentRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXContentRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Controllers\XContentServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using xContentService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xContentService.Models.Entities; -using xContentService.Interfaces.Dtos; -using Microsoft.EntityFrameworkCore.Query; - -namespace xContentService.Controllers -{ - public abstract class XContentServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XContentServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXContentRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Controllers\XContentServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xContentService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; -using xContentService.Interfaces.Dtos; -using Microsoft.EntityFrameworkCore.Query; - -namespace xContentService.Controllers -{ - public abstract class XContentServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XContentServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXContentServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Controllers\XControllerProviderControllerBase.cs - -using System; -using System.Linq; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xTagService.Controllers; -using Microsoft.AspNetCore.Mvc; -using xContentService.Interfaces; -using xContentService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xContentService.Interfaces.Controllers; - -namespace xContentService.Controllers -{ - public abstract class XContentProviderControllerBase : XBaseProvidedHasTagControllerBase, IXContentProviderController - { - private readonly IXContentProvider provider; - - protected XContentProviderControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXContentProvider provider, - IXContentTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - tagProvided, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { - this.provider = provider; - } - - /// - /// Add an item ... - /// - /// - /// - /// - /// - [HttpPost("Add")] - public async Task> Add( - [FromBody] XContentDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotEmpty(item.Title) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Normalize Language ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - if (language.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - var result = await provider.Add( - item: item, - userInfo: userInfo, - language: language, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\DI\XDIHelperExtensions.cs - -using System; -using xPushService.DI; -using xDataService.DI; -using xDataService.Db; -using xCommons.Helpers; -using xDataService.Models; -using xCommons.Extensions; -using xPushService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xContentService.Helpers; -using xContentService.Constants; -using xContentService.Providers; -using xContentService.Interfaces; -using Microsoft.AspNetCore.Builder; -using xContentService.Providers.Dtos; -using xContentService.Interfaces.Dtos; -using xContentService.Providers.Entities; -using xContentService.Interfaces.Entities; -using xContentService.Providers.Enrichers; -using xContentService.Interfaces.Enrichers; -using Microsoft.Extensions.DependencyInjection; - -namespace xContentService.DI -{ - /// - /// Service Registration Extensions Classes ... - /// - public static partial class XDIHelperExtensions - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXContentService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddContentService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXContentService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddContentService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use xContentService Middleware ... - /// - /// - /// - public static void UseXContentService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XContent Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XContentServiceConstants.XContentDtoHub); - pushHelper.AddHub(XContentServiceConstants.XContentEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XContent Repository Descriptor ... - if (!descriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XContentServiceConstants.XContentServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddContentService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - descriptor = typeof(XContentServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XContentServiceConstants.GetXContentEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - descriptor = XContentServiceHelper.GetXContentMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - descriptor = XContentServiceHelper.GetXContentInMemoryRepositoryDescriptor(); - break; - } - - // - // Register XContent Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: descriptor - ); - - // - // Resource Providers ... - services.Add( - new ServiceDescriptor(typeof(IXContentTitleResourceProvider), typeof(XContentTitleResourceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXContentDescriptionResourceProvider), typeof(XContentDescriptionResourceProvider), lifeTime) - ); - - // - // Enrichers ... - services.Add( - new ServiceDescriptor(typeof(IXContentEnricher), typeof(XContentEnricher), lifeTime) - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXContentServiceProvider), typeof(XContentServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXContentRepositoryService), typeof(XContentRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXContentRepositoryProvider), typeof(XContentRepositoryProvider), lifeTime) - ); - - // - // Tags ... - services.Add( - new ServiceDescriptor(typeof(IXContentTagProvider), typeof(XContentTagProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXContentTagProvided), typeof(XContentTagProvided), lifeTime) - ); - - // - // Provider ... - services.Add( - new ServiceDescriptor(typeof(IXContentProvider), typeof(XContentProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Extensions\XModelExtensions.cs - -using xCommons.Extensions; -using xContentService.Models.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Extensions -{ - /// - /// All Service Model's Extensions ... - /// - public static class XModelExtensions - { - /// - /// Validate a Model ... - /// - /// - /// - public static bool IsValid(this XContent source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Title.IsNullOrEmpty() && - !source.OwnerId.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate a Model ... - /// - /// - /// - public static bool IsValid(this XContentDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Title.IsNullOrEmpty() && - !source.OwnerId.IsNullOrEmpty(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Helpers\XContentServiceHelper.cs - -using System; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xContentService.Models.Entities; -using xContentService.Providers.GraphQL; -using xContentService.Providers.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Helpers -{ - public static class XContentServiceHelper - { - // - #region XContent ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentEFRepository, - TContext - > GetXContentEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentEFRepository, - TContext, - IXContentSeeder, - TSeederImplementation - > GetXContentEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentEFRepository, - TContext, - IXContentSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentMongoRepository - > GetXContentMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentMongoRepository, - IXContentSeeder, - TSeederImplementation - > GetXContentMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentMongoRepository, - IXContentSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentInMemoryRepository - > GetXContentInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentInMemoryRepository, - IXContentSeeder, - TSeederImplementation - > GetXContentInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XContent, - Guid, - IXContentKeyGenerator, - XContentKeyGenerator, - IXContentRepositoryEvents, - XContentRepositoryEvents, - XContentGraphType, - GuidGraphType, - XContentGraphQuery, - IXContentGraphQLTypeHelper, - XContentGraphQLTypeHelper, - XContentGraphSchema, - IXContentRepository, - XContentInMemoryRepository, - IXContentSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\IXContentDescriptionResourceProvider.cs - -using xStringService.Interfaces; - -namespace xContentService.Interfaces -{ - public interface IXContentDescriptionResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\IXContentProvider.cs - -using System; -using System.Threading; -using xTagService.Interfaces; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces -{ - public interface IXContentProvider : IXBaseProvidedHasTag - { - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - /// - public Task Add( - XContentDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - string language = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\IXContentTagProvided.cs - -using System; -using xTagService.Interfaces; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces -{ - public interface IXContentTagProvided : IXTagProvided - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\IXContentTagProvider.cs - -using System; -using xTagService.Interfaces; - -namespace xContentService.Interfaces -{ - public interface IXContentTagProvider : IXBaseTagProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\IXContentTitleResourceProvider.cs - -using xStringService.Interfaces; - -namespace xContentService.Interfaces -{ - public interface IXContentTitleResourceProvider : IXItemResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Controllers\IXContentProviderController.cs - -using System; -using System.Threading; -using xTagService.Interfaces; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Controllers -{ - public interface IXContentProviderController : IXBaseProvidedHasTagController - { - /// - /// Add an item ... - /// - /// - /// - /// - /// - [HttpPost("Add")] - Task> Add( - [FromBody] XContentDto item, - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Dtos\IXContentDtoHub.cs - -using System; -using xPushService.Interfaces; -using xContentService.Models.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Dtos -{ - public interface IXContentDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Dtos\IXContentRepositoryService.cs - -using System; -using xDataService.Interfaces; -using xContentService.Models.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Dtos -{ - public interface IXContentRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Dtos\IXContentServiceProvider.cs - -using System; -using xPushService.Interfaces; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Dtos -{ - public interface IXContentServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Enrichers\IXContentEnricher.cs - -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; -using xContentService.Models.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Enrichers -{ - public interface IXContentEnricher - { - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XContent source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - Task Enrich( - XContentDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentEntityHub.cs - -using System; -using xPushService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentRepository.cs - -using System; -using xDataService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentRepositoryEvents.cs - -using xDataService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xContentService.Models.Entities; -using xContentService.Providers.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Interfaces\Entities\IXContentSeeder.cs - -using System; -using xDataService.Interfaces; -using xContentService.Models.Entities; - -namespace xContentService.Interfaces.Entities -{ - public interface IXContentSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Models\Dtos\XContentDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; - -namespace xContentService.Models.Dtos -{ - /// - /// Content Describe DTO ... - /// - public class XContentDto : XBaseGuidIDEntityDto - { - public string OwnerId { get; set; } - public virtual XPersonDto Owner { get; set; } - - public string Title { get; set; } - public virtual XResourceDto TitleResource { get; set; } - - public string Description { get; set; } - public virtual XResourceDto DescriptionResource { get; set; } - - public string[] Tags { get; set; } - - public DateTime CreatedOn { get; set; } - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Models\Entities\XContent.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xContentService.Models.Entities -{ - /// - /// Content Describe ... - /// - public class XContent : XBaseGuidIDEntity - { - /// - /// User Identifier ... - /// - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Title of Content ... - /// - [Required] - [StringLength(255)] - public string Title { get; set; } - - /// - /// Description of Content ... - /// - [StringLength(255)] - public string Description { get; set; } - - /// - /// Created Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Updated Time ... - /// - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentDescriptionResourceProvider.cs - -using xStringService.Providers; -using xContentService.Constants; -using xContentService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xContentService.Providers -{ - public class XContentDescriptionResourceProvider : XBaseItemResourceProvider, IXContentDescriptionResourceProvider - { - public XContentDescriptionResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XContentServiceConstants.XContentDescriptionIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xContentService.Models.Entities; -using xContentService.Configuration.Entities; - -namespace xContentService.Providers -{ - public class XContentEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XContentEntityRegisterar() - : base(nameof(XContentEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XContentEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xTagService.Providers; -using xExceptions.Constants; -using xIdentityModels.Models; -using System.Threading.Tasks; -using xPushService.Constants; -using System.Linq.Expressions; -using xCommons.Configurations; -using xContentService.Constants; -using xContentService.Interfaces; -using System.Collections.Generic; -using xContentService.Extensions; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Models.Entities; -using xContentService.Interfaces.Dtos; -using Microsoft.EntityFrameworkCore.Query; -using xContentService.Interfaces.Enrichers; - -namespace xContentService.Providers -{ - public class XContentProvider : XBaseProvidedHasTag, IXContentProvider - { - private readonly IXContentEnricher enricher; - private readonly XAppConfiguration configuration; - private readonly IXContentTagProvider tagProvider; - private readonly IXContentServiceProvider provider; - private readonly IXContentTitleResourceProvider titleResourceProvider; - private readonly IXContentDescriptionResourceProvider descriptionResourceProvider; - - public XContentProvider( - IXContentEnricher enricher, - XAppConfiguration configuration, - IXContentTagProvider tagProvider, - IXContentServiceProvider provider, - IXContentTitleResourceProvider titleResourceProvider, - IXContentDescriptionResourceProvider descriptionResourceProvider - ) : base( - provider: provider, - tagProvider: tagProvider, - permittedRoles: [XContentServiceConstants.XAdminRole] - ) - { - this.provider = provider; - this.enricher = enricher; - this.tagProvider = tagProvider; - this.configuration = configuration; - this.titleResourceProvider = titleResourceProvider; - this.descriptionResourceProvider = descriptionResourceProvider; - } - - public override bool IsOwned( - XContent item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - !item.OwnerId.IsNullOrEmpty() && - userInfo.UserId == item.OwnerId; - - // - return result; - } - - public override bool IsOwned( - XContentDto item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - !item.OwnerId.IsNullOrEmpty() && - userInfo.UserId == item.OwnerId; - - // - return result; - } - - // - #region Overrides ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - public override async Task Get( - Guid id, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Item ... - var result = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (!result.IsNullOrDefault()) - { - // - result = await enricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - public override async Task> GetAll( - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Items ... - var result = await provider.GetAllAsync( - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (result.HasChild()) - { - // - result = await enricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - public override async Task FindOne( - Expression> predicate, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Detect Item ... - var result = await provider.FindOneAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (!result.IsNullOrDefault()) - { - // - result = await enricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public override async Task> FindMany( - Expression> predicate, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Detect Items ... - var result = await provider.FindManyAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (result.HasChild()) - { - // - result = await enricher.EnrichRange( - sources: result, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - public override async Task> Query( - XQuery query, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Query Items ... - var result = await provider.QueryAsync( - query: query, - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (!result.IsNullOrDefault() && result.Items.HasChild()) - { - // - result.Items = await enricher.EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// retrieve Owned Items based on XQuery Pagination structure ... - /// if supported ... - /// - /// - /// - /// - /// - /// - /// - /// - public override async Task> QueryOwned( - XQuery query, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Predicator ... - Expression> predicateor = null; - if (!predicate.IsNull()) - { - // - var predicateFnc = predicate.Compile(); - predicateor = x => - predicateFnc(x) && - IsOwned(x, userInfo); - } - else - { - predicateor = x => IsOwned(x, userInfo); - } - - // - // Query Items ... - var result = await provider.QueryAsync( - query: query, - predicate: predicateor, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - // Handle Enrichment ... - if (!result.IsNullOrDefault() && result.Items.HasChild()) - { - // - result.Items = await enricher.EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - public override async Task Add( - XContentDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Add( - item: item, - language: null, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - /// - public async Task Add( - XContentDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - - // - // Language ... - if (language.IsNullOrEmpty()) - { - language = configuration.DefaultLanguage; - } - - // - // Owner Id ... - if (item.OwnerId.IsNullOrEmpty()) - { - // - if (!userInfo.IsNullOrDefault()) - { - item.OwnerId = userInfo.UserId; - } - } - - // - // Created On ... - item.CreatedOn = DateTime.UtcNow; - - // - // Validate Normalized Items ... - isValid = item.IsValid(); - if (!isValid) - { - XException.InvalidData.Throw(); - } - - // - // Handle Insert Temp ... - var result = await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: null, // Ignor Push Notifications ..., - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Handle Insert Title/Description ... - - // - var titleResource = await titleResourceProvider.AddOrUpdateLocale( - connectionId: null, - identifier: result.Id, - locale: new XLocaleResourceDto - { - Language = language, - Value = result.Title, - }, - cancellationToken: cancellationToken - ); - - // - XResourceDto descriptionResource = null; - if (!result.Description.IsNullOrEmpty()) - { - // - descriptionResource = await descriptionResourceProvider.AddOrUpdateLocale( - connectionId: null, - identifier: result.Id, - locale: new XLocaleResourceDto - { - Language = language, - Value = result.Description, - }, - cancellationToken: cancellationToken - ); - } - - // - // Fill Item Title and Description ... - if (titleResource.IsNullOrDefault()) - { - result.Title = titleResource.Resource; - } - if (descriptionResource.IsNullOrDefault()) - { - result.Description = descriptionResource.Resource; - } - - // - // Update Item ... - result = await Update( - item: result, - id: result.Id, - userInfo: userInfo, - connectionId: null, - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Handle Enrichment ... - if (isValid) - { - // - result = await enricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - // Handle Push Notifications ... - if (isValid && !connectionId.IsNullOrEmpty()) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - /// - /// - public override async Task Update( - Guid id, - XContentDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - // Handle Resources ... - if (!item.TitleResource.IsNullOrDefault()) - { - item.TitleResource = await titleResourceProvider.AddOrUpdateResource( - identifier: item.Id, - connectionId: connectionId, - resource: item.TitleResource, - cancellationToken: cancellationToken - ); - } - - // - // Handle Update on ... - item.UpdatedAt = DateTime.UtcNow; - - // - var result = await provider.UpdateAsync( - id: id, - item: item, - saveChanges: true, - connectionId: null, - cancellationToken: cancellationToken - ); - var isValid = !result.IsNullOrDefault(); - - // - // Handle Enrichment ... - if (isValid) - { - // - result = await enricher.Enrich( - source: result, - cancellationToken: cancellationToken - ); - } - - // - // Handle Notification ... - if (isValid && !connectionId.IsNullOrEmpty()) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Update.GetStringValue() - ); - } - - // - return result; - } - - /// - /// remove an Item ... - /// - /// - /// - /// - /// - /// - public override async Task Remove( - Guid id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var item = await Get( - id: id, - cancellationToken: cancellationToken - ); - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - // Handle Item Remove ... - var result = await provider.RemoveAsync( - id: id, - saveChanges: true, - softDelete: false, - connectionId: null, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - // Remove Titles/Descriptions ... - - // - // Titles ... - await titleResourceProvider.RemoveLocales( - connectionId: null, - identifier: result.Id, - cancellationToken: cancellationToken - ); - - // - // Descriptions ... - await descriptionResourceProvider.RemoveLocales( - connectionId: null, - identifier: result.Id, - cancellationToken: cancellationToken - ); - - // - // Handle Notifications ... - if (!connectionId.IsNullOrEmpty()) - { - // - await provider.SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Delete.GetStringValue() - ); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentTagProvided.cs - -using System; -using xCommons.Extensions; -using xTagService.Providers; -using xIdentityModels.Models; -using xContentService.Constants; -using xContentService.Interfaces; -using xContentService.Models.Dtos; -using xContentService.Providers.Dtos; -using xContentService.Interfaces.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Providers -{ - public class XContentTagProvided : XBaseTagProvided, IXContentTagProvided - { - public XContentTagProvided( - IXContentTagProvider tagProvider, - IXContentServiceProvider provider - ) : base( - provider: provider, - tagProvider: tagProvider, - permittedRoles: [XContentServiceConstants.XAdminRole] - ) - { } - - public override bool IsOwned( - XContent item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - item.OwnerId == userInfo.UserId; - - // - return result; - } - - public override bool IsOwned( - XContentDto item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - item.OwnerId == userInfo.UserId; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentTagProvider.cs - -using System; -using xTagService.Providers; -using xContentService.Constants; -using xContentService.Interfaces; -using xTagService.Interfaces.Dtos; - -namespace xContentService.Providers -{ - public class XContentTagProvider : XBaseTagProvider, IXContentTagProvider - { - public XContentTagProvider( - IXTagServiceProvider tagProvider - ) : base( - tagProvider: tagProvider, - providedFor: XContentServiceConstants.XContentTagProvided - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\XContentTitleResourceProvider.cs - -using xStringService.Providers; -using xContentService.Constants; -using xContentService.Interfaces; -using xStringService.Interfaces.Dtos; - -namespace xContentService.Providers -{ - public class XContentTitleResourceProvider : XBaseItemResourceProvider, IXContentTitleResourceProvider - { - public XContentTitleResourceProvider( - IXStringServiceProvider stringProvider - ) : base( - stringProvider: stringProvider, - item: XContentServiceConstants.XContentTitleIdentifier - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Dtos\XContentDtoHub.cs - -using System; -using xPushService.Base; -using xContentService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xContentService.Interfaces.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Providers.Dtos -{ - public class XContentDtoHub : XBaseDtoHub, IXContentDtoHub - { - public XContentDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Dtos\XContentRepositoryService.cs - -using System; -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xContentService.Models.Dtos; -using xContentService.Interfaces.Dtos; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Dtos -{ - public class XContentRepositoryService : XBaseRepositoryService, IXContentRepositoryService - { - public XContentRepositoryService( - IXContentRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Dtos\XContentServiceProvider.cs - -using System; -using xPushService.Base; -using xDataService.Configuration; -using xContentService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xContentService.Interfaces.Dtos; -using xContentService.Models.Entities; - -namespace xContentService.Providers.Dtos -{ - public class XContentServiceProvider : XBaseDtoProvider, IXContentServiceProvider - { - public XContentServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXContentRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Enrichers\XContentEnricher.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Collections.Generic; -using xContentService.Interfaces; -using xContentService.Models.Dtos; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using xContentService.Models.Entities; -using xContentService.Interfaces.Enrichers; - -namespace xContentService.Providers.Enrichers -{ - public class XContentEnricher : IXContentEnricher - { - private readonly IXContentTagProvided tagProvider; - private readonly IXIdentityProvider identityProvider; - private readonly IXContentTitleResourceProvider titleResourceProvider; - private readonly IXContentDescriptionResourceProvider descriptionResourceProvider; - - public XContentEnricher( - IXContentTagProvided tagProvider, - IXIdentityProvider identityProvider, - IXContentTitleResourceProvider titleResourceProvider, - IXContentDescriptionResourceProvider descriptionResourceProvider - ) - { - this.tagProvider = tagProvider; - this.identityProvider = identityProvider; - this.titleResourceProvider = titleResourceProvider; - this.descriptionResourceProvider = descriptionResourceProvider; - } - - // - #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XContent source, - CancellationToken cancellationToken = default - ) - { - // - // Mapping Default ... - var result = source.MapConvert(); - result = await Enrich( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XContentDto source, - CancellationToken cancellationToken = default - ) - { - // - // Handdle Owner ... - XPersonDto owner = null; - if (!source.OwnerId.IsNullOrEmpty()) - { - // - // Try to Retrieve User Info ... - var device = identityProvider.GetDevice(); - var userInfo = await identityProvider.GetUserInfo( - device: device, - userSelectByParam: source.OwnerId - ); - owner = userInfo.ToXPersonDto(); - } - - // - // Hanlde Content Title ... - string contentTitle = string.Empty; - XResourceDto titleResource = await titleResourceProvider.GetResource( - identifier: source.Id, - cancellationToken: cancellationToken - ); - if (!titleResource.IsNullOrDefault()) - { - contentTitle = titleResource.Resource; - } - - // - // Hanlde Content Description ... - string contentDescription = string.Empty; - XResourceDto descriptionResource = await descriptionResourceProvider.GetResource( - identifier: source.Id, - cancellationToken: cancellationToken - ); - if (!descriptionResource.IsNullOrDefault()) - { - contentDescription = descriptionResource.Resource; - } - - // - var tags = await tagProvider.GetTags( - id: source.Id, - cancellationToken: cancellationToken - ); - - - // - // Attach Extracted Items ... - var result = source.MapConvert(); - result.Owner = owner; - result.Tags = [..tags]; - result.Title = contentTitle; - result.TitleResource = titleResource; - result.Description = contentDescription; - result.DescriptionResource = descriptionResource; - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(x => Enrich(x, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentEFRepository : XBaseEFRepository, IXContentRepository - where TContext : XDbContext - { - public XContentEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXContentKeyGenerator keyGenerator = null, - IXContentRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentEntityHub.cs - -using System; -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentEntityHub : XBaseEntityHub, IXContentEntityHub - { - public XContentEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentInMemoryRepository : XBaseInMemoryRepository, IXContentRepository - { - public XContentInMemoryRepository( - XDataServiceConfiguration configuration, - IXContentKeyGenerator keyGenerator = null, - IXContentRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentKeyGenerator.cs - -using xDataService.Providers; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentKeyGenerator : XGuidKeyGenerator, IXContentKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentMongoRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentMongoRepository : XBaseMongoRepository, IXContentRepository - { - public XContentMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXContentKeyGenerator keyGenerator = null, - IXContentRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentRepositoryEvents.cs - -using xDataService.Providers; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentRepositoryEvents : XBaseRepositoryEvents, IXContentRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentRepositoryProvider.cs - -using System; -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public class XContentRepositoryProvider : XBaseEntityProvider, IXContentRepositoryProvider - { - public XContentRepositoryProvider( - IHubContext hub, - IXContentRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\Entities\XContentSeederBase.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.Entities -{ - public abstract class XContentSeederBase : XBaseDbSeeder, IXContentSeeder - { - protected XContentSeederBase( - string entity, - string database, - IXContentRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\GraphQL\XContentGraphQLTypeHelper.cs - -using System; -using xDataService.GraphQL; -using xContentService.Constants; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.GraphQL -{ - public class XContentGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXContentGraphQLTypeHelper - { - public override string GetInQueryCollectionName() - { - return XContentServiceConstants.XContentCollectionName; - } - - public override string GetInQuerySingleName() - { - return XContentServiceConstants.XContentSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\GraphQL\XContentGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xContentService.Models.Entities; -using xContentService.Interfaces.Entities; - -namespace xContentService.Providers.GraphQL -{ - public class XContentGraphQuery : XBaseGraphQLQuery - { - public XContentGraphQuery( - XDataServiceConfiguration configuration, - IXContentRepository repository, - IXContentGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\GraphQL\XContentGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xContentService.Providers.GraphQL -{ - public class XContentGraphSchema : Schema - { - public XContentGraphSchema(IServiceProvider services) : base(services) - { - Query = (XContentGraphQuery)services.GetService(typeof(XContentGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xContentService\Providers\GraphQL\XContentGraphType.cs - -using System; -using xDataService.GraphQL; -using xContentService.Models.Entities; - -namespace xContentService.Providers.GraphQL -{ - public class XContentGraphType : XBaseGraphObjectType - { - public XContentGraphType() : base() - { - Field(x => x.Title); - Field(x => x.OwnerId); - Field(x => x.CreatedOn); - Field(x => x.UpdatedAt); - Field(x => x.Description); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xDataService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xDataService-20261109_152620.txt deleted file mode 100644 index 0480f3e..0000000 --- a/Documents/GeneratedContext/xDashboard-xDataService-20261109_152620.txt +++ /dev/null @@ -1,13507 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Builders\XRepositoryDescriptorBuilder.cs - -using xModels.Base; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.GraphQL; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Builders -{ - /// - /// Fluent Builder for constructing XRepositoryDescriptor instances. - /// Replaces the telescoping generic constructors (12-17 type parameters) - /// with a readable, chainable API. - /// - /// The entity type - /// The entity key type - /// - /// var descriptor = XRepositoryDescriptor.For<XAiMessage, Guid>() - /// .WithKeyGenerator<IXAiMessageKeyGenerator, XAiMessageKeyGenerator>() - /// .WithEvents<IXAiMessageRepositoryEvents, XAiMessageRepositoryEvents>() - /// .WithGraphQL<XAiMessageGraphType, GuidGraphType, XAiMessageGraphQuery, - /// IXAiMessageGraphQLTypeHelper, XAiMessageGraphQLTypeHelper, XAiMessageGraphSchema>() - /// .WithEFRepository<XAiApiDbContext, IXAiMessageRepository, XAiMessageEFRepository<XAiApiDbContext>>() - /// .WithSeeder<IXAiMessageSeeder, XAiMessageSeeder>() - /// .Build(); - /// - public sealed class XRepositoryDescriptorBuilder - where TEntity : XBaseEntity - { - private readonly XRepositoryDescriptor _descriptor; - - private XRepositoryDescriptorBuilder() - { - _descriptor = new XRepositoryDescriptor - { - Entity = typeof(TEntity), - Key = typeof(TKey) - }; - } - - /// - /// Creates a new builder instance for the specified entity and key types. - /// - public static XRepositoryDescriptorBuilder Create() - { - return new XRepositoryDescriptorBuilder(); - } - - // - #region KeyGenerator - /// - /// Configures the Key Generator service for the entity. - /// - /// The key generator interface - /// The key generator implementation - public XRepositoryDescriptorBuilder WithKeyGenerator() - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - _descriptor.KeyGeneratorService = typeof(TKeyGeneratorService); - _descriptor.KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - return this; - } - #endregion - - // - #region Events - /// - /// Configures the Repository Events service for the entity. - /// - /// The events interface - /// The events implementation - public XRepositoryDescriptorBuilder WithEvents() - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - _descriptor.EventsService = typeof(TEventsService); - _descriptor.EventsImplementation = typeof(TEventsImplementation); - return this; - } - #endregion - - // - #region GraphQL - /// - /// Configures the full GraphQL stack for the entity. - /// - /// The GraphQL object type - /// The GraphQL key type - /// The GraphQL query type - /// The GraphQL type helper interface - /// The GraphQL type helper implementation - /// The GraphQL schema - public XRepositoryDescriptorBuilder WithGraphQL< - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema>() - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - _descriptor.GraphType = typeof(TGraph); - _descriptor.GraphTypeKey = typeof(TGraphKey); - _descriptor.GraphQuery = typeof(TGraphQuery); - _descriptor.GraphSchema = typeof(TGraphSchema); - _descriptor.GraphTypeHelperService = typeof(TGraphTypeHelperService); - _descriptor.GraphTypeHelperImplementation = typeof(TGraphTypeHelperImplementation); - return this; - } - #endregion - - // - #region Repository - /// - /// Configures an Entity Framework Core repository for the entity. - /// - /// The EF DbContext - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithEFRepository() - where TContext : XDbContext - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseEFRepository - { - _descriptor.Context = typeof(TContext); - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - - /// - /// Configures a MongoDB repository for the entity. - /// - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithMongoRepository() - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseMongoRepository - { - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - - /// - /// Configures an In-Memory repository for the entity. - /// - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithInMemoryRepository() - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseInMemoryRepository - { - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - #endregion - - // - #region Seeder - /// - /// Configures the database seeder for the entity. - /// - /// The seeder interface - /// The seeder implementation - public XRepositoryDescriptorBuilder WithSeeder() - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - { - _descriptor.SeederService = typeof(TSeederService); - _descriptor.SeederImplementation = typeof(TSeederImplementation); - return this; - } - #endregion - - // - #region Build - /// - /// Builds and returns the configured XRepositoryDescriptor. - /// - /// The fully configured descriptor - public XRepositoryDescriptor Build() - { - return _descriptor; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Configuration\XDataBaseConfiguration.cs - -using xDataService.Constants; -using System.Collections.Generic; - -namespace xDataService.Configuration -{ - /// - /// Describe a Database ... - /// - public class XDataBaseConfiguration - { - /// - /// Provider Type ... - /// - /// - public XDbProviders Provider { get; set; } - - /// - /// Connection String which provide Requires Data to Connect to Db Provider ... - /// - /// - public string ConnectionString { get; set; } - - /// - /// Holds Seeding items ... - /// nameof(TEntity) => TEntity - /// - public IDictionary> SeedItems { get; set; } = new Dictionary>(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Configuration\XDataServiceConfiguration.cs - -using xDataService.Constants; -using System.Collections.Generic; - -namespace xDataService.Configuration -{ - /// - /// Represent Configurations of DataService Module ... - /// - public partial class XDataServiceConfiguration - { - /// - /// the base path for providing GraphQL ... - /// - /// - public string GraphQLBasePath { get; set; } = "/graphql"; - - /// - /// Data Bases Configuration ... - /// - /// - public IDictionary Databases { get; set; } = new Dictionary(); - - /// - /// Enable Soft Delete Entities or Not ... - /// - /// - public bool EnableSoftDelete { get; set; } - - /// - /// Specified Seeding Mode ... - /// - public XDbSeedingMode SeedingMode { get; set; } = XDbSeedingMode.None; - - /// - /// Enable Tracking of Entities ... - /// Only Used on EFCore ... - /// - /// - public bool EnableTracking { get; set; } = false; - - /// - /// Enable Logging Details of Errors ... - /// Only Used on EFCore ... - /// - /// - public bool EnableDetailedErrors { get; set; } = false; - - /// - /// Enable Logging Sensitive Data ... - /// Only Used on EFCore ... - /// - /// - public bool EnableSensitiveDataLogging { get; set; } = false; - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - /// - public PagingConfiguration PagingConfiguration { get; set; } = new PagingConfiguration(); - } - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - public partial class PagingConfiguration - { - /// - /// Default Page Size ... - /// - /// - public int DefaultPageSize { get; set; } = XDataServiceConstants.DEFAULT_PAGE_SIZE; - - /// - /// restrict Maximum Page Size ... - /// - /// - public int MaxAvailablePageSize { get; set; } = XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE; - - /// - /// restrice Minimum Page Size ... - /// - /// - public int MinAvailablePageSize { get; set; } = XDataServiceConstants.MIN_AVAILABLE_PAGE_SIZE; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Constants\ConfigurationNodeNames.cs - -namespace xDataService.Constants { - public partial struct ConfigurationNodeNames { - public const string DB_PROVIDER_NODE = "XDBProvider"; - public const string DATA_SERVICE_NODE = "DataServiceConfiguration"; - public const string DATA_SERVICE_DB_SEED_NODE = "DbSeeder"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Constants\XDataServiceConstants.cs - -namespace xDataService.Constants { - /// - /// Default Pagination Values ... - /// - public partial struct XDataServiceConstants { - public static int DEFAULT_PAGE_SIZE = 50; - public static int MAX_AVAILABLE_PAGE_SIZE = 500; - public static int MIN_AVAILABLE_PAGE_SIZE = 20; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Constants\XDbProviders.cs - -namespace xDataService.Constants { - /// - /// Represent Supported DBMS for Managing Data ... - /// - public enum XDbProviders { - None, - MySQL, - SQLite, - Oracle, - SQLServer, - MongoDB, - } - - /// - /// Represent Supported DBMS for Managing Data ... - /// - public partial struct ProviderType { - public const string MySQL = "MYSQL"; - public const string SQLite = "SQLITE"; - public const string Oracle = "ORACLE"; - public const string MongoDB = "MONGODB"; - public const string SQLServer = "SQLSERVER"; - } - -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Constants\XDbSeedingMode.cs - -namespace xDataService.Constants -{ - /// - /// All Seeding Data Mode ... - /// - public enum XDbSeedingMode - { - /// - /// No Seed Data ... - /// - None, - - /// - /// Seed Only New Items ... - /// - AddIfNotExists, - - /// - /// Seed Force (Add/Update) ... - /// - AddOrUpdate, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Constants\XRepositoryType.cs - -using xExceptions.Attributes; - -namespace xDataService.Constants -{ - public enum XRepositoryType - { - [StringValue("EF")] - EF, - - [StringValue("Mongo")] - Mongo, - - [StringValue("InMemory")] - InMemory - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Controllers\XBaseRepositoryController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xDataService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Controllers -{ - /// - /// an Abstract Controller for Providing Entity Repository Actions Implementatin ... - /// - /// - /// - [AllowAnonymous] - public abstract class XBaseRepositoryController : XBaseApiV1Controller, IXBaseRepositoryController - where TEntity : XBaseEntity - { - // - #region Properties ... - public IXBaseRepository Repository { get; } - - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Constructor ... - protected XBaseRepositoryController( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXBaseRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - // - Repository = repository; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await Repository - .AddAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - public virtual async Task> AddOrUpdate( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await Repository - .AddOrUpdateAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - public virtual async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await Repository - .AddRangeAsync( - request.Items, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .GetAsync( - id, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Get Result ... - var result = await Repository - .GetAllAsync( - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await Repository - .FindOneAsync( - predicate: t => - t.PropValuesContains(query), - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await Repository - .FindManyAsync( - predicate: t => - t.PropValuesContains(query), - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - - // - // Get Result ... - var result = await Repository - .QueryAsync( - query: query, - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id, item) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await Repository - .UpdateAsync( - id: id, - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - public virtual async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await Repository - .UpdateRangeAsync( - saveChanges: true, - items: request.Items, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .RemoveAsync( - id: id, - saveChanges: true, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - public virtual async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await Repository - .RemoveRangeAsync( - saveChanges: true, - items: request.Items, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Controllers\XBaseServiceController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xDataService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Controllers -{ - /// - /// an Abstract Controller for Providing Entity Dto Repository Service Actions Implementatin ... - /// - /// - /// - /// - [AllowAnonymous] - public abstract class XBaseServiceController : XBaseApiV1Controller, IXBaseServiceController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - public IXBaseRepositoryService RepositoryService { get; } - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Constructor ... - protected XBaseServiceController( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXBaseRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - // - RepositoryService = repositoryService; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await RepositoryService - .AddAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - public virtual async Task> AddOrUpdate( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await RepositoryService - .AddOrUpdateAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - public virtual async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await RepositoryService - .AddRangeAsync( - request.Items, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .GetAsync( - id, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Get Result ... - var result = await RepositoryService - .GetAllAsync( - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await RepositoryService - .FindOneAsync( - predicate: t => - t.PropValuesContains(query), - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await RepositoryService - .FindManyAsync( - predicate: t => - t.PropValuesContains(query), - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - - // - // Get Result ... - var result = await RepositoryService - .QueryAsync( - query: query, - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id, item) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await RepositoryService - .UpdateAsync( - id: id, - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - public virtual async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await RepositoryService - .UpdateRangeAsync( - saveChanges: true, - items: request.Items, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .RemoveAsync( - id: id, - saveChanges: true, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - public virtual async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await RepositoryService - .RemoveRangeAsync( - saveChanges: true, - items: request.Items, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Db\XDbContext.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xDataService.Providers; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Db -{ - /// - /// Provide an abstraction layout arround DBContext ... - /// Only Used on EFCore ... - /// - public abstract class XDbContext : DbContext - { - // - #region Properties ... - private readonly string database; - private readonly XDataServiceConfiguration config; - private readonly string[] dynamicEntityRegisterarsNames; - private readonly XEntityRegisterarHandlerService dynamicEntityHandlers; - #endregion - - // - #region Entities ... - // - // Register Default and Base Entities ... - #endregion - - // - #region Constructor ... - public XDbContext( - string database, - DbContextOptions options, - XDataServiceConfiguration config, - XEntityRegisterarHandlerService dynamicEntityHandlers, - string[] dynamicEntityRegisterarsNames = null - ) : base(options) - { - // - try - { - Database.EnsureCreated(); - Database.Migrate(); - } - catch { } - - // - this.config = config; - this.database = database; - this.dynamicEntityHandlers = dynamicEntityHandlers; - this.dynamicEntityRegisterarsNames = dynamicEntityRegisterarsNames; - - // - // Handling DbSets of Dynamic Entities ... - if (!dynamicEntityHandlers.IsNull()) - { - // - // Configure XEntityRegisterarHandlerService ... - dynamicEntityHandlers.HandleRegisteredEntities(); - - // - // Loop through Entity Types ... - foreach (var entityType in dynamicEntityHandlers.GetEntityTypes(dynamicEntityRegisterarsNames)) - { - // - try - { - // - // Use reflection to call Set() - var method = typeof(XDbContext) - .GetMethod(nameof(XDbContext.Set), Type.EmptyTypes) - .MakeGenericMethod(entityType); - if (!method.IsNull()) - { - method.Invoke(this, null); - } - } - catch { } - } - } - } - #endregion - - /// - /// Extract Current Database Configuration ... - /// - /// - public XDataBaseConfiguration GetDatabaseConfiguration() - { - // - XDataBaseConfiguration result = - config.Databases.FirstOrDefault(db => string - .Equals(db.Key, database, StringComparison.InvariantCultureIgnoreCase)).Value; - - // - return result; - } - - // - #region Overrides ... - // - // Prepare Model Configs ... - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - // - OnXModelCreating(modelBuilder); - - // - // Automatically apply all IEntityTypeConfiguration in this assembly - modelBuilder.ApplyConfigurationsFromAssembly(typeof(XDbContext).Assembly); - - // - // Check Dynamic Registered Service is Exists or not ... - if (!dynamicEntityHandlers.IsNull()) - { - // - // Set Entity of Dynamically Registered Entities ... - foreach (var entityType in dynamicEntityHandlers.GetEntityTypes(dynamicEntityRegisterarsNames)) - { - modelBuilder.Entity(entityType); - } - - // - // Configure Entity using Provided Registerar ... - dynamicEntityHandlers - .HandleApplyRegisteredEntitiesConfigurations(modelBuilder, dynamicEntityRegisterarsNames); - } - - // - // Since this class inherit from Identity Db Context, - // we have to pass this to Building Identity Models ... - base.OnModelCreating(modelBuilder); - } - - // - // Prepare Configuring ... - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - // - if (config.EnableDetailedErrors) - { - optionsBuilder.EnableDetailedErrors(); - } - - // - if (config.EnableSensitiveDataLogging) - { - optionsBuilder.EnableSensitiveDataLogging(); - } - - // - if (config.EnableTracking) - { - optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll); - } - else - { - optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); - } - - // - OnXConfiguring(optionsBuilder); - - // - base.OnConfiguring(optionsBuilder); - } - #endregion - - // - #region Abstracts ... - // - public abstract void OnXModelCreating(ModelBuilder modelBuilder); - - // - public abstract void OnXConfiguring(DbContextOptionsBuilder optionsBuilder); - #endregion - - // - #region Dynamic DbSet(s) ... - public override DbSet Set() - where TEntity : class - { - return base.Set(); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Db\XUnitOfWorks.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Db { - /// - /// Provide Unit Of Works Design Pattern for Db Transactions ... - /// Only Used on EFCore ... - /// - /// - public class XUnitOfWorks : IXUnitOfWorks - where TDbContext : XDbContext { - public TDbContext DbContext { get; } - - public XUnitOfWorks (TDbContext context) { - this.DbContext = context; - } - - public DbSet GetDbSet () - where T : XBaseEntity { - return DbContext.Set (); - } - - /// - /// Save Changes - /// - public int SaveChanges () { - return DbContext.SaveChanges (); - } - - /// - /// Save Changes Async - /// - /// - /// - public async Task SaveChangesAsync ( - CancellationToken cancellationToken = default - ) { - return await DbContext.SaveChangesAsync (cancellationToken); - } - - public void Dispose () { - DbContext.Dispose (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xDataService.Providers; -using xDataService.Extensions; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace xDataService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Retrive XDataService Configurations - /// - /// - /// - public static XDataServiceConfiguration GetXDataServiceConfiguration( - this IConfiguration source - ) - { - // - var xDataServiceConfigSection = source - .GetSection(ConfigurationNodeNames.DATA_SERVICE_NODE); - var result = xDataServiceConfigSection.Get(); - - // - // Reading Seeders ... - if (!result.IsNull() && - result.Databases.HasChild()) - { - // - result - .Databases - .ToList() - .ForEach(db => - { - // - var seedItemsSectionName = $"{ConfigurationNodeNames.DATA_SERVICE_NODE}:{nameof(XDataServiceConfiguration.Databases)}:{db.Key}:{nameof(XDataBaseConfiguration.SeedItems)}"; - var section = source.GetSection(seedItemsSectionName); - var sectionJson = source.GetSectionAsJson(seedItemsSectionName); - var sectionDict = sectionJson.FromJSON>>(); - if (!sectionDict.IsNull() && - sectionDict.Values.HasChild()) - { - // - sectionDict - .Keys - .ToList() - .ForEach(entity => - { - // - // Setting Values to Result ... - result.Databases[db.Key].SeedItems[entity] = sectionDict[entity]; - }); - } - }); - } - - // - return result; - } - - /// - /// Register XDataService Configuration ... - /// - /// - /// - public static void AddXDataServiceConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXDataServiceConfiguration(); - if (config.IsNullOrDefault()) - { - // - Log("Configurations Not Founded ..."); - XException.NotFound.Throw(); - } - - // - source.AddSingleton(config); - } - - /// - /// Register XDataService Configuration ... - /// - /// - /// - public static void AddXDataServiceConfiguration( - this IServiceCollection source, - XDataServiceConfiguration configuration - ) - { - // - if (configuration.IsNullOrDefault()) - { - // - Log("Configurations Not Founded ..."); - XException.NotFound.Throw(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Register a Data Base using Descriptor ... - /// - /// - /// - /// - /// - public static void AddXDatabase( - this IServiceCollection source, - IConfiguration configuration, - XDatabaseDescriptor descriptor, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Validate Database Descriptor ... - var isValid = - !descriptor.IsNullOrDefault() && - !descriptor.Name.IsNullOrEmpty(); - if (!isValid) - { - // - Log("Invalid Database Descriptor ..."); - return; - } - - // - // Check Service Collection Validation ... - isValid = - !source.IsNull() && - !configuration.IsNull(); - if (!isValid) - { - // - Log("Invalid Service Provider or Configuration ..."); - return; - } - - // - // Get Registere Data Service Configuration ... - var xDataServiceConfiguration = source - .GetRegisteredService(); - isValid = !xDataServiceConfiguration.IsNullOrDefault(); - if (!isValid) - { - // - // Extract Configuration from Configuration ... - xDataServiceConfiguration = configuration.GetXDataServiceConfiguration(); - isValid = !xDataServiceConfiguration.IsNullOrDefault(); - if (!isValid) - { - // - Log("DataService Configuration not provided ..."); - return; - } - - // - // Register Configuration in DI ... - source.AddSingleton(xDataServiceConfiguration); - } - - // - // Check Data Service Configuration has Database ... - isValid = - !xDataServiceConfiguration.Databases.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Contains(descriptor.Name); - if (!isValid) - { - // - Log("Invalid Database Descriptor ..."); - return; - } - - // - // Register Handler Service ... - source.AddSingleton(); - - // - // Configure Database Descriptor ... - descriptor.Configure(source); - - // - // Register Context ... - if (!descriptor.Context.IsNull() && - descriptor.Provider != XDbProviders.None && - !descriptor.ConnectionString.IsNullOrEmpty()) - { - // - try - { - // - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "AddXDbContext", - runtimeType: descriptor.Context, - args: [ - source, - descriptor, - lifeTime - ] - ); - - // - Log($"DbContext: {descriptor.Name} Registered Successfully ..."); - } - catch (Exception ex) - { - Log($"DbContext: {descriptor.Name} Registration failed due {ex.Message} ..."); - } - } - - // - // Register Repositories ... - if (!descriptor.Repositories.IsNull() && - descriptor.Repositories.HasChild()) - { - // - descriptor.Repositories.ToList().ForEach(r => - { - // - source.AddXRepository( - descriptor: r, - lifeTime: lifeTime - ); - }); - } - } - - public static void AddXRepository( - this IServiceCollection source, - XRepositoryDescriptor descriptor, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Preparing Runtime Types ... - Type[] runtimeTypes = descriptor.GetType().GenericTypeArguments; - - // - try - { - // - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "AddXRepository", - runtimeTypes: runtimeTypes, - args: [ - source, - descriptor, - lifeTime - ] - ); - - // - Log($"Repository of: {runtimeTypes[0]}, Registered Successfully ..."); - } - catch (Exception ex) - { - Log($"Repository of: {runtimeTypes[0]}, Registration failed due {ex.Message} ..."); - } - } - - public static void UseXDatabase( - this IApplicationBuilder source, - XDatabaseDescriptor descriptor, - bool isDevelopmentEnvironment = false - ) - { - // - // Validate ... - var isValid = - !source.IsNull() && - descriptor.IsValid(); - if (!isValid) - { - // - Log("Invalid Database Configuration ..."); - XException.InvalidArgs.Throw(); - } - - // - // Check Repositories Exists ... - isValid = descriptor.HasRepositories(); - if (isValid) - { - // - // Loop through Repositories ... - descriptor.Repositories - .ToList() - .ForEach(r => - { - // - source.UseXRepository( - descriptor: r, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - }); - } - } - - /// - /// Use a Repository Middlewares by Providing it's Descriptor ... - /// - /// - /// - /// - public static void UseXRepository( - this IApplicationBuilder source, - XRepositoryDescriptor descriptor, - bool isDevelopmentEnvironment = false - ) - { - // - Log($"Start Using Repository of: {descriptor.Entity}"); - - // - var withPlayground = false; - if (isDevelopmentEnvironment) - { - withPlayground = true; - } - - // - // Create an Scope for Services Acces ... - using (var scope = source.ApplicationServices.CreateScope()) - { - // - // Inject XDataServiceConfiguration ForMake Sure DataService Registration ... - var dataServiceConfiguration = scope.ServiceProvider.GetService(); - var isValid = !dataServiceConfiguration.IsNullOrDefault(); - if (isValid) - { - // - // Check Seeder Exists ... - // Execute Seeding Data Task if Exists ... - isValid = descriptor.HasSeeder(); - if (isValid) - { - // - var seeder = (dynamic)scope.ServiceProvider.GetService(descriptor.SeederService); - isValid = seeder != null; - if (isValid) - { - // - Log($"Start Seeding {descriptor.Entity} ..."); - - // - // Seeding ... - seeder - .Seed() - .GetAwaiter() - .GetResult(); - } - } - - // - // Check GraphQL Support ... - isValid = descriptor.HasGraphSupport(); - if (isValid) - { - // - // Use WebSockets ... - source.UseWebSockets(); - - // - // Inject GraphQL Type Helper ... - var helper = (dynamic)scope.ServiceProvider.GetService(descriptor.GraphTypeHelperService); - isValid = helper != null; - if (isValid) - { - // - var graphPath = $"{helper.GetGraphQLPath()}"; - var graphBasePath = $"{dataServiceConfiguration.GraphQLBasePath}"; - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "UseXGraphQL", - runtimeTypes: [ - descriptor.Entity, - descriptor.Key, - descriptor.GraphType, - descriptor.GraphTypeKey, - descriptor.GraphQuery, - descriptor.GraphTypeHelperService, - descriptor.GraphTypeHelperImplementation, - descriptor.GraphSchema - ], - args: [ - source, - graphBasePath, - graphPath, - withPlayground - ] - ); - - // - Log($"Register GraphQL: {graphPath}"); - } - } - } - } - } - - // - #region Private ... - /// - /// a LogTag for xDataService ... - /// - private static string XLogTag = "xDataService"; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\DbContextOptionExtensions.cs - -using System; -using MySql.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace xDataService.Extensions { - public static class DbContextOptionExtensions { - /// - /// convert dynamic object to MySqlDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToMySQLDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - - /// - /// convert dynamic object to SqliteDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToSqliteDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - - /// - /// convert dynamic object to SqlServerDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToSqlServerDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\EntityExtensions.cs - -using System; -using System.Linq; -using xModels.Base; -using xCommons.Extensions; -using System.Linq.Expressions; -using System.Collections.Generic; - -namespace xDataService.Extensions { - public static class EntityExtensions { - /// - /// return all values of an entity properties as a json string ... - /// - /// - /// - /// - public static string GetPropValues (this T item) - where T : XBaseEntity { - // - var props = item.GetType ().GetProperties (); - var vals = props.Select (p => p.GetValue (item)); - - // - return vals.ToJSON (); - } - - /// - /// check values of all properties of an Entity contains specific value or not ... - /// - /// - /// - /// - /// - public static bool PropValuesContains (this T item, string value) - where T : XBaseEntity => item.GetPropValues () - .ToNormalString () - .Contains (value); - - /// - /// Retrieve Default Column Map of specific Entity ... - /// - /// - /// - /// - public static IDictionary>> GetDefaultColumnsMap (this T item) - where T : XBaseEntity { - // - if (item.IsNull ()) { - return null; - } - - // - var result = new Dictionary>> (); - var props = item.GetType ().GetProperties (); - - // - foreach (var prop in props) { - result.Add ( - prop.Name, - t => t.GetType ().GetProperty (prop.Name).GetValue (t, null)); - } - - // - return result; - } - - /// - /// Check a Type is XBaseEntity or not ... - /// - /// - /// - public static bool IsXEntity(this Type source) - { - // - var result = !source.IsNull(); - if (!result) - { - return result; - } - - // - var baseType = source.BaseType; - while(!baseType.IsNull() && baseType != typeof(object)) - { - // - if (baseType.IsGenericType && - baseType.GetGenericTypeDefinition() == typeof(XBaseEntity<>)) - { - result = true; - break; - } - - // - baseType = baseType.BaseType; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\IQueryableExtensions.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Reflection; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xDataService.Constants; -using System.Linq.Expressions; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Extensions -{ - public static class IQueryableExtensions - { - /// - /// Apply Search Filter on a Query - /// - /// - /// - /// - /// - /// - public static IQueryable ApplyFilter( - this IQueryable source, - string filter - ) - where T : XBaseEntity - { - // - // Apply Filter ... - return source.Where(r => r.PropValuesContains(filter)); - } - - /// - /// Apply Search Filter on a Query - /// - /// - /// - /// - /// - /// - public static async Task> ApplyFilterAsync( - this IQueryable source, - string filter - ) - where T : XBaseEntity - { - // - // Where Clause ... - Expression> whereClause = r => r - .PropValuesContains(filter); - - // - // Generate Where Function ... - var whereFunc = whereClause.Compile(); - - // - // Get Enumerable ... - var enumerator = source - .AsAsyncEnumerable(); - - // - var result = new List(); - await - foreach (var entity in enumerator) - { - // - var isApproved = whereFunc(entity); - if (isApproved) - { - result.Add(entity); - } - } - - // - return result.AsQueryable(); - } - - /// - /// Apply Search Filter on a Enumerable - /// - /// - /// - /// - /// - /// - public static async Task> ApplyFilterAsync( - this IEnumerable source, - string filter - ) - where T : XBaseEntity - { - // - // Where Clause ... - Expression> whereClause = r => r - .PropValuesContains(filter); - - // - // Generate Where Function ... - var whereFunc = whereClause.Compile(); - - // - // Get Enumerable ... - var enumerator = source - .ToList() - .AsQueryable(); - - // - var result = new List(); - foreach (var entity in enumerator) - { - // - var isApproved = whereFunc(entity); - if (isApproved) - { - result.Add(entity); - } - } - - // - return result - .AsEnumerable(); - } - - /// - /// Apply Search Filter on a Enumerable - /// - /// - /// - /// - /// - public static IEnumerable ApplyFilter( - this IEnumerable source, - string filter - ) - where T : class - { - // - // Apply Filter ... - return source.Where(r => r.PropValuesContains(filter)); - } - - /// - /// provide a way to Order an IQueryable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedQueryable OrderBy( - this IQueryable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - - // - // Create x => x.PropName - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - ParameterExpression arg = Expression.Parameter(entityType, "x"); - MemberExpression property = Expression.Property(arg, propertyName); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); - - // - // Get System.Linq.Queryable.OrderBy() method. - var enumarableType = typeof(System.Linq.Queryable); - var method = enumarableType.GetMethods() - .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition) - .Where(m => - { - // - var parameters = m.GetParameters().ToList(); - - // - // Put more restriction here to ensure selecting the right overload - return parameters.Count == 2; // overload that has 2 parameters - }).Single(); - - // - // The linq's OrderBy has two generic types, which provided here ... - MethodInfo genericMethod = method - .MakeGenericMethod(entityType, propertyInfo.PropertyType); - - /* - Call query.OrderBy(selector), with query and selector: x=> x.PropName - Note that we pass the selector as Expression to the method and we don't compile it. - - By doing so EF can extract "order by" columns and generate SQL for it. - */ - var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, selector }); - - // - return newQuery; - } - - /// - /// provide a way to Order an IEnumerable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedEnumerable OrderBy( - this IEnumerable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - return query.OrderBy(x => propertyInfo.GetValue(x, null)); - } - - /// - /// provide a way to Order an IQueryable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedQueryable OrderByDescending( - this IQueryable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - - // - // Create x => x.PropName - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - ParameterExpression arg = Expression.Parameter(entityType, "x"); - MemberExpression property = Expression.Property(arg, propertyName); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); - - // - // Get System.Linq.Queryable.OrderBy() method. - var enumarableType = typeof(System.Linq.Queryable); - var method = enumarableType.GetMethods() - .Where(m => m.Name == "OrderByDescending" && m.IsGenericMethodDefinition) - .Where(m => - { - // - var parameters = m.GetParameters().ToList(); - - // - // Put more restriction here to ensure selecting the right overload - return parameters.Count == 2; // overload that has 2 parameters - }).Single(); - - // - // The linq's OrderBy has two generic types, which provided here ... - MethodInfo genericMethod = method - .MakeGenericMethod(entityType, propertyInfo.PropertyType); - - /* - Call query.OrderBy(selector), with query and selector: x=> x.PropName - Note that we pass the selector as Expression to the method and we don't compile it. - - By doing so EF can extract "order by" columns and generate SQL for it. - */ - var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, selector }); - - // - return newQuery; - } - - /// - /// provide a way to Order an IEnumerable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedEnumerable OrderByDescending( - this IEnumerable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - return query.OrderByDescending(x => propertyInfo.GetValue(x, null)); - } - - /// - /// Apply Sorting on a query - /// - /// - /// - /// - /// - /// - /// - /// - public static IQueryable ApplySorting( - this IQueryable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : XBaseEntity - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Sorting on a query - /// - /// - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplySorting( - this IEnumerable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : XBaseEntity - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Sorting on a Enumerable - /// - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplySorting( - this IEnumerable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : class - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Paging on a qury - /// - /// - /// - /// - /// - /// - public static IQueryable ApplyPaging( - this IQueryable source, - int? page, - int? pageSize - ) - { - // - if (!page.HasValue || - page <= 0) - { - page = 1; - } - - // - if (!pageSize.HasValue || - pageSize <= 0 || - pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE) - { - pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE; - } - - // - var pageVal = page.GetValueOrDefault(); - var pageSizeVal = pageSize.GetValueOrDefault(); - - // - return source - .Skip((pageVal - 1) * pageSizeVal) - .Take(pageSizeVal); - } - - /// - /// Apply Paging on a Enumerable - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplyPaging( - this IEnumerable source, - int? page, - int? pageSize - ) - { - // - if (!page.HasValue || - page <= 0) - { - page = 1; - } - - // - if (!pageSize.HasValue || - pageSize <= 0 || - pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE) - { - pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE; - } - - // - var pageVal = page.GetValueOrDefault(); - var pageSizeVal = pageSize.GetValueOrDefault(); - - // - return source - .Skip((pageVal - 1) * pageSizeVal) - .Take(pageSizeVal); - } - - /// - /// Count Query Pages based on Specified Total Number ... - /// - /// - /// - /// - public static int CountPages(this XQuery source, int totalItems) - { - // - int result = 0; - - // - // Validate and Calculate ... - if (!source.IsNull() && source.PageSize > 0 && totalItems > 0) - { - // - result = totalItems / source.PageSize; - if (totalItems % source.PageSize > 0) - { - result++; - } - } - - // - return result; - } - - /// - /// Normalize an XQuery based on Data Service Configurations ... - /// - /// - /// - /// - public static XQuery NormalizeQuery( - this XQuery source, - XDataServiceConfiguration configuration // - ) - { - // - if (source.IsNull()) - { - source = new XQuery(); - } - - // - // Page Size Normalization ... - if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize; - } - if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize; - } - - // - return source; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XDatabaseDescriptorExtensions.cs - -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Constants; - -namespace xDataService.Extensions -{ - public static class XDatabaseDescriptorExtensions - { - /// - /// Validate a Database Descriptor ... - /// - /// - /// - public static bool IsValid(this XDatabaseDescriptor source) - { - // - var result = - !source.IsNull() && - !source.Name.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Chack a Descriptor Has Provider or not ... - /// - /// - /// - public static bool HasProvider(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.Provider != XDbProviders.None; - - // - return result; - } - - /// - /// Check a Descriptor Has EF Core Context or not ... - /// - /// - /// - public static bool HasContext(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - source.Provider != XDbProviders.MongoDB && - !source.Context.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Repositories or not ... - /// - /// - /// - public static bool HasRepositories(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - !source.Repositories.IsNull() && - source.Repositories.HasChild(); - - // - return result; - } - - /// - /// Check a Descriptor Has MongoDB Convention Packs ... - /// - /// - /// - public static bool HasConventionPacks(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - source.Provider == XDbProviders.MongoDB && - !source.ConventionPacks.IsNull(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XDataServiceConfigurationExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Constants; -using xDataService.Configuration; - -namespace xDataService.Extensions { - public static class XDataServiceConfigurationExtensions { - /// - /// Extract Provider enum from Provider Type ... - /// - /// - /// - public static XDbProviders ToDbProvider (this string source) { - // - if (source.IsNullOrEmpty ()) { - return XDbProviders.None; - } - - // - source = source.ToNormalString (); - - // - var result = source == ProviderType.MySQL.ToNormalString () ? - XDbProviders.MySQL : - source == ProviderType.SQLite.ToNormalString () ? - XDbProviders.SQLite : - source == ProviderType.SQLServer.ToNormalString () ? - XDbProviders.SQLServer : - source == ProviderType.MongoDB.ToNormalString () ? - XDbProviders.MongoDB : - XDbProviders.None; - - // - return result; - } - - /// - /// Retrieve Mongo URI from ConnectionString - /// - /// - /// - public static string GetMongoDbURI (this XDataBaseConfiguration source) { - // - var parts = source.GetConnectionParts (); - var result = parts - .Where (p => p.Trim ().StartsWith ("Uri=")) - .FirstOrDefault (); - result = result.Replace ("Uri=", "").Trim (); - - // - return result; - } - - /// - /// Retrieve Mongo Database Name from Connaction string - /// - /// - /// - public static string GetMongoDbDatabase (this XDataBaseConfiguration source) { - // - var parts = source.GetConnectionParts (); - var result = parts - .Where (p => p.Trim ().StartsWith ("Database=")) - .FirstOrDefault (); - result = result.Replace ("Database=", "").Trim (); - - // - return result; - } - - // - #region Private ... - private static string[] GetConnectionParts (this XDataBaseConfiguration source) { - // - var result = source.ConnectionString.Split (';'); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XGraphQLExtensions.cs - -using GraphQL; -using xModels.Dtos; -using GraphQL.Types; -using xDataService.Constants; - -namespace xDataService.Extensions { - public static class XGraphQLExtensions { - public static TKey GetIdArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.GetIdArgument().Name); - } - - public static bool GetIgnoreSoftDeletedArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.IgnoreSoftDeletedArgument.Name); - } - - public static string GetSearchQueryArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.SearchQueryArgument.Name); - } - - public static XQuery GetQueryArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.QueryArgument.Name); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XMongoDbExtensions.cs - -using System; -using System.Linq; -using MongoDB.Bson; -using MongoDB.Driver; -using xDataService.Mongo; -using MongoDB.Driver.Linq; -using System.Collections.Generic; - -namespace xDataService.Extensions { - public static class XMongoDbExtensions { - public static Guid ToGuid (this ObjectId source) { - // - var bytes = source - .ToByteArray () - .Concat (new byte[] { 5, 5, 5, 5 }) - .ToArray (); - - // - var result = new Guid (bytes); - - // - return result; - } - - public static ObjectId ToObjectId (this Guid source) { - // - var bytes = source - .ToByteArray () - .Take (12) - .ToArray (); - - // - var result = new ObjectId (bytes); - - // - return result; - } - - public static IAsyncEnumerable ToAsyncEnumerable (this IAsyncCursorSource asyncCursorSource) { - return new XAsyncEnumerableAdapter (asyncCursorSource); - } - - public static async IAsyncEnumerable ToAsyncEnumerable (this IAsyncCursor source) { - while (await source.MoveNextAsync ()) { - foreach (var current in source.Current) { - yield return current; - } - } - } - - public static XMongoAsyncCursor ToAsyncCursor (this IQueryable source) { - return new XMongoAsyncCursor (source); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XReferenceExtensions.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using System.ComponentModel; -using System.Collections.Generic; - -namespace xDataService.Extensions -{ - public static class XReferenceExtensions - { - /// - /// Converts an XReference to String Representation ... - /// - /// - /// - /// - /// - public static string ToXReferenceString( - this XReference source, - char? splitter = '_' - ) - { - // - var result = string.Empty; - - // - // Normalize Splitter ... - if (!splitter.HasValue) - { - splitter = '_'; - } - - // - if (!source.IsNullOrDefault() && source.Index >= 0 && !source.ReferencedTo.IsNull()) - { - result = $"{source.ProvidedFor}{splitter.Value}{source.ReferencedTo}{splitter.Value}{source.Index}"; - } - - // - return result; - } - - /// - /// Parse an String and Extract to XReference if it's Described ... - /// - /// - /// - /// - /// - public static XReference FromXReference( - this string source, - char? splitter = '_' - ) - { - // - XReference result = null; - - // - // Normalize Splitter ... - if (!splitter.HasValue) - { - splitter = '_'; - } - - // - if (!source.IsNullOrEmpty()) - { - // - var parts = source.Split(splitter.Value); - if (parts.Count() >= 3) - { - // - T referencedTo; - try - { - referencedTo = (T)Convert.ChangeType(parts[1], typeof(T)); - } - catch - { - referencedTo = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(parts[1]); - } - - // - // Parse String Parts ... - result = new XReference - { - ReferencedTo = referencedTo, - Index = (int)Convert.ChangeType(parts[2], typeof(int)), - ProvidedFor = (string)Convert.ChangeType(parts[0], typeof(string)), - }; - } - } - - // - return result; - } - - /// - /// Converts a Collection of XReference to it's String Representation ... - /// - /// - /// - /// - public static string ToXReferenceString(this IEnumerable> source) - { - // - var result = string.Empty; - - // - if (!source.IsNull() && source.HasChild()) - { - // - var stringList = new List(); - foreach (var s in source) - { - // - var sr = ToXReferenceString(s); - if (!sr.IsNullOrEmpty()) - { - stringList.Add(sr); - } - } - - // - result = stringList.ToListString(); - } - - // - return result; - } - public static string ToXReferenceString(this ICollection> source) - { - // - var result = source - .AsEnumerable() - .ToXReferenceString(); - - // - return result; - } - public static string ToXReferenceString(this IList> source) - { - // - var result = source - .AsEnumerable() - .ToXReferenceString(); - - // - return result; - } - - /// - /// Parse an string to XReference Collection Representation ... - /// - /// - /// - /// - public static IList> ParseXReferenceList(this string source) - { - // - var result = new List>(); - - // - if (!source.IsNullOrEmpty()) - { - // - var stringList = source.ParseListString(); - if (!stringList.IsNull() && stringList.HasChild()) - { - // - foreach (var s in stringList) - { - // - var sr = FromXReference(s); - if (!sr.IsNullOrDefault()) - { - result.Add(sr); - } - } - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Extensions\XRepositoryDescriptorExtensions.cs - -using xModels.Base; -using xDataService.Db; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Extensions -{ - public static class XRepositoryDescriptorExtensions - { - // - #region Hasers ... - /// - /// Validate a Descriptor ... - /// - /// - /// - public static bool IsValid(this XRepositoryDescriptor source) - { - var result = - !source.IsNull() && - !source.Key.IsNull() && - !source.Entity.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Events Service or not ... - /// - /// - /// - public static bool HasEvents(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.EventsService.IsNull() && - !source.EventsImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has EF Core Context or not ... - /// - /// - /// - public static bool HasContext(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.Context.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has GraphQL Support or not ... - /// - /// - /// - public static bool HasGraphSupport(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - source.HasRepository() && - !source.GraphType.IsNull() && - !source.GraphQuery.IsNull() && - !source.GraphSchema.IsNull() && - !source.GraphTypeKey.IsNull() && - !source.GraphTypeHelperService.IsNull() && - !source.GraphTypeHelperImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Key Generator Service or not ... - /// - /// - /// - public static bool HasKeyGenerator(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.KeyGeneratorService.IsNull() && - !source.KeyGeneratorImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Repository Service or not ... - /// - /// - /// - public static bool HasRepository(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.RepositoryService.IsNull() && - !source.RepositoryImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Seeder or not ... - /// - /// - /// - public static bool HasSeeder(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - source.HasRepository() && - !source.SeederService.IsNull() && - !source.SeederImplementation.IsNull(); - - // - return result; - } - #endregion - - // - #region Builders ... - public static XRepositoryDescriptor AddEntity( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - { - // - if (source.IsNull()) - { - source = new XRepositoryDescriptor(); - } - - // - source.Key = typeof(TKey); - source.Entity = typeof(TEntity); - - // - return source; - } - - public static XRepositoryDescriptor AddEvents( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.EventsService = typeof(TEventsService); - source.EventsImplementation = typeof(TEventsImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddKeyGenerator( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.KeyGeneratorService = typeof(TKeyGeneratorService); - source.KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddSeeder( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.SeederService = typeof(TSeederService); - source.SeederImplementation = typeof(TSeederImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddEFRepository( - this XRepositoryDescriptor source - ) - where TContext : XDbContext - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseEFRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddMongoRepository( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseMongoRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddInMemoryRepository( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseInMemoryRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphObjectType.cs - -using xModels.Base; -using GraphQL.Types; - -namespace xDataService.GraphQL -{ - /// - /// Base Entity GraphType Object ... - /// - /// - /// - public abstract class XBaseGraphObjectType : ObjectGraphType - where TEntity : XBaseEntity { - public XBaseGraphObjectType () { - // - Name = $"{typeof(TEntity).Name}GraphType"; - - // - Field (x => x.Id); - Field (x => x.Deleted); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLEventType.cs - -using xModels.Base; -using GraphQL.Types; -using xDataService.Models; - -namespace xDataService.GraphQL { - public class XBaseGraphQLEventType : ObjectGraphType> - where TGraphType : IGraphType - where TEntity : XBaseEntity { - public XBaseGraphQLEventType () { - // - Name = nameof (XBaseGraphQLEventType); - - // - Field (x => x.Model, type : typeof (TGraphType)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLQuery.cs - -using System; -using xModels.Base; -using GraphQL.Types; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Constants; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using xDataService.Configuration; - -namespace xDataService.GraphQL -{ - public abstract class XBaseGraphQLQuery : ObjectGraphType, IXBaseGraphQLQuery - where TEntity : XBaseEntity - where TGraph : IGraphType - where TGraphKey : IGraphType - { - // - protected readonly XDataServiceConfiguration configuration; - protected readonly IXBaseRepository repository; - protected readonly IXBaseGraphQLTypeHelper helper; - - // - public XBaseGraphQLQuery( - XDataServiceConfiguration configuration, - IXBaseRepository repository, - IXBaseGraphQLTypeHelper helper - ) - { - // - this.helper = helper; - this.repository = repository; - this.configuration = configuration; - - // - Name = GetType().Name; - - // - #region Retrieve ... - // - // Get ... - FieldAsync( - name: helper.GetInQuerySingleName(), - arguments: new QueryArguments( - XGraphQLHelper.GetIdArgument(), - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .GetAsync( - includeBuilder: null, - id: context.GetIdArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // GetAll ... - FieldAsync>( - name: helper.GetInQueryCollectionName(), - arguments: new QueryArguments( - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .GetAllAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // FindOne ... - FieldAsync( - name: helper.GetFindOneName(), - arguments: new QueryArguments( - XGraphQLHelper.SearchQueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async (context) => - { - // - var searchQuery = context.GetSearchQueryArgument(); - Expression> whereClase = pe => pe - .PropValuesContains(searchQuery); - - // - return await repository - .FindOneAsync( - includeBuilder: null, - predicate: whereClase, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject(); - } - ); - - // - // FindMany ... - FieldAsync>( - name: helper.GetFindManyName(), - arguments: new QueryArguments( - XGraphQLHelper.SearchQueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async (context) => - { - // - var searchQuery = context.GetSearchQueryArgument(); - Expression> whereClase = pe => pe - .PropValuesContains(searchQuery); - - // - return await repository - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - predicate: whereClase, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject(); - } - ); - - // - // Query ... - FieldAsync>( - name: helper.GetQueryName(), - arguments: new QueryArguments( - XGraphQLHelper.QueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .QueryAsync( - predicate: null, - orderBuilder: null, - includeBuilder: null, - query: context.GetQueryArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // Count ... - FieldAsync( - name: helper.GetCountName(), - arguments: new QueryArguments( - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .CountAsync( - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - ); - - // - // Exists ... - FieldAsync( - name: helper.GetExistsName(), - arguments: new QueryArguments( - XGraphQLHelper.GetIdArgument(), - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository.IsExistsAsync( - id: context.GetIdArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - ); - #endregion - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLSubscription.cs - -using xModels.Base; -using GraphQL.Types; -using GraphQL.Resolvers; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Providers; -using xDataService.Interfaces; -using System.Collections.Generic; - -namespace xDataService.GraphQL { - public abstract class XBaseGraphQLSubscription : ObjectGraphType - where TGraph : IGraphType - where TEntity : XBaseEntity { - public XBaseGraphQLSubscription (IXBaseRepositoryEvents eventProvider = null) { - // - Name = GetType ().Name; - - // - // Check if base repository patter registered ... - if (!eventProvider.IsNull ()) { - // - // Add ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.AddEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnAddObservable; - }) - }); - - // - // Add Many ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.AddManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnAddManyObservable; - }) - }); - - // - // Update ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.UpdateEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnUpdateObservable; - }) - }); - - // - // Update Mnay ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.UpdateManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnUpdateManyObservable; - }) - }); - - // - // Remove ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.RemoveEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnRemoveObservable; - }) - }); - - // - // Remove Many ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.RemoveManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnRemoveManyObservable; - }) - }); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLTypeHelper.cs - -using xModels.Base; -using xCommons.Extensions; -using xDataService.Interfaces; -using xDataService.Configuration; - -namespace xDataService.GraphQL -{ - public abstract class XBaseGraphQLTypeHelper : IXBaseGraphQLTypeHelper - where TEntity : XBaseEntity - { - // - private readonly XDataServiceConfiguration configuration; - - // - protected XBaseGraphQLTypeHelper( - XDataServiceConfiguration configuration = null - ) - { - this.configuration = configuration; - } - - // - public abstract string GetInQueryCollectionName(); - - public abstract string GetInQuerySingleName(); - - // - public string GetFindOneName() - { - return $"find{GetInQuerySingleName().ToNormalString().Capitalize()}"; - } - - public string GetFindManyName() - { - return $"find{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetQueryName() - { - return $"query{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetCountName() - { - return $"count{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetExistsName() - { - return $"exists{GetInQuerySingleName().ToNormalString().Capitalize()}"; - } - - public string GetGraphQLPath(string baseGraphPath = null) - { - // - baseGraphPath = baseGraphPath.IsNullOrEmpty() ? - configuration.IsNull() || configuration.GraphQLBasePath.IsNullOrEmpty() ? - "" : - configuration.GraphQLBasePath : - baseGraphPath; - - // - var basePath = baseGraphPath - .EndsWith("/") ? - baseGraphPath - .Substring(0, baseGraphPath.Length - 1) : - baseGraphPath; - - // - return $"{basePath}/{GetInQueryCollectionName().ToNormalString()}"; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Helpers\XCursorHelper.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using System.Collections.Generic; - -namespace xDataService.Helpers { - public partial class XCursorHelper { - public static string ToCursor (T id) { - // - // Check Numbers ... - if (id.ToString ().IsDigits ()) { - return Convert - .ToBase64String (BitConverter - .GetBytes (Convert.ToInt32 (id)) - ); - } else - // - // Check Guid ... - if (id.ToString ().IsGuid ()) { - return Convert - .ToBase64String (new Guid (id.ToString ()) - .ToByteArray ()); - } else - // - // Assume as String ... - { - return Convert - .ToBase64String (id - .ToString ().ToBytes ()); - } - } - - public static T FromCursor (string cursor) { - // - // Check Numbers ... - var returnType = typeof (T); - if (returnType == typeof (int) || - returnType == typeof (long) || - returnType == typeof (decimal)) { - return Convert.ChangeType ((BitConverter - .ToInt32 (Convert - .FromBase64String (cursor), - 0 - )) - .ToDynamicObject (), returnType); - } else - // - // Check Guid ... - if (returnType == typeof (Guid)) { - return Convert.ChangeType ((new Guid ( - Convert.FromBase64String (cursor) - )) - .ToDynamicObject (), returnType); - } else - // - // Assume as String ... - { - return Convert.ChangeType (( - Convert.FromBase64String (cursor) - ) - .ToDynamicObject (), returnType); - } - } - - public static (string firstCursor, string lastCursor) GetFirstAndLastCursor (IEnumerable ids) { - // - if (ids?.Any () != true) { - return (null, null); - } - - // - var firstCursor = ToCursor (ids.First ()); - var lastCursor = ToCursor (ids.Last ()); - - // - return (firstCursor, lastCursor); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Helpers\XDataServiceHelper.cs - -using System; -using GraphQL; -using System.Linq; -using xModels.Base; -using GraphQL.Types; -using GraphQL.Server; -using xDataService.Db; -using System.Reflection; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.GraphQL; -using xExceptions.Constants; -using xDataService.Constants; -using xDataService.Providers; -using xDataService.Extensions; -using xDataService.Interfaces; -using GraphQL.Server.Ui.Voyager; -using System.Collections.Generic; -using MongoDB.Bson.Serialization; -using GraphQL.Server.Ui.Playground; -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using MySql.EntityFrameworkCore.Extensions; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Helpers -{ - public static class XDataServiceHelper - { - /// - /// Register DbContext ... - /// - /// - /// - /// - /// - public static void AddXDbContext( - IServiceCollection source, - XDatabaseDescriptor databaseDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - // - var isValid = - databaseDescriptor.IsValid() && - databaseDescriptor.HasProvider(); - if (!isValid) - { - XException.InvalidConfiguration.Throw(); - } - - // - switch (databaseDescriptor.Provider) - { - // - // MySQL ... - case XDbProviders.MySQL: - // - source.AddEntityFrameworkMySQL(); - source.AddDbContext(cfg => - { - // - cfg.UseMySQL( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // SQLite ... - case XDbProviders.SQLite: - // - source.AddEntityFrameworkSqlite(); - source.AddDbContext(cfg => - { - // - cfg.UseSqlite( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // Oracle ... - case XDbProviders.Oracle: - // - source.AddEntityFrameworkOracle(); - source.AddDbContext(cfg => - { - // - cfg.UseOracle( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // SQLServer ... - case XDbProviders.SQLServer: - // - source.AddEntityFrameworkSqlServer(); - source.AddDbContext(cfg => - { - // - cfg.UseSqlServer( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // Mongo DB ... - case XDbProviders.MongoDB: - // - #region XBaseEntity Mappers ... - // - // Map ID as BsonId here ... - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - #endregion - - // - // Check Has Convention Packs ... - isValid = databaseDescriptor.HasConventionPacks(); - if (isValid) - { - // - ConventionRegistry.Register( - nameof( - databaseDescriptor.ConventionPacks - ), - databaseDescriptor.ConventionPacks, - type => !type.FullName - .IsNullOrEmpty() - ); - } - break; - } - - // - isValid = - databaseDescriptor.Provider == XDbProviders.MySQL || - databaseDescriptor.Provider == XDbProviders.SQLite || - databaseDescriptor.Provider == XDbProviders.Oracle || - databaseDescriptor.Provider == XDbProviders.SQLServer; - if (isValid) - { - // - AddXUnitOfWorks( - source, - lifetime - ); - } - } - - // - #region Repository ... - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - >( - IServiceCollection source, - XInMemoryRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XInMemoryRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - >( - IServiceCollection source, - XMongoRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XMongoRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TSeederImplementation : XBaseDbSeeder - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext - >( - IServiceCollection source, - XEFRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XEFRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Use GraphQL ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void UseXGraphQL< - TEntity, - TKey, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IApplicationBuilder source, - string graphBasePath, - string graphPath, - bool withPlayGround = false - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - source.UseGraphQL(graphPath); - source.UseGraphQLWebSockets(); - - // - if (withPlayGround) - { - // - source.UseGraphQLPlayground(new GraphQLPlaygroundOptions - { - Path = "/ui/playground", - GraphQLEndPoint = graphBasePath - }); - - // - source.UseGraphQLVoyager(new GraphQLVoyagerOptions - { - Path = "/ui/voyager", - GraphQLEndPoint = graphBasePath - }); - } - } - #endregion - - // - #region Entity Assembly Detector ... - /// - /// Extract Assemblies which Contains Entity ... - /// - /// - public static List ExtractEntityAssemblies() - { - // - var result = new List(); - - // - var allAssemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach (var assembly in allAssemblies) - { - // - try - { - // - bool hasEntity = assembly - .GetExportedTypes() - .Any(t => t.IsXEntity()); - if (hasEntity) - { - result.Add(assembly); - } - } - catch { } - } - - // - return result; - } - - /// - /// Register All Entities using Model Builder ... - /// - /// - public static void RegisterAllEntities(this ModelBuilder modelBuilder) - { - // - // Extract Entity Container Assemblies ... - var entityAssemblies = ExtractEntityAssemblies(); - foreach(var assembly in entityAssemblies) - { - modelBuilder.ApplyConfigurationsFromAssembly(assembly); - } - } - - #endregion - - // - #region Private ... - /// - /// Register Unit of Works ... - /// - /// - /// - /// - public static void AddXUnitOfWorks( - IServiceCollection source, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - // - source.Add( - new ServiceDescriptor( - typeof(IXUnitOfWorks), - typeof(XUnitOfWorks), - lifetime - ) - ); - } - - /// - /// Register Key Generator Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXKeyGenerator< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.KeyGeneratorService.IsNull() && - !repositoryDescriptor.KeyGeneratorImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register ... - source.Add( - new ServiceDescriptor( - repositoryDescriptor.KeyGeneratorService, - repositoryDescriptor.KeyGeneratorImplementation, - lifetime - ) - ); - } - - /// - /// Register Events Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXEvents< - TEntity, - TKey, - TEventsService, - TEventsImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.EventsService.IsNull() && - !repositoryDescriptor.EventsImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register ... - source.Add( - new ServiceDescriptor( - repositoryDescriptor.EventsService, - repositoryDescriptor.EventsImplementation, - lifetime - ) - ); - } - - /// - /// Register GraphQL Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXGraphQL< - TEntity, - TKey, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.GraphType.IsNull() && - !repositoryDescriptor.GraphQuery.IsNull() && - !repositoryDescriptor.GraphSchema.IsNull() && - !repositoryDescriptor.GraphTypeKey.IsNull() && - !repositoryDescriptor.GraphTypeHelperService.IsNull() && - !repositoryDescriptor.GraphTypeHelperImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register Graph Type ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, // ServiceLifetime.Singleton, - serviceType: repositoryDescriptor.GraphType, - implementationType: repositoryDescriptor.GraphType - ) - ); - - // - // Register Graph Events ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, // ServiceLifetime.Singleton, - serviceType: typeof(XBaseGraphQLEventType), - implementationType: typeof(XBaseGraphQLEventType) - ) - ); - - // - // Register Graph Type Helper ... - source.Add( - new ServiceDescriptor( - lifetime: ServiceLifetime.Singleton, - serviceType: repositoryDescriptor.GraphTypeHelperService, - implementationType: repositoryDescriptor.GraphTypeHelperImplementation - ) - ); - - // - // Register Graph Query ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, - serviceType: repositoryDescriptor.GraphQuery, - implementationType: repositoryDescriptor.GraphQuery - ) - ); - - // - // Register Graph Schema ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, - serviceType: repositoryDescriptor.GraphSchema, - implementationType: repositoryDescriptor.GraphSchema - ) - ); - - // - source.AddScoped(); - - // - // Register Graph Type Schema ... - var builder = source.GetRegisteredService(); - if (builder.IsNull()) - { - // - Action options = x => - { - // - x.EnableMetrics = true; - x.UnhandledExceptionDelegate = context => - { - Console.WriteLine("XGraphQL Error: " + context.OriginalException.Message); - }; - }; - builder = source.AddGraphQL(options) - .AddNewtonsoftJson(deserializerSettings => { }, serializerSettings => { }) - .AddWebSockets() - .AddDataLoader() - .AddGraphTypes(lifetime); - } - builder.AddGraphTypes( - serviceLifetime: lifetime, - typeFromAssembly: repositoryDescriptor.GraphSchema - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Helpers\XGraphQLHelper.cs - -using xModels.Dtos; -using GraphQL.Types; -using xDataService.Models; - -namespace xDataService.Constants { - public static class XGraphQLHelper { - public static QueryArgument GetIdArgument () - where TKey : IGraphType { - return new QueryArgument { - Name = "id", - Description = "the id of entity, which you want to retrieve ..." - }; - } - - public static QueryArgument IgnoreSoftDeletedArgument = new QueryArgument { - Name = "ignoreSoftDeleteds", - DefaultValue = true, - Description = "determines result should ignore soft deleted items or not ..." - }; - - public static QueryArgument SearchQueryArgument = new QueryArgument { - Name = "searchQuery", - Description = "the value which had to looking for ..." - }; - - public static QueryArgument QueryArgument = new QueryArgument { - Name = "query", - DefaultValue = new XQuery (), - Description = "determines query structure info for retrieving data ..." - }; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseDbSeeder.cs - -using xModels.Base; -using System.Threading.Tasks; -using xDataService.Configuration; - -namespace xDataService.Interfaces -{ - /// - /// Db Seeder used to seed data on Database on startup time ... - /// - public interface IXBaseDbSeeder - where TEntity : XBaseEntity - { - /// - /// Holds Entity Name ... - /// - string Entity { get; } - - /// - /// Holds Database Name ... - /// - string Database { get; } - - /// - /// Repository Service for Data Manipulation ... - /// - IXBaseRepository Repository { get; } - - /// - /// DataServiceConfiguration ... - /// - XDataServiceConfiguration DataServiceConfiguration { get; } - - /// - /// do all seeding action by helping of Repositories here ... - /// - /// - Task Seed(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseEnricher.cs - -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Interfaces -{ - public interface IXBaseEnricher - { - Task EnrichAsync( - TSource source, - TDest destination, - CancellationToken cancellationToken = default - ); - - Task EnrichRangeAsync( - IEnumerable sources, - IEnumerable destinations, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseGraphQLQuery.cs - -using xModels.Base; -using GraphQL.Types; - -namespace xDataService.Interfaces -{ - public interface IXBaseGraphQLQuery - where TEntity : XBaseEntity - where TGraph : IGraphType - where TGraphKey : IGraphType - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseGraphQLTypeHelper.cs - -using xModels.Base; - -namespace xDataService.Interfaces -{ - public interface IXBaseGraphQLTypeHelper - where TEntity : XBaseEntity - { - string GetInQuerySingleName(); - - string GetInQueryCollectionName(); - - string GetFindOneName(); - - string GetFindManyName(); - - string GetQueryName(); - - string GetCountName(); - - string GetExistsName(); - - string GetGraphQLPath(string baseGraphPath = null); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseReferencedProvider.cs - -using xModels.Dtos; -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Interfaces -{ - /// - /// in Some Cases we have Entities Which Can Referenced for Specified - /// Provider and Types ... - /// this interface Globaly introduce all available Actions for those ... - /// - /// TKey: type of Provider Models Keys ... - /// TModel: type of Dto which Referenced ... - /// - public interface IXBaseReferencedProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - string Provider { get; } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - Task GetReference( - TKey providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - Task> GetAllReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - Task>> GetAllReferencings( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Count References ... - /// - /// - /// - /// - Task CountReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - Task> QueryReferences( - XQuery query, - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - Task RemoveReferences( - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - public interface IXBaseRepository : IDisposable { } - - /// - /// Base Repository Pattern Contracts in XDashboard's Data Service ... - /// use for Data Manipulation ... - /// - /// - /// - public interface IXBaseRepository : IXBaseRepository - where T : XBaseEntity - { - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ); - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ); - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - Task SaveChangesAsync( - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - TKey GetKey(T item); - - /// - /// Set Key of Entity ... - /// - /// - /// - void SetKey( - ref T item, - TKey id - ); - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - void Detach(T item); - - /// - /// Detach an Enumerable of Entities ... - /// - /// - void Detach(IEnumerable items); - - /// - /// Detach a Query Result of Entity ... - /// - /// - void Detach(XQueryResult query); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Base Repository Actions Providing Using Controllers ... - /// - /// - /// - public interface IXBaseRepositoryController - where TEntity : XBaseEntity - { - // - IXBaseRepository Repository { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - - // - #region Add ... - Task> Add( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task> AddOrUpdate( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - - Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryEvents.cs - -using System; -using xDataService.Models; -using System.Collections.Generic; - -namespace xDataService.Interfaces { - public interface IXBaseRepositoryEvents { - // - void AddEvent (XBaseEventModel model); - void UpdateEvent (XBaseEventModel model); - void RemoveEvent (XBaseEventModel model); - - // - void AddManyEvent (XBaseEventModel> model); - void UpdateManyEvent (XBaseEventModel> model); - void RemoveManyEvent (XBaseEventModel> model); - - // - IObservable> OnAddObservable { get; } - IObservable> OnUpdateObservable { get; } - IObservable> OnRemoveObservable { get; } - - // - IObservable>> OnAddManyObservable { get; } - IObservable>> OnUpdateManyObservable { get; } - IObservable>> OnRemoveManyObservable { get; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryService.cs - -using System; -using AutoMapper; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Manipulating Data Using Services based on Dto Mapping ... - /// - /// - /// - /// - public interface IXBaseRepositoryService : IDisposable - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - /// - /// Mapper Instance ... - /// - IMapper Mapper { get; } - - /// - /// Repository Implementation for Data Manipulations ... - /// - IXBaseRepository Repository { get; } - - /// - /// Mapping Profile Configuration ... - /// - /// this Configuration used for Mapping TEntity to Dto and reverse ... - /// default mapping prepared on Constructing time, other custom maps - /// must handled manually if required ... - /// - MapperConfiguration MapperConfiguration { get; } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - Task AddAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add or update a Dto (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - Task AddOrUpdateAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add a range of new Dtos ... - /// - /// - /// - /// - /// - Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update a range of Dtos ... - /// - /// - /// - /// - /// - Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Dto ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TDto item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove a range of exists Dtos ... - /// - /// - /// - /// - /// - /// - Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Count ... - /// - /// count all exists Dtos ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseServiceController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Base RepositoryService Actions Providing Using Controllers ... - /// - /// - /// - /// - public interface IXBaseServiceController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - IXBaseRepositoryService RepositoryService { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - - // - #region Add ... - Task> Add( - TDto item, - CancellationToken cancellationToken = default - ); - - Task> AddOrUpdate( - TDto item, - CancellationToken cancellationToken = default - ); - - Task AddMany( - XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ); - - Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeletedss = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - - Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXDatabaseDescriptor.cs - -using System; -using xDataService.Db; -using xDataService.Models; -using xDataService.Constants; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.Extensions.Configuration; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Interfaces -{ - /// - /// Data Base Descriptor ... - /// - public interface IXDatabaseDescriptor - { - // - #region Props ... - /// - /// Database Name ... - /// - /// - string Name { get; set; } - - /// - /// Database Provider ... - /// - /// - XDbProviders Provider { get; set; } - - /// - /// Db Context Type ... - /// - /// - Type Context { get; set; } - - /// - /// Database Connecion String ... - /// - /// - string ConnectionString { get; set; } - - /// - /// Data Service Configuration ... - /// - /// - XDataBaseConfiguration Configuration { get; set; } - - /// - /// Repositories Descriptions ... - /// - /// - IList Repositories { get; set; } - - /// - /// Mongo Convention Packs ... - /// - ConventionPack ConventionPacks { get; set; } - - /// - /// DbContext Options Builder ... - /// - /// - Action OptionsBuilder { get; set; } - #endregion - - // - #region Configure ... - /// - /// Configure Database Descriptor using Registered Services ... - /// - /// - void Configure( - IServiceCollection services - ); - - /// - /// Configure Database Descriptor using IConfiguration ... - /// - /// - void Configure( - IConfiguration configuration - ); - - /// - /// Configure Database Descriptor using Database Configuration ... - /// - /// - void Configure( - XDataBaseConfiguration configuration - ); - - /// - /// Configure Database Descriptor using Provider and Connection String ... - /// - /// - /// - void Configure( - XDbProviders provider, - string connectionString - ); - #endregion - } - - /// - /// Data Base Descriptor ... - /// - /// - public interface IXDatabaseDescriptor : IXDatabaseDescriptor - where TContext : XDbContext - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXEntityRegisterar.cs - -using System; -using xModels.Base; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Interfaces -{ - /// - /// an Interface to Intruduce Entities for Dynamic Registration ... - /// - public interface IXEntityRegisterar - { - /// - /// Database Name ... - /// - string Name { get; } - - /// - /// Returns all entity types this plugin wants registered in the DbContext - /// - IEnumerable GetEntityTypes(); - - /// - /// Optional: Apply additional per-entity configuration - /// - void ConfigureEntities(ModelBuilder modelBuilder); - - /// - /// Add XDataService Based Entity to List ... - /// - /// - /// - void AddEntity() - where TEntity : XBaseEntity; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXKeyGenerator.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; - -namespace xDataService.Interfaces -{ - /// - /// Typed Base Key Generator ... - /// - /// - /// - public interface IXKeyGenerator - where TEntity : XBaseEntity - { - bool IsEmpty(TKey id); - Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXSequentialGuid.cs - -using System; - -namespace xDataService.Interfaces { - /// - /// this service provide Sequential GUID mechanism for Entity Ids ... - /// - public interface IXSequentialGuid { - Guid GetCurrentGuid (); - Guid Next (); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXUnitOfWorks.cs - -using System; -using xModels.Base; -using xDataService.Db; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Interfaces { - /// - /// Provide Unit Of Works Design Pattern for Db Transactions ... - /// Only Used on EFCore ... - /// - /// - public interface IXUnitOfWorks : IDisposable - where TDbContext : XDbContext { - TDbContext DbContext { get; } - DbSet GetDbSet () where T : XBaseEntity; - int SaveChanges (); - Task SaveChangesAsync ( - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XBaseEventModel.cs - -namespace xDataService.Models { - /// - /// Pass Data on Repository Events ... - /// - /// - public class XBaseEventModel { - public T Model { get; set; } - - public XBaseEventModel (T model) { - Model = model; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XDatabaseDescriptor.cs - -using System; -using System.Linq; -using xDataService.Db; -using xDataService.DI; -using xCommons.Extensions; -using xDataService.Constants; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.Extensions.Configuration; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Models -{ - /// - /// Data Base Descriptor ... - /// - public abstract class XDatabaseDescriptor : IXDatabaseDescriptor - { - // - #region Props ... - /// - /// Database Name ... - /// - /// - public virtual string Name { get; set; } - - /// - /// Database Provider ... - /// - /// - public virtual XDbProviders Provider { get; set; } - - /// - /// Db Context... - /// - /// - public virtual Type Context { get; set; } = null; - - /// - /// Database Connecion String ... - /// - /// - public virtual string ConnectionString { get; set; } - - /// - /// Data Service Configuration ... - /// - /// - public virtual XDataBaseConfiguration Configuration { get; set; } - - /// - /// Repositories Descriptions ... - /// - /// - public virtual IList Repositories { get; set; } = null; - - /// - /// Mongo Convention Packs ... - /// - public ConventionPack ConventionPacks { get; set; } = null; - - /// - /// DbContext Options Builder ... - /// - /// - public Action OptionsBuilder { get; set; } = null; - #endregion - - // - #region Constructor ... - /// - /// Constructor of Descriptor ... - /// - /// - /// - /// - public XDatabaseDescriptor( - string name, - IList repositories = null - ) - { - // - Name = name; - Repositories = repositories; - } - #endregion - - // - #region Configure ... - /// - /// Configure Database Descriptor using Registered Services ... - /// - /// - public void Configure( - IServiceCollection services - ) - { - // - bool isValid = !Name.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var xDataServiceConfiguration = services.GetRegisteredService(); - isValid = - !xDataServiceConfiguration.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Any(k => k == Name); - if (!isValid) - { - return; - } - - // - var database = xDataServiceConfiguration.Databases[Name]; - isValid = !database.IsNullOrDefault(); - if (!isValid) - { - return; - } - - // - Configure(database); - } - - /// - /// Configure Database Descriptor using IConfiguration ... - /// - /// - public void Configure( - IConfiguration configuration - ) - { - // - bool isValid = !Name.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var xDataServiceConfiguration = configuration.GetXDataServiceConfiguration(); - isValid = - !xDataServiceConfiguration.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Any(k => k == Name); - if (!isValid) - { - return; - } - - // - var database = xDataServiceConfiguration.Databases[Name]; - isValid = !database.IsNullOrDefault(); - if (!isValid) - { - return; - } - - // - Configure(database); - } - - /// - /// Configure Database Descriptor using Database Configuration ... - /// - /// - public void Configure( - XDataBaseConfiguration configuration - ) - { - // - Configuration = configuration; - Provider = configuration.Provider; - ConnectionString = configuration.ConnectionString; - } - - /// - /// Configure Database Descriptor using Provider and Connection String ... - /// - /// - /// - public void Configure( - XDbProviders provider, - string connectionString - ) - { - // - Provider = provider; - ConnectionString = connectionString; - Configuration = new XDataBaseConfiguration - { - Provider = provider, - ConnectionString = connectionString - }; - } - #endregion - } - - /// - /// Data Base Descriptor ... - /// - /// - public abstract class XDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor - where TContext : XDbContext - { - /// - /// Constructor of Descriptor ... - /// - /// - /// - /// - /// - public XDatabaseDescriptor( - string name, - IList repositories = null - ) : base( - name: name, - repositories: repositories - ) - { - Context = typeof(TContext); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XGraphQueryResult.cs - -using xModels.Dtos; -using GraphQL.Types; - -namespace xDataService.Models { - public class XGraphQueryResult : ObjectGraphType> - where TGraph : IGraphType { - public XGraphQueryResult () { - // - Name = $"{typeof(TGraph).Name}QueryResult"; - - // - Field> (nameof (XQueryResult.Items)); - Field (x => x.Page); - Field (x => x.PageSize); - Field (x => x.TotalPages); - Field (x => x.TotalFilteredItems); - Field (x => x.TotalItems); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XGraphQueryType.cs - -using xModels.Dtos; -using GraphQL.Types; - -namespace xDataService.Models { - public class XGraphQueryType : InputObjectGraphType { - public XGraphQueryType () { - // - Name = "query"; - - // - Field (x => x.Filter); - Field (x => x.ContainsDetail); - Field (x => x.SortBy); - Field (x => x.IsAscending); - Field (x => x.Page); - Field (x => x.PageSize); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XReference.cs - -namespace xDataService.Models -{ - public class XReference - { - public int Index { get; set; } - public T ReferencedTo { get; set; } - public string ProvidedFor { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Models\XRepositoryDescriptor.cs - -using System; -using xModels.Base; -using GraphQL.Types; -using xDataService.Db; -using xDataService.GraphQL; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Models -{ - /// - /// a Global non Generic Repository Descriptor ... - /// - public class XRepositoryDescriptor - { - /// - /// Entity Key Type ... - /// - /// - public Type Key { get; set; } = null; - - /// - /// Entity Type ... - /// - /// - public Type Entity { get; set; } = null; - - /// - /// Context Type ... - /// - /// - public Type Context { get; set; } = null; - - /// - /// Graph Type Key ... - /// - /// - public Type GraphTypeKey { get; set; } = null; - - /// - /// Graph Type ... - /// - /// - public Type GraphType { get; set; } = null; - - /// - /// Entity Type GraphQL Schema ... - /// - /// - public Type GraphSchema { get; set; } = null; - - /// - /// Entity GraphQL Type Helper ... - /// - /// - public Type GraphTypeHelperService { get; set; } = null; - - /// - /// Entity GraphQL Type Helper ... - /// - /// - public Type GraphTypeHelperImplementation { get; set; } = null; - - /// - /// Entity GrapQL Query ... - /// - /// - public Type GraphQuery { get; set; } = null; - - /// - /// Repository Event Provider ... - /// - /// - public Type EventsService { get; set; } = null; - - /// - /// Repository Event Provider ... - /// - /// - public Type EventsImplementation { get; set; } = null; - - /// - /// Repository Key Generator for Entity ... - /// - /// - public Type KeyGeneratorService { get; set; } = null; - - /// - /// Repository Key Generator for Entity ... - /// - /// - public Type KeyGeneratorImplementation { get; set; } = null; - - /// - /// Repository Data Access Design Pattern ... - /// - /// - public Type RepositoryService { get; set; } = null; - - /// - /// Repository Data Access Design Pattern ... - /// - /// - public Type RepositoryImplementation { get; set; } = null; - - /// - /// Database Data Seeder ... - /// - public Type SeederService { get; set; } = null; - - /// - /// Database Data Seeder ... - /// - public Type SeederImplementation { get; set; } = null; - } - - /// - /// a Repository Descriptor ... - /// - /// - /// - public class XRepositoryDescriptor : XRepositoryDescriptor - where TEntity : XBaseEntity - { - public XRepositoryDescriptor() : base() - { - // - Key = typeof(TKey); - Entity = typeof(TEntity); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - > : XRepositoryDescriptor - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - public XRepositoryDescriptor() : base() - { - // - KeyGeneratorService = typeof(TKeyGeneratorService); - KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - > - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - { - public XRepositoryDescriptor() : base() - { - // - EventsService = typeof(TEventsService); - EventsImplementation = typeof(TEventsImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XRepositoryDescriptor() : base() - { - // - GraphType = typeof(TGraph); - GraphTypeKey = typeof(TGraphKey); - GraphQuery = typeof(TGraphQuery); - GraphSchema = typeof(TGraphSchema); - GraphTypeHelperService = typeof(TGraphTypeHelperService); - GraphTypeHelperImplementation = typeof(TGraphTypeHelperImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XInMemoryRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XInMemoryRepositoryDescriptor() : base() - { - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XInMemoryRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TSeederImplementation : XBaseDbSeeder - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XInMemoryRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XMongoRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XMongoRepositoryDescriptor() : base() - { - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XMongoRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XMongoRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XEFRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XEFRepositoryDescriptor() : base() - { - // - Context = typeof(TContext); - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XEFRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XEFRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - Context = typeof(TContext); - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Mongo\XAsyncEnumerableAdapter.cs - -using MongoDB.Driver; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XAsyncEnumerableAdapter : IAsyncEnumerable { - // - private readonly IAsyncCursorSource asyncCursorSource; - - // - public XAsyncEnumerableAdapter (IAsyncCursorSource asyncCursorSource) { - this.asyncCursorSource = asyncCursorSource; - } - - // - public IAsyncEnumerator GetAsyncEnumerator (CancellationToken cancellationToken) => - new XAsyncEnumeratorAdapter (asyncCursorSource, cancellationToken); - } - - public class XAsyncEnumeratorAdapter : IAsyncEnumerator { - private readonly IAsyncCursorSource asyncCursorSource; - private readonly CancellationToken cancellationToken; - private IAsyncCursor asyncCursor; - private IEnumerator batchEnumerator; - - public T Current => batchEnumerator.Current; - - public XAsyncEnumeratorAdapter ( - IAsyncCursorSource asyncCursorSource, - CancellationToken cancellationToken - ) { - // - this.asyncCursorSource = asyncCursorSource; - this.cancellationToken = cancellationToken; - } - - public async ValueTask MoveNextAsync () { - // - if (asyncCursor == null) { - asyncCursor = await asyncCursorSource - .ToCursorAsync (cancellationToken); - } - - // - if (batchEnumerator != null && - batchEnumerator.MoveNext ()) { - return true; - } - - // - if (asyncCursor != null && - await asyncCursor.MoveNextAsync (cancellationToken)) { - // - batchEnumerator?.Dispose (); - batchEnumerator = asyncCursor.Current.GetEnumerator (); - - // - return batchEnumerator.MoveNext (); - } - - // - return false; - } - - public async ValueTask DisposeAsync () { - // - await Task.CompletedTask; - asyncCursor?.Dispose (); - asyncCursor = null; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoAsyncCursor.cs - -using MongoDB.Driver; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XMongoAsyncCursor : IAsyncCursor { - public IEnumerable Current { get; } - private IEnumerator CurrentEnumerator { get; } - - public XMongoAsyncCursor (IEnumerable source) { - this.Current = source; - this.CurrentEnumerator = source.GetEnumerator (); - } - - public void Dispose () { - CurrentEnumerator.Dispose (); - } - - public bool MoveNext (CancellationToken cancellationToken = default) { - return CurrentEnumerator.MoveNext (); - } - - public Task MoveNextAsync (CancellationToken cancellationToken = default) { - return Task.Run ( - () => CurrentEnumerator.MoveNext (), - cancellationToken : cancellationToken - ); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoQueryable.cs - -using System; -using System.Linq; -using xModels.Base; -using MongoDB.Driver; -using System.Threading; -using System.Collections; -using MongoDB.Driver.Linq; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XMongoQueryable : IMongoQueryable - where TEntity : XBaseEntity { - private readonly IMongoCollection collection; - - public Type ElementType { get; } - public IQueryable Items { get; } - public Expression Expression { get; } - public IQueryProvider Provider { get; } - - public XMongoQueryable ( - IQueryable items, - IMongoCollection collection - ) { - // - this.Items = items; - this.collection = collection; - - // - Provider = items.Provider; - Expression = items.Expression; - ElementType = items.ElementType; - } - - public IEnumerator GetEnumerator () { - return Items.GetEnumerator (); - } - - public QueryableExecutionModel GetExecutionModel () { - return collection.AsQueryable ().GetExecutionModel (); - } - - public IAsyncCursor ToCursor (CancellationToken cancellationToken = default) { - return new XMongoAsyncCursor (Items); - } - - public Task> ToCursorAsync (CancellationToken cancellationToken = default) { - return Task.Run (() => new XMongoAsyncCursor (Items) as IAsyncCursor); - } - - IEnumerator IEnumerable.GetEnumerator () { - return Items.GetEnumerator (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoReadPreferenceResolver.cs - -using MongoDB.Driver; - -namespace xDataService.Mongo { - public static class XMongoReadPreferenceResolver { - public static ReadPreference GetEffectiveReadPreference ( - IClientSessionHandle session, - ReadPreference explicitReadPreference, - ReadPreference defaultReadPreference) { - if (explicitReadPreference != null) { - return explicitReadPreference; - } - - if (session.IsInTransaction) { - var transactionReadPreference = session.WrappedCoreSession.CurrentTransaction.TransactionOptions.ReadPreference; - if (transactionReadPreference != null) { - return transactionReadPreference; - } - } - - return defaultReadPreference ?? ReadPreference.Primary; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseDbSeeder.cs - -using System.Linq; -using xModels.Base; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Constants; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; - -namespace xDataService.Providers -{ - public abstract class XBaseDbSeeder : IXBaseDbSeeder - where TEntity : XBaseEntity - { - // - #region Properties ... - /// - /// Holds Entity Name ... - /// - public string Entity { get; } - - /// - /// Holds Database Name ... - /// - public string Database { get; } - - /// - /// Repository Service for Data Manipulation ... - /// - public IXBaseRepository Repository { get; } - - /// - /// DataServiceConfiguration ... - /// - public XDataServiceConfiguration DataServiceConfiguration { get; } - #endregion - - // - #region Constructor ... - public XBaseDbSeeder( - string entity, - string database, - IXBaseRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) - { - // - this.Entity = entity; - this.Database = database; - this.Repository = repository; - this.DataServiceConfiguration = dataServiceConfiguration; - } - #endregion - - public async Task Seed() - { - // - // Validate Seed ... - var isValid = - DataServiceConfiguration.SeedingMode != XDbSeedingMode.None && - DataServiceConfiguration - .Databases - .Any(db => - db.Key == Database && - db.Value.SeedItems - .Any(si => - si.Key == Entity && - si.Value.HasChild())); - if (!isValid) - { - return; - } - - // - // Extract Seeding Items ... - var seedItems = DataServiceConfiguration - .Databases[Database] - .SeedItems[Entity] - .ToList(); - foreach (var item in seedItems) - { - // - try - { - // - var entity = item - .ToJSON() - .FromJSON(); - - // - // Check Item Exists or not ... - var isExist = false; - TEntity exists = null; - var asyncEnumerable = this.Repository.GetAllAsAsyncEnumerable(); - await foreach (var e in asyncEnumerable) - { - // - isExist = e.IsSameContent( - dest: entity, - propertyBlackList: new List - { - nameof(entity.Id), - nameof(entity.Deleted) - }); - if (isExist) - { - exists = e; - break; - } - } - - // - // Seed Based on Seed Mode ... - var seedMode = DataServiceConfiguration.SeedingMode; - switch (seedMode) - { - // - case XDbSeedingMode.AddIfNotExists: - // - if (!isExist) - { - // - exists = await Repository.AddAsync( - item: entity, - saveChanges: true - ); - } - break; - - // - case XDbSeedingMode.AddOrUpdate: - // - exists = exists.UpdateData( - updateWith: entity, - propertyBlackList: new List - { - nameof(entity.Id), - nameof(entity.Deleted) - } - ); - - // - await Repository.AddOrUpdateAsync(exists); - break; - } - } - catch - { } - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEFRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using xDataService.Db; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for EF DBs using - /// EF Core Capabilities ... - /// - /// - /// - /// - public abstract class XBaseEFRepository : IXBaseRepository - where T : XBaseEntity - where TDbContext : XDbContext - { - // - #region Properties ... - // - public readonly DbSet dbSet; - private readonly IXKeyGenerator keyGenerator; - public readonly IXUnitOfWorks unitOfWorks; - public readonly XDataServiceConfiguration configuration; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - #endregion - - // - #region Constructor ... - public XBaseEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - // - this.unitOfWorks = unitOfWorks; - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.dbSet = unitOfWorks.GetDbSet(); - this.baseRepositoryEvents = baseRepositoryEvents; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - var entry = await dbSet.AddAsync( - entity: item, - cancellationToken: cancellationToken - ); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: GetKey(item), - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - return await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - else - { - // - return await UpdateAsync( - item: item, - id: GetKey(item), - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Preparing Ids and Keys ... - await dbSet.AddRangeAsync( - await Task - .WhenAll( - items - .Select(async i => await HandleKeyAsync(i)) - ), - cancellationToken: cancellationToken - ); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Get Exists Entity ... - var existsEntity = await GetAsync( - id: id, - ignoreSoftDeleteds: false, - cancellationToken: cancellationToken - ); - - // - // Update Data ... - existsEntity.UpdateData(item); - var entry = dbSet.Attach(existsEntity); - entry.State = EntityState.Modified; - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - items - .ToList() - .ForEach(i => - { - var entry = dbSet.Attach(i); - entry.State = EntityState.Modified; - }); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateManyEvent(new XBaseEventModel>(null)); - } - - // - // Return result base on action Succeed ... - return isSucceed; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Item ... - var item = await GetAsync( - id, - ignoreSoftDeleteds: false, - cancellationToken: cancellationToken - ); - if (item.IsNullOrDefault()) - { - return null; - } - - // - // Handle Remove ... - EntityEntry entry = null; - if (softDelete && configuration.EnableSoftDelete) - { - // - item.Deleted = true; - entry = dbSet.Update(item); - } - else - { - entry = dbSet.Remove(item); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Remove ... - if (softDelete && configuration.EnableSoftDelete) - { - // - foreach (var item in items) - { - item.Deleted = true; - } - - // - dbSet.UpdateRange(items); - } - else - { - dbSet.RemoveRange(items); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = 0; - - // - if (ignoreSoftDeleteds) - { - // - result = await dbSet.CountAsync( - predicate: x => !x.Deleted, - cancellationToken: cancellationToken - ); - } - else - { - result = await dbSet.CountAsync(cancellationToken); - } - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = dbSet - .AsQueryable(); - - // - // Apply Predicate ... - if (!predicate.IsNull()) - { - result = result - .Where(predicate); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - // Apply Ordering ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken)) - .FirstOrDefault(x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var list = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - var whereClause = predicate.Compile(); - var result = list.FirstOrDefault(x => whereClause(x)); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken)) - .Where(predicate.Compile()); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .ToListAsync(cancellationToken)) - .Any(predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - return await unitOfWorks.SaveChangesAsync(cancellationToken); - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(T item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref T item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(T item) - { - // - if (item.IsNull()) - { - return; - } - - // - Entry(item).State = EntityState.Detached; - } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) - { - // - if (items.IsNull() || !items.HasChild()) - { - return; - } - - // - items - .ToList() - .ForEach(item => - { - Detach(item); - }); - } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) - { - // - if (query.IsNull() || query.Items.HasChild()) - { - return; - } - - // - Detach(query.Items); - } - #endregion - #endregion - - // - #region Others ... - public void Dispose() - { - unitOfWorks.Dispose(); - } - - public string GetPropValues(T item) - { - // - var props = item.GetType().GetProperties(); - var vals = props.Select(p => p.GetValue(p.Name)); - - // - return vals.ToJSON(); - } - - public EntityEntry Entry(T item) - { - return unitOfWorks.DbContext.Entry(item); - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEntityRegisterar.cs - -using System; -using xModels.Base; -using xDataService.Interfaces; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Providers -{ - /// - /// Base Entity Registerar ... - /// - public abstract class XBaseEntityRegisterar : IXEntityRegisterar - { - /// - /// Private Entity Types Collection ... - /// - private readonly List entityTypes = []; - - /// - /// Name ... - /// - public string Name { get; } - - protected XBaseEntityRegisterar(string name) - { - Name = name; - } - - /// - /// Add Specified Entity to Collection ... - /// - /// - /// - public void AddEntity() - where TEntity : XBaseEntity - { - entityTypes.Add(typeof(TEntity)); - } - - /// - /// Retrieve Registered Entity Types ... - /// - /// - public IEnumerable GetEntityTypes() - { - return entityTypes; - } - - /// - /// Configure Dynamic Entities ... - /// - /// - public virtual void ConfigureEntities(ModelBuilder modelBuilder) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEntityTypeConfiguration.cs - -using xModels.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xDataService.Providers -{ - /// - /// Configure an Entity Specifications ... - /// - /// - /// - public abstract class XBaseEntityTypeConfiguration : IEntityTypeConfiguration - where TEntity : XBaseEntity - { - public abstract void Configure(EntityTypeBuilder builder); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseInMemoryRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using System.Collections.Concurrent; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for InMemory Stores using - /// EF Core Capabilities ... - /// - /// - /// - public abstract class XBaseInMemoryRepository : IXBaseRepository - where TEntity : XBaseEntity - { - // - #region Props ... - private readonly XDataServiceConfiguration configuration; - private readonly IXKeyGenerator keyGenerator; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - private static readonly ConcurrentDictionary store = new ConcurrentDictionary(); - #endregion - - // - #region Constructor ... - public XBaseInMemoryRepository( - XDataServiceConfiguration configuration, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.baseRepositoryEvents = baseRepositoryEvents; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - var isSucceed = false; - - // - // Add Item to Dictionary ... - try - { - // - store[item.Id] = item; - isSucceed = true; - } - catch - { - isSucceed = false; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - - // - // Return Item ... - return item; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: item.Id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - var isSucceed = false; - if (isExists) - { - // - try - { - // - item = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - isSucceed = true; - } - catch - { - isSucceed = false; - } - } - else - { - // - try - { - // - item = await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - isSucceed = true; - } - catch - { - isSucceed = false; - } - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - if (isExists) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - else - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - } - - // - return item; - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - - // - // Notify Event ... - if ( - isValid && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isExists) - { - return null; - } - - // - var isSucceed = false; - var exists = store[id]; - - // - try - { - // - exists = exists.UpdateData( - exists, - propertyBlackList: new List { nameof(exists.Id) } - ); - store[id] = exists; - - // - isSucceed = true; - } - catch - { - isSucceed = false; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - - // - return exists; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return result; - } - - // - foreach (var item in items) - { - // - var updated = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - if (!updated.IsNullOrDefault() && !result) - { - result = true; - } - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: id, - cancellationToken: cancellationToken - ); - if (!isExists) - { - return null; - } - - // - TEntity result = null; - if (softDelete && configuration.EnableSoftDelete) - { - // - store[id].Deleted = true; - result = store[id]; - } - else - { - // - result = store[id]; - store.TryRemove(id, out _); - } - - // - return result; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TEntity item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await RemoveAsync( - item: item, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .CountAsync(cancellationToken); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .AnyAsync( - cancellationToken: cancellationToken, - predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = store.Values.AsQueryable(); - - // - // Predicate ... - if (!predicate.IsNull()) - { - result = result.Where(predicate); - } - - // - // Apply Orders ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - if (asNoTracking) - { - result = result.AsNoTracking(); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(x => GetKey(x).ToString() == id.ToString()) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync(); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - // - return await Task.Run( - () => 0, - cancellationToken - ); - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(TEntity item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref TEntity item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - TEntity item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(TEntity item) { } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) { } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) { } - #endregion - #endregion - - // - #region Others ... - public void Dispose() - { } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseMongoRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using MongoDB.Driver; -using System.Threading; -using MongoDB.Driver.Linq; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for Mongo DBs using - /// EF Core Capabilities ... - /// - /// - /// - public abstract class XBaseMongoRepository : IXBaseRepository - where T : XBaseEntity - { - // - #region Properties ... - private readonly string collectionName; - public List> bulkCollection; - public readonly IMongoCollection collection; - private readonly IXKeyGenerator keyGenerator; - public readonly XDataBaseConfiguration dbConfiguration; - public readonly XDataServiceConfiguration configuration; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - #endregion - - // - #region Constructor ... - protected XBaseMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - // - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.collectionName = collectionName - .IsNullOrEmpty() ? - typeof(T).Name : - collectionName; - this.dbConfiguration = dbConfiguration; - this.baseRepositoryEvents = baseRepositoryEvents; - - // - var client = new MongoClient(dbConfiguration.GetMongoDbURI()); - var database = client.GetDatabase(dbConfiguration.GetMongoDbDatabase()); - - // - bulkCollection = new List>(); - collection = database.GetCollection( - this.collectionName - ); - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - // Add Action model to Bulk Collection ... - bulkCollection.Add(new InsertOneModel(item)); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: GetKey(item), - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - // Add Action model to Bulk Collection ... - bulkCollection - .Add(new InsertOneModel(item)); - } - else - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, item.Id); - - // - // Add Action model to Bulk Collection ... - bulkCollection - .Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - if (isExists) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - else - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - - // - // Notify Event ... - if ( - isValid && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, id); - - // - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = false }); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return result; - } - - // - foreach (var item in items) - { - // - var updated = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - if (!updated.IsNullOrDefault() && !result) - { - result = true; - } - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Item ... - var item = await GetAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (item.IsNull()) - { - return null; - } - - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, id); - - // - // Check SoftDelete ... - if (softDelete && configuration.EnableSoftDelete) - { - // - // Set Soft Delete ... - item.Deleted = true; - - // - // Update ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - else - { - // - // Delete ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new DeleteOneModel(filter)); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // loop through items ... - foreach (var item in items) - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, item.Id); - - // - // Check Soft Delete ... - if (softDelete && configuration.EnableSoftDelete) - { - // - // Set Soft Delete ... - item.Deleted = true; - - // - // Update ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - else - { - // - // Delete ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new DeleteOneModel(filter)); - } - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .CountAsync(cancellationToken); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = collection - .AsQueryable(); - - // - // Apply Predicate ... - if (!predicate.IsNull()) - { - result = result - .Where(predicate); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - // - // Since Mongo Queryable doesnt Support Includes ... - // we ignore this ... - result = (IMongoQueryable)includeBuilder(result); - } - - // - // Apply Ordering ... - if (!orderBuilder.IsNull()) - { - result = (IMongoQueryable)orderBuilder(result); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(x => GetKey(x).ToString() == id.ToString()) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .Where(predicate) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync(); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .AnyAsync( - cancellationToken: cancellationToken, - predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Write all Bulk Models which stored inside bulkCollection ... - var result = await collection - .BulkWriteAsync( - options: null, - requests: bulkCollection, - cancellationToken: cancellationToken - ); - - // - // Clear Bulk Collection ... - bulkCollection.Clear(); - - // - // Return number of Modified Documents ... - var resultCount = (int)result.ModifiedCount + - (int)result.InsertedCount + - (int)result.DeletedCount; - - // - return resultCount; - } - catch (Exception ex) - { - // - // Log Thrown Exception ... - Console.WriteLine($"XMongo Repository Exception: {ex.Message} ..."); - - // - // Return less than zero value ... - return -1; - } - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(T item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref T item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(T item) { } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) { } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) { } - #endregion - #endregion - - // - #region Others ... - public void Dispose() { } - - public string GetPropValues(T item) - { - // - var props = item.GetType().GetProperties(); - var vals = props.Select(p => p.GetValue(p.Name)); - - // - return vals.ToJSON(); - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseRepositoryEvents.cs - -using System; -using xDataService.Models; -using System.Reactive.Linq; -using xDataService.Interfaces; -using System.Reactive.Subjects; -using System.Collections.Generic; - -namespace xDataService.Providers { - /// - /// Some Events can be Raised on Some Actions Happens on Repositories ... - /// this is the Base Events Class ... - /// - /// - public abstract class XBaseRepositoryEvents : IXBaseRepositoryEvents { - // - private readonly ISubject> onAddSubject; - private readonly ISubject> onUpdateSubject; - private readonly ISubject> onRemoveSubject; - - // - private readonly ISubject>> onAddManySubject; - private readonly ISubject>> onUpdateManySubject; - private readonly ISubject>> onRemoveManySubject; - - // - protected XBaseRepositoryEvents () { - // - onAddSubject = new ReplaySubject> (1); - onUpdateSubject = new ReplaySubject> (1); - onRemoveSubject = new ReplaySubject> (1); - - // - onAddManySubject = new ReplaySubject>> (1); - onUpdateManySubject = new ReplaySubject>> (1); - onRemoveManySubject = new ReplaySubject>> (1); - } - - // - public void AddEvent (XBaseEventModel model) => onAddSubject.OnNext (model); - - public void UpdateEvent (XBaseEventModel model) => onUpdateSubject.OnNext (model); - - public void RemoveEvent (XBaseEventModel model) => onRemoveSubject.OnNext (model); - - // - public void AddManyEvent (XBaseEventModel> model) => onAddManySubject.OnNext (model); - public void UpdateManyEvent (XBaseEventModel> model) => onUpdateManySubject.OnNext (model); - public void RemoveManyEvent (XBaseEventModel> model) => onRemoveManySubject.OnNext (model); - - // - public IObservable> OnAddObservable => onAddSubject.AsObservable (); - - public IObservable> OnUpdateObservable => onUpdateSubject.AsObservable (); - - public IObservable> OnRemoveObservable => onRemoveSubject.AsObservable (); - - // - public IObservable>> OnAddManyObservable => onAddManySubject.AsObservable (); - public IObservable>> OnUpdateManyObservable => onUpdateManySubject.AsObservable (); - public IObservable>> OnRemoveManyObservable => onRemoveManySubject.AsObservable (); - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseRepositoryService.cs - -using System; -using AutoMapper; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Interfaces; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Service Implementation which Use a Repository Patterns Implementatin - /// and provides Data Manipulation Methods using Dtos instead of Entities ... - /// - /// it can be use of following Repository Patterns Implementation: - /// - /// - /// - /// - public abstract class XBaseRepositoryService : IXBaseRepositoryService - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - /// - /// Mapper Instance ... - /// - public IMapper Mapper { get; } - - /// - /// Repository Implementation for Data Manipulations ... - /// - public IXBaseRepository Repository { get; } - - /// - /// Mapping Profile Configuration ... - /// - /// this Configuration used for Mapping TEntity to Dto and reverse ... - /// default mapping prepared on Constructing time, other custom maps - /// must handled manually if required ... - /// - public MapperConfiguration MapperConfiguration { get; } - #endregion - - // - #region Constructor ... - public XBaseRepositoryService( - IXBaseRepository repository, - IEnumerable mapperProfiles = null - ) - { - // - Repository = repository; - - // - // Preparing Mapping Configurations ... - MapperConfiguration = new MapperConfiguration(cfg => - { - // - // Add Default Profiles ... - - // - // Entity To Dto ... - cfg.CreateMap() - .ForMember(dest => dest.Deleted, opt => opt.Ignore()); - cfg.CreateMap, XQueryResult>(); - - // - // Dto to Entity ... - cfg.CreateMap() - .ForMember(dest => dest.Deleted, opt => opt.Ignore()); - cfg.CreateMap, XQueryResult>(); - - // - // Add Provided Profiles if Provided ... - // if Same Profiles Provided, here resolved ... - if (!mapperProfiles.IsNull() && - mapperProfiles.HasChild()) - { - cfg.AddProfiles(mapperProfiles); - } - }); - - // - // Make Mapper Instance using prepared Configuration ... - Mapper = MapperConfiguration.CreateMapper(); - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - public virtual async Task AddAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - // Validate ... - bool isValid = !item.IsNull(); - if (!isValid) - { - return result; - } - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.AddAsync( - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// add or update a Dto (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - // Validate ... - bool isValid = !item.IsNull(); - if (!isValid) - { - return result; - } - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.AddOrUpdateAsync( - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// add a range of new Dtos ... - /// - /// - /// - /// - /// - public virtual async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !items.IsNull() && - items.HasChild(); - if (!isValid) - { - return; - } - - // - try - { - // - var entities = Mapper.Map>(items); - - // - await Repository.AddRangeAsync( - items: entities, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { } - } - #endregion - - // - #region Update ... - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.UpdateAsync( - id: item.Id, - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// Update a range of Dtos ... - /// - /// - /// - /// - /// - public virtual async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !items.IsNull() && - items.HasChild(); - if (!result) - { - return result; - } - - // - try - { - // - var entitis = Mapper.Map>(items); - - // - result = await Repository.UpdateRangeAsync( - items: entitis, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { - result = false; - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// remove an Dto ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TDto item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.RemoveAsync( - item: entity, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// remove a range of exists Dtos ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !items.IsNull() && - items.HasChild(); - if (!isValid) - { - return; - } - - // - var entities = Mapper.Map>(items); - - // - try - { - // - await Repository.RemoveRangeAsync( - items: entities, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { } - } - #endregion - - // - #region Count ... - /// - /// count all exists Dtos ... - /// - /// - /// - /// - public virtual async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public virtual async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.PagesCountAsync( - pageSize: pageSize, - totalItems: totalItems, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - public virtual async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.GetAsync( - id: id, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - public virtual async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - IEnumerable result = Enumerable.Empty(); - - // - try - { - // - var entities = await Repository.GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entities); - } - catch - { } - - // - return result; - } - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default - ) - { - // - var entityEnumerable = Repository.GetAllAsAsyncEnumerable( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - await foreach (var entity in entityEnumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var dto = Mapper.Map(entity); - yield return dto; - } - } - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.FindOneAsync( - predicate: predicate, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - IEnumerable result = Enumerable.Empty(); - - // - try - { - // - var entities = await Repository.FindManyAsync( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entities); - } - catch - { } - - // - return result; - } - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - XQueryResult result = null; - - // - try - { - // - var entityResult = await Repository.QueryAsync( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entityResult); - } - catch - { } - - // - return result; - } - #endregion - - public virtual void Dispose() - { } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XEntityRegisterarHandlerService.cs - -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using xCommons.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Providers -{ - public class XEntityRegisterarHandlerService - { - /// - /// a Collection for Extract Registerars Services ... - /// - private readonly List registerars = []; - - /// - /// a Collection for Holding all Entity Types ... - /// - public IReadOnlyList AllEntityTypes { get; private set; } - - /// - /// Retrieve Specified Registerars Entity Types ... - /// - /// - /// - public IReadOnlyList GetEntityTypes(string[] names = null) - { - // - var items = new List(); - - // - if (!names.IsNull() && names.HasChild()) - { - // - items = [.. registerars - .Where(r => names.Contains(r.Name)) - .SelectMany(r => r.GetEntityTypes())]; - } - - // - return items.AsReadOnly(); - } - - /// - /// Load all Dynamically Registered Entities ... - /// - public void HandleRegisteredEntities() - { - // - var entityTypes = new List(); - var path = Path.Combine (AppContext.BaseDirectory); - var files = Directory.GetFiles(path, "*.dll"); - foreach (var dll in files) - { - // - // Retrieve DLL Assembly ... - var assembly = Assembly.LoadFrom(dll); - - // - // Extract Registerar Types ... - var registerarTypes = assembly - .GetExportedTypes() - .Where(t => - !t.IsAbstract && - typeof(IXEntityRegisterar).IsAssignableFrom(t)); - foreach (var registerarType in registerarTypes) - { - // - // Create Instance of Registerar Type ... - var registerar = (IXEntityRegisterar)Activator.CreateInstance(registerarType); - if (!registerar.IsNull()) - { - // - // Add Registerar Instance to Collection ... - registerars.Add(registerar); - - // - // Add Registerar Provided Entities to Collection ... - entityTypes.AddRange(registerar.GetEntityTypes()); - } - } - - // - // Converts to Readonly List ... - AllEntityTypes = entityTypes.AsReadOnly(); - } - } - - /// - /// Configure all Dynamically Registered Entities ... - /// - /// - /// - public void HandleApplyRegisteredEntitiesConfigurations( - ModelBuilder modelBuilder, - string[] names = null - ) - { - // - var selectedRegisterars = - !names.IsNull() && - names.HasChild() - ? registerars - .Where(r => names.Contains(r.Name)) - : registerars; - - // - // Loop Through Extracted Registerars ... - foreach(var registerar in selectedRegisterars) - { - // - // Configure Specified Registerars Entities ... - registerar.ConfigureEntities(modelBuilder); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XGuidKeyGenerator.cs - -using System; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Guid Key Generator ... - /// - /// - public class XGuidKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - private readonly IXSequentialGuid sequentialGuid; - - public XGuidKeyGenerator( - IXSequentialGuid sequentialGuid = null - ) - { - this.sequentialGuid = sequentialGuid; - } - - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - return await Task.Run(() => - { - // - // Check if provided SequentialGuid ... - if (sequentialGuid.IsNull()) - { - return Guid.NewGuid(); - } - else - { - return sequentialGuid.Next(); - } - }, cancellationToken: cancellationToken); - } - - public override bool IsEmpty(Guid id) - { - // - var result = id.IsNull() || id.IsDefaultGuid(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XIntKeyGenerator.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Extensions; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Int Key Generator ... - /// - /// - public class XIntKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - var items = (await repository.GetAllAsync()) - .OrderByDescending(nameof(XBaseEntity.Id)); - var last = items - .FirstOrDefault(); - - // - var result = last.IsNull() ? 1 : last.Id + 1; - - // - return result; - } - - public override bool IsEmpty(int id) - { - // - var result = id <= 0; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XKeyGenerator.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - public abstract class XKeyGenerator : IXKeyGenerator - where TEntity : XBaseEntity - { - public abstract Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ); - - public abstract bool IsEmpty(TKey id); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XLongKeyGenerator.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Extensions; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Long Key Generator ... - /// - /// - public class XLongKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - var items = (await repository.GetAllAsync()) - .OrderByDescending(nameof(XBaseEntity.Id)); - var last = items - .FirstOrDefault(); - - // - var result = last.IsNull() ? 1 : last.Id + 1; - - // - return result; - } - - public override bool IsEmpty(long id) - { - // - var result = id <= 0; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XSequentialGuid.cs - -using System; -using xDataService.Interfaces; - -namespace xDataService.Helpers -{ - /// - /// this service provide Sequential GUID mechanism for Entity Ids ... - /// - public class XSequentialGuid : IXSequentialGuid - { - private static int[] sqlOrderMap = null; - private static int[] SQLORDERMAP - { - get - { - if (sqlOrderMap == null) - { - sqlOrderMap = new int[16] { - 3, - 2, - 1, - 0, - 5, - 4, - 7, - 6, - 9, - 8, - 15, - 14, - 13, - 12, - 11, - 10 - }; - // 3 - the least significant byte in Guid ByteArray [for SQL Server ORDER BY clause] - // 10 - the most significant byte in Guid ByteArray [for SQL Server ORDERY BY clause] - } - return sqlOrderMap; - } - } - - private Guid currentGuid; - - public XSequentialGuid() - { - currentGuid = Guid.NewGuid(); - } - - public Guid GetCurrentGuid() - { - return currentGuid; - } - - public Guid Next() - { - byte[] bytes = currentGuid.ToByteArray(); - for (int mapIndex = 0; mapIndex < 16; mapIndex++) - { - int bytesIndex = SQLORDERMAP[mapIndex]; - bytes[bytesIndex]++; - if (bytes[bytesIndex] != 0) - { - break; // No need to increment more significant bytes - } - } - currentGuid = new Guid(bytes); - return currentGuid; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xDataService\Providers\XStringKeyGenerator.cs - -using System; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Guid Key Generator ... - /// - /// - - public class XStringKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - private readonly IXSequentialGuid sequentialGuid; - - public XStringKeyGenerator(IXSequentialGuid sequentialGuid = null) - { - this.sequentialGuid = sequentialGuid; - } - - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - await Task.CompletedTask; - - // - if (sequentialGuid.IsNull()) - { - return Guid.NewGuid().ToString(); - } - else - { - return sequentialGuid.Next().ToString(); - } - } - - public override bool IsEmpty(string id) - { - return id.IsNullOrEmpty(); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xDataService-20261111_120055.txt b/Documents/GeneratedContext/xDashboard-xDataService-20261111_120055.txt deleted file mode 100644 index 09b2daf..0000000 --- a/Documents/GeneratedContext/xDashboard-xDataService-20261111_120055.txt +++ /dev/null @@ -1,13507 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Builders\XRepositoryDescriptorBuilder.cs - -using xModels.Base; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.GraphQL; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Builders -{ - /// - /// Fluent Builder for constructing XRepositoryDescriptor instances. - /// Replaces the telescoping generic constructors (12-17 type parameters) - /// with a readable, chainable API. - /// - /// The entity type - /// The entity key type - /// - /// var descriptor = XRepositoryDescriptor.For<XAiMessage, Guid>() - /// .WithKeyGenerator<IXAiMessageKeyGenerator, XAiMessageKeyGenerator>() - /// .WithEvents<IXAiMessageRepositoryEvents, XAiMessageRepositoryEvents>() - /// .WithGraphQL<XAiMessageGraphType, GuidGraphType, XAiMessageGraphQuery, - /// IXAiMessageGraphQLTypeHelper, XAiMessageGraphQLTypeHelper, XAiMessageGraphSchema>() - /// .WithEFRepository<XAiApiDbContext, IXAiMessageRepository, XAiMessageEFRepository<XAiApiDbContext>>() - /// .WithSeeder<IXAiMessageSeeder, XAiMessageSeeder>() - /// .Build(); - /// - public sealed class XRepositoryDescriptorBuilder - where TEntity : XBaseEntity - { - private readonly XRepositoryDescriptor _descriptor; - - private XRepositoryDescriptorBuilder() - { - _descriptor = new XRepositoryDescriptor - { - Entity = typeof(TEntity), - Key = typeof(TKey) - }; - } - - /// - /// Creates a new builder instance for the specified entity and key types. - /// - public static XRepositoryDescriptorBuilder Create() - { - return new XRepositoryDescriptorBuilder(); - } - - // - #region KeyGenerator - /// - /// Configures the Key Generator service for the entity. - /// - /// The key generator interface - /// The key generator implementation - public XRepositoryDescriptorBuilder WithKeyGenerator() - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - _descriptor.KeyGeneratorService = typeof(TKeyGeneratorService); - _descriptor.KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - return this; - } - #endregion - - // - #region Events - /// - /// Configures the Repository Events service for the entity. - /// - /// The events interface - /// The events implementation - public XRepositoryDescriptorBuilder WithEvents() - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - _descriptor.EventsService = typeof(TEventsService); - _descriptor.EventsImplementation = typeof(TEventsImplementation); - return this; - } - #endregion - - // - #region GraphQL - /// - /// Configures the full GraphQL stack for the entity. - /// - /// The GraphQL object type - /// The GraphQL key type - /// The GraphQL query type - /// The GraphQL type helper interface - /// The GraphQL type helper implementation - /// The GraphQL schema - public XRepositoryDescriptorBuilder WithGraphQL< - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema>() - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - _descriptor.GraphType = typeof(TGraph); - _descriptor.GraphTypeKey = typeof(TGraphKey); - _descriptor.GraphQuery = typeof(TGraphQuery); - _descriptor.GraphSchema = typeof(TGraphSchema); - _descriptor.GraphTypeHelperService = typeof(TGraphTypeHelperService); - _descriptor.GraphTypeHelperImplementation = typeof(TGraphTypeHelperImplementation); - return this; - } - #endregion - - // - #region Repository - /// - /// Configures an Entity Framework Core repository for the entity. - /// - /// The EF DbContext - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithEFRepository() - where TContext : XDbContext - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseEFRepository - { - _descriptor.Context = typeof(TContext); - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - - /// - /// Configures a MongoDB repository for the entity. - /// - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithMongoRepository() - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseMongoRepository - { - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - - /// - /// Configures an In-Memory repository for the entity. - /// - /// The repository interface - /// The repository implementation - public XRepositoryDescriptorBuilder WithInMemoryRepository() - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseInMemoryRepository - { - _descriptor.RepositoryService = typeof(TRepositoryService); - _descriptor.RepositoryImplementation = typeof(TRepositoryImplementation); - return this; - } - #endregion - - // - #region Seeder - /// - /// Configures the database seeder for the entity. - /// - /// The seeder interface - /// The seeder implementation - public XRepositoryDescriptorBuilder WithSeeder() - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - { - _descriptor.SeederService = typeof(TSeederService); - _descriptor.SeederImplementation = typeof(TSeederImplementation); - return this; - } - #endregion - - // - #region Build - /// - /// Builds and returns the configured XRepositoryDescriptor. - /// - /// The fully configured descriptor - public XRepositoryDescriptor Build() - { - return _descriptor; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Configuration\XDataBaseConfiguration.cs - -using xDataService.Constants; -using System.Collections.Generic; - -namespace xDataService.Configuration -{ - /// - /// Describe a Database ... - /// - public class XDataBaseConfiguration - { - /// - /// Provider Type ... - /// - /// - public XDbProviders Provider { get; set; } - - /// - /// Connection String which provide Requires Data to Connect to Db Provider ... - /// - /// - public string ConnectionString { get; set; } - - /// - /// Holds Seeding items ... - /// nameof(TEntity) => TEntity - /// - public IDictionary> SeedItems { get; set; } = new Dictionary>(); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Configuration\XDataServiceConfiguration.cs - -using xDataService.Constants; -using System.Collections.Generic; - -namespace xDataService.Configuration -{ - /// - /// Represent Configurations of DataService Module ... - /// - public partial class XDataServiceConfiguration - { - /// - /// the base path for providing GraphQL ... - /// - /// - public string GraphQLBasePath { get; set; } = "/graphql"; - - /// - /// Data Bases Configuration ... - /// - /// - public IDictionary Databases { get; set; } = new Dictionary(); - - /// - /// Enable Soft Delete Entities or Not ... - /// - /// - public bool EnableSoftDelete { get; set; } - - /// - /// Specified Seeding Mode ... - /// - public XDbSeedingMode SeedingMode { get; set; } = XDbSeedingMode.None; - - /// - /// Enable Tracking of Entities ... - /// Only Used on EFCore ... - /// - /// - public bool EnableTracking { get; set; } = false; - - /// - /// Enable Logging Details of Errors ... - /// Only Used on EFCore ... - /// - /// - public bool EnableDetailedErrors { get; set; } = false; - - /// - /// Enable Logging Sensitive Data ... - /// Only Used on EFCore ... - /// - /// - public bool EnableSensitiveDataLogging { get; set; } = false; - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - /// - public PagingConfiguration PagingConfiguration { get; set; } = new PagingConfiguration(); - } - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - public partial class PagingConfiguration - { - /// - /// Default Page Size ... - /// - /// - public int DefaultPageSize { get; set; } = XDataServiceConstants.DEFAULT_PAGE_SIZE; - - /// - /// restrict Maximum Page Size ... - /// - /// - public int MaxAvailablePageSize { get; set; } = XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE; - - /// - /// restrice Minimum Page Size ... - /// - /// - public int MinAvailablePageSize { get; set; } = XDataServiceConstants.MIN_AVAILABLE_PAGE_SIZE; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Constants\ConfigurationNodeNames.cs - -namespace xDataService.Constants { - public partial struct ConfigurationNodeNames { - public const string DB_PROVIDER_NODE = "XDBProvider"; - public const string DATA_SERVICE_NODE = "DataServiceConfiguration"; - public const string DATA_SERVICE_DB_SEED_NODE = "DbSeeder"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Constants\XDataServiceConstants.cs - -namespace xDataService.Constants { - /// - /// Default Pagination Values ... - /// - public partial struct XDataServiceConstants { - public static int DEFAULT_PAGE_SIZE = 50; - public static int MAX_AVAILABLE_PAGE_SIZE = 500; - public static int MIN_AVAILABLE_PAGE_SIZE = 20; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Constants\XDbProviders.cs - -namespace xDataService.Constants { - /// - /// Represent Supported DBMS for Managing Data ... - /// - public enum XDbProviders { - None, - MySQL, - SQLite, - Oracle, - SQLServer, - MongoDB, - } - - /// - /// Represent Supported DBMS for Managing Data ... - /// - public partial struct ProviderType { - public const string MySQL = "MYSQL"; - public const string SQLite = "SQLITE"; - public const string Oracle = "ORACLE"; - public const string MongoDB = "MONGODB"; - public const string SQLServer = "SQLSERVER"; - } - -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Constants\XDbSeedingMode.cs - -namespace xDataService.Constants -{ - /// - /// All Seeding Data Mode ... - /// - public enum XDbSeedingMode - { - /// - /// No Seed Data ... - /// - None, - - /// - /// Seed Only New Items ... - /// - AddIfNotExists, - - /// - /// Seed Force (Add/Update) ... - /// - AddOrUpdate, - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Constants\XRepositoryType.cs - -using xExceptions.Attributes; - -namespace xDataService.Constants -{ - public enum XRepositoryType - { - [StringValue("EF")] - EF, - - [StringValue("Mongo")] - Mongo, - - [StringValue("InMemory")] - InMemory - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Controllers\XBaseRepositoryController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xDataService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Controllers -{ - /// - /// an Abstract Controller for Providing Entity Repository Actions Implementatin ... - /// - /// - /// - [AllowAnonymous] - public abstract class XBaseRepositoryController : XBaseApiV1Controller, IXBaseRepositoryController - where TEntity : XBaseEntity - { - // - #region Properties ... - public IXBaseRepository Repository { get; } - - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Constructor ... - protected XBaseRepositoryController( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXBaseRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - // - Repository = repository; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await Repository - .AddAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - public virtual async Task> AddOrUpdate( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await Repository - .AddOrUpdateAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - public virtual async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await Repository - .AddRangeAsync( - request.Items, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .GetAsync( - id, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Get Result ... - var result = await Repository - .GetAllAsync( - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await Repository - .FindOneAsync( - predicate: t => - t.PropValuesContains(query), - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await Repository - .FindManyAsync( - predicate: t => - t.PropValuesContains(query), - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - - // - // Get Result ... - var result = await Repository - .QueryAsync( - query: query, - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id, item) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await Repository - .UpdateAsync( - id: id, - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - public virtual async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await Repository - .UpdateRangeAsync( - saveChanges: true, - items: request.Items, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await Repository - .RemoveAsync( - id: id, - saveChanges: true, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - public virtual async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await Repository - .RemoveRangeAsync( - saveChanges: true, - items: request.Items, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Controllers\XBaseServiceController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xDataService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Controllers -{ - /// - /// an Abstract Controller for Providing Entity Dto Repository Service Actions Implementatin ... - /// - /// - /// - /// - [AllowAnonymous] - public abstract class XBaseServiceController : XBaseApiV1Controller, IXBaseServiceController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - public IXBaseRepositoryService RepositoryService { get; } - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Constructor ... - protected XBaseServiceController( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXBaseRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - // - RepositoryService = repositoryService; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await RepositoryService - .AddAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - public virtual async Task> AddOrUpdate( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - // Get Result ... - var result = await RepositoryService - .AddOrUpdateAsync( - item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - public virtual async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await RepositoryService - .AddRangeAsync( - request.Items, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .GetAsync( - id, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Get Result ... - var result = await RepositoryService - .GetAllAsync( - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await RepositoryService - .FindOneAsync( - predicate: t => - t.PropValuesContains(query), - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(query); - - // - // Get Result ... - var result = await RepositoryService - .FindManyAsync( - predicate: t => - t.PropValuesContains(query), - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - - // - // Get Result ... - var result = await RepositoryService - .QueryAsync( - query: query, - orderBuilder: useDefaultOrders - ? DefaultOrderBuilder - : null, - includeBuilder: useDefaultIncludes - ? DefaultIncludeBuilder - : null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id, item) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await RepositoryService - .UpdateAsync( - id: id, - item: item, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - public virtual async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await RepositoryService - .UpdateRangeAsync( - saveChanges: true, - items: request.Items, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - ValidationProvider.NotNull(id); - - // - // Get Result ... - var result = await RepositoryService - .RemoveAsync( - id: id, - saveChanges: true, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - public virtual async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotZeroChilds(request.Items) - .ValidateGroupAsync(); - - // - // Get Result ... - await RepositoryService - .RemoveRangeAsync( - saveChanges: true, - items: request.Items, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Db\XDbContext.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xDataService.Providers; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Db -{ - /// - /// Provide an abstraction layout arround DBContext ... - /// Only Used on EFCore ... - /// - public abstract class XDbContext : DbContext - { - // - #region Properties ... - private readonly string database; - private readonly XDataServiceConfiguration config; - private readonly string[] dynamicEntityRegisterarsNames; - private readonly XEntityRegisterarHandlerService dynamicEntityHandlers; - #endregion - - // - #region Entities ... - // - // Register Default and Base Entities ... - #endregion - - // - #region Constructor ... - public XDbContext( - string database, - DbContextOptions options, - XDataServiceConfiguration config, - XEntityRegisterarHandlerService dynamicEntityHandlers, - string[] dynamicEntityRegisterarsNames = null - ) : base(options) - { - // - try - { - Database.EnsureCreated(); - Database.Migrate(); - } - catch { } - - // - this.config = config; - this.database = database; - this.dynamicEntityHandlers = dynamicEntityHandlers; - this.dynamicEntityRegisterarsNames = dynamicEntityRegisterarsNames; - - // - // Handling DbSets of Dynamic Entities ... - if (!dynamicEntityHandlers.IsNull()) - { - // - // Configure XEntityRegisterarHandlerService ... - dynamicEntityHandlers.HandleRegisteredEntities(); - - // - // Loop through Entity Types ... - foreach (var entityType in dynamicEntityHandlers.GetEntityTypes(dynamicEntityRegisterarsNames)) - { - // - try - { - // - // Use reflection to call Set() - var method = typeof(XDbContext) - .GetMethod(nameof(XDbContext.Set), Type.EmptyTypes) - .MakeGenericMethod(entityType); - if (!method.IsNull()) - { - method.Invoke(this, null); - } - } - catch { } - } - } - } - #endregion - - /// - /// Extract Current Database Configuration ... - /// - /// - public XDataBaseConfiguration GetDatabaseConfiguration() - { - // - XDataBaseConfiguration result = - config.Databases.FirstOrDefault(db => string - .Equals(db.Key, database, StringComparison.InvariantCultureIgnoreCase)).Value; - - // - return result; - } - - // - #region Overrides ... - // - // Prepare Model Configs ... - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - // - OnXModelCreating(modelBuilder); - - // - // Automatically apply all IEntityTypeConfiguration in this assembly - modelBuilder.ApplyConfigurationsFromAssembly(typeof(XDbContext).Assembly); - - // - // Check Dynamic Registered Service is Exists or not ... - if (!dynamicEntityHandlers.IsNull()) - { - // - // Set Entity of Dynamically Registered Entities ... - foreach (var entityType in dynamicEntityHandlers.GetEntityTypes(dynamicEntityRegisterarsNames)) - { - modelBuilder.Entity(entityType); - } - - // - // Configure Entity using Provided Registerar ... - dynamicEntityHandlers - .HandleApplyRegisteredEntitiesConfigurations(modelBuilder, dynamicEntityRegisterarsNames); - } - - // - // Since this class inherit from Identity Db Context, - // we have to pass this to Building Identity Models ... - base.OnModelCreating(modelBuilder); - } - - // - // Prepare Configuring ... - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - // - if (config.EnableDetailedErrors) - { - optionsBuilder.EnableDetailedErrors(); - } - - // - if (config.EnableSensitiveDataLogging) - { - optionsBuilder.EnableSensitiveDataLogging(); - } - - // - if (config.EnableTracking) - { - optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll); - } - else - { - optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); - } - - // - OnXConfiguring(optionsBuilder); - - // - base.OnConfiguring(optionsBuilder); - } - #endregion - - // - #region Abstracts ... - // - public abstract void OnXModelCreating(ModelBuilder modelBuilder); - - // - public abstract void OnXConfiguring(DbContextOptionsBuilder optionsBuilder); - #endregion - - // - #region Dynamic DbSet(s) ... - public override DbSet Set() - where TEntity : class - { - return base.Set(); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Db\XUnitOfWorks.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Db { - /// - /// Provide Unit Of Works Design Pattern for Db Transactions ... - /// Only Used on EFCore ... - /// - /// - public class XUnitOfWorks : IXUnitOfWorks - where TDbContext : XDbContext { - public TDbContext DbContext { get; } - - public XUnitOfWorks (TDbContext context) { - this.DbContext = context; - } - - public DbSet GetDbSet () - where T : XBaseEntity { - return DbContext.Set (); - } - - /// - /// Save Changes - /// - public int SaveChanges () { - return DbContext.SaveChanges (); - } - - /// - /// Save Changes Async - /// - /// - /// - public async Task SaveChangesAsync ( - CancellationToken cancellationToken = default - ) { - return await DbContext.SaveChangesAsync (cancellationToken); - } - - public void Dispose () { - DbContext.Dispose (); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xDataService.Providers; -using xDataService.Extensions; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace xDataService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Retrive XDataService Configurations - /// - /// - /// - public static XDataServiceConfiguration GetXDataServiceConfiguration( - this IConfiguration source - ) - { - // - var xDataServiceConfigSection = source - .GetSection(ConfigurationNodeNames.DATA_SERVICE_NODE); - var result = xDataServiceConfigSection.Get(); - - // - // Reading Seeders ... - if (!result.IsNull() && - result.Databases.HasChild()) - { - // - result - .Databases - .ToList() - .ForEach(db => - { - // - var seedItemsSectionName = $"{ConfigurationNodeNames.DATA_SERVICE_NODE}:{nameof(XDataServiceConfiguration.Databases)}:{db.Key}:{nameof(XDataBaseConfiguration.SeedItems)}"; - var section = source.GetSection(seedItemsSectionName); - var sectionJson = source.GetSectionAsJson(seedItemsSectionName); - var sectionDict = sectionJson.FromJSON>>(); - if (!sectionDict.IsNull() && - sectionDict.Values.HasChild()) - { - // - sectionDict - .Keys - .ToList() - .ForEach(entity => - { - // - // Setting Values to Result ... - result.Databases[db.Key].SeedItems[entity] = sectionDict[entity]; - }); - } - }); - } - - // - return result; - } - - /// - /// Register XDataService Configuration ... - /// - /// - /// - public static void AddXDataServiceConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXDataServiceConfiguration(); - if (config.IsNullOrDefault()) - { - // - Log("Configurations Not Founded ..."); - XException.NotFound.Throw(); - } - - // - source.AddSingleton(config); - } - - /// - /// Register XDataService Configuration ... - /// - /// - /// - public static void AddXDataServiceConfiguration( - this IServiceCollection source, - XDataServiceConfiguration configuration - ) - { - // - if (configuration.IsNullOrDefault()) - { - // - Log("Configurations Not Founded ..."); - XException.NotFound.Throw(); - } - - // - source.AddSingleton(configuration); - } - - /// - /// Register a Data Base using Descriptor ... - /// - /// - /// - /// - /// - public static void AddXDatabase( - this IServiceCollection source, - IConfiguration configuration, - XDatabaseDescriptor descriptor, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Validate Database Descriptor ... - var isValid = - !descriptor.IsNullOrDefault() && - !descriptor.Name.IsNullOrEmpty(); - if (!isValid) - { - // - Log("Invalid Database Descriptor ..."); - return; - } - - // - // Check Service Collection Validation ... - isValid = - !source.IsNull() && - !configuration.IsNull(); - if (!isValid) - { - // - Log("Invalid Service Provider or Configuration ..."); - return; - } - - // - // Get Registere Data Service Configuration ... - var xDataServiceConfiguration = source - .GetRegisteredService(); - isValid = !xDataServiceConfiguration.IsNullOrDefault(); - if (!isValid) - { - // - // Extract Configuration from Configuration ... - xDataServiceConfiguration = configuration.GetXDataServiceConfiguration(); - isValid = !xDataServiceConfiguration.IsNullOrDefault(); - if (!isValid) - { - // - Log("DataService Configuration not provided ..."); - return; - } - - // - // Register Configuration in DI ... - source.AddSingleton(xDataServiceConfiguration); - } - - // - // Check Data Service Configuration has Database ... - isValid = - !xDataServiceConfiguration.Databases.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Contains(descriptor.Name); - if (!isValid) - { - // - Log("Invalid Database Descriptor ..."); - return; - } - - // - // Register Handler Service ... - source.AddSingleton(); - - // - // Configure Database Descriptor ... - descriptor.Configure(source); - - // - // Register Context ... - if (!descriptor.Context.IsNull() && - descriptor.Provider != XDbProviders.None && - !descriptor.ConnectionString.IsNullOrEmpty()) - { - // - try - { - // - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "AddXDbContext", - runtimeType: descriptor.Context, - args: [ - source, - descriptor, - lifeTime - ] - ); - - // - Log($"DbContext: {descriptor.Name} Registered Successfully ..."); - } - catch (Exception ex) - { - Log($"DbContext: {descriptor.Name} Registration failed due {ex.Message} ..."); - } - } - - // - // Register Repositories ... - if (!descriptor.Repositories.IsNull() && - descriptor.Repositories.HasChild()) - { - // - descriptor.Repositories.ToList().ForEach(r => - { - // - source.AddXRepository( - descriptor: r, - lifeTime: lifeTime - ); - }); - } - } - - public static void AddXRepository( - this IServiceCollection source, - XRepositoryDescriptor descriptor, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Preparing Runtime Types ... - Type[] runtimeTypes = descriptor.GetType().GenericTypeArguments; - - // - try - { - // - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "AddXRepository", - runtimeTypes: runtimeTypes, - args: [ - source, - descriptor, - lifeTime - ] - ); - - // - Log($"Repository of: {runtimeTypes[0]}, Registered Successfully ..."); - } - catch (Exception ex) - { - Log($"Repository of: {runtimeTypes[0]}, Registration failed due {ex.Message} ..."); - } - } - - public static void UseXDatabase( - this IApplicationBuilder source, - XDatabaseDescriptor descriptor, - bool isDevelopmentEnvironment = false - ) - { - // - // Validate ... - var isValid = - !source.IsNull() && - descriptor.IsValid(); - if (!isValid) - { - // - Log("Invalid Database Configuration ..."); - XException.InvalidArgs.Throw(); - } - - // - // Check Repositories Exists ... - isValid = descriptor.HasRepositories(); - if (isValid) - { - // - // Loop through Repositories ... - descriptor.Repositories - .ToList() - .ForEach(r => - { - // - source.UseXRepository( - descriptor: r, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - }); - } - } - - /// - /// Use a Repository Middlewares by Providing it's Descriptor ... - /// - /// - /// - /// - public static void UseXRepository( - this IApplicationBuilder source, - XRepositoryDescriptor descriptor, - bool isDevelopmentEnvironment = false - ) - { - // - Log($"Start Using Repository of: {descriptor.Entity}"); - - // - var withPlayground = false; - if (isDevelopmentEnvironment) - { - withPlayground = true; - } - - // - // Create an Scope for Services Acces ... - using (var scope = source.ApplicationServices.CreateScope()) - { - // - // Inject XDataServiceConfiguration ForMake Sure DataService Registration ... - var dataServiceConfiguration = scope.ServiceProvider.GetService(); - var isValid = !dataServiceConfiguration.IsNullOrDefault(); - if (isValid) - { - // - // Check Seeder Exists ... - // Execute Seeding Data Task if Exists ... - isValid = descriptor.HasSeeder(); - if (isValid) - { - // - var seeder = (dynamic)scope.ServiceProvider.GetService(descriptor.SeederService); - isValid = seeder != null; - if (isValid) - { - // - Log($"Start Seeding {descriptor.Entity} ..."); - - // - // Seeding ... - seeder - .Seed() - .GetAwaiter() - .GetResult(); - } - } - - // - // Check GraphQL Support ... - isValid = descriptor.HasGraphSupport(); - if (isValid) - { - // - // Use WebSockets ... - source.UseWebSockets(); - - // - // Inject GraphQL Type Helper ... - var helper = (dynamic)scope.ServiceProvider.GetService(descriptor.GraphTypeHelperService); - isValid = helper != null; - if (isValid) - { - // - var graphPath = $"{helper.GetGraphQLPath()}"; - var graphBasePath = $"{dataServiceConfiguration.GraphQLBasePath}"; - typeof(XDataServiceHelper).InvokeGenericMethod( - methodName: "UseXGraphQL", - runtimeTypes: [ - descriptor.Entity, - descriptor.Key, - descriptor.GraphType, - descriptor.GraphTypeKey, - descriptor.GraphQuery, - descriptor.GraphTypeHelperService, - descriptor.GraphTypeHelperImplementation, - descriptor.GraphSchema - ], - args: [ - source, - graphBasePath, - graphPath, - withPlayground - ] - ); - - // - Log($"Register GraphQL: {graphPath}"); - } - } - } - } - } - - // - #region Private ... - /// - /// a LogTag for xDataService ... - /// - private static string XLogTag = "xDataService"; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\DbContextOptionExtensions.cs - -using System; -using MySql.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace xDataService.Extensions { - public static class DbContextOptionExtensions { - /// - /// convert dynamic object to MySqlDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToMySQLDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - - /// - /// convert dynamic object to SqliteDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToSqliteDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - - /// - /// convert dynamic object to SqlServerDbContextOptionBuilder ... - /// Only Used in EFCore ... - /// - /// - /// - public static Action ToSqlServerDbContextOptionsBuilder ( - this Action source - ) { - return ((Action) source); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\EntityExtensions.cs - -using System; -using System.Linq; -using xModels.Base; -using xCommons.Extensions; -using System.Linq.Expressions; -using System.Collections.Generic; - -namespace xDataService.Extensions { - public static class EntityExtensions { - /// - /// return all values of an entity properties as a json string ... - /// - /// - /// - /// - public static string GetPropValues (this T item) - where T : XBaseEntity { - // - var props = item.GetType ().GetProperties (); - var vals = props.Select (p => p.GetValue (item)); - - // - return vals.ToJSON (); - } - - /// - /// check values of all properties of an Entity contains specific value or not ... - /// - /// - /// - /// - /// - public static bool PropValuesContains (this T item, string value) - where T : XBaseEntity => item.GetPropValues () - .ToNormalString () - .Contains (value); - - /// - /// Retrieve Default Column Map of specific Entity ... - /// - /// - /// - /// - public static IDictionary>> GetDefaultColumnsMap (this T item) - where T : XBaseEntity { - // - if (item.IsNull ()) { - return null; - } - - // - var result = new Dictionary>> (); - var props = item.GetType ().GetProperties (); - - // - foreach (var prop in props) { - result.Add ( - prop.Name, - t => t.GetType ().GetProperty (prop.Name).GetValue (t, null)); - } - - // - return result; - } - - /// - /// Check a Type is XBaseEntity or not ... - /// - /// - /// - public static bool IsXEntity(this Type source) - { - // - var result = !source.IsNull(); - if (!result) - { - return result; - } - - // - var baseType = source.BaseType; - while(!baseType.IsNull() && baseType != typeof(object)) - { - // - if (baseType.IsGenericType && - baseType.GetGenericTypeDefinition() == typeof(XBaseEntity<>)) - { - result = true; - break; - } - - // - baseType = baseType.BaseType; - } - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\IQueryableExtensions.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Reflection; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xDataService.Constants; -using System.Linq.Expressions; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Extensions -{ - public static class IQueryableExtensions - { - /// - /// Apply Search Filter on a Query - /// - /// - /// - /// - /// - /// - public static IQueryable ApplyFilter( - this IQueryable source, - string filter - ) - where T : XBaseEntity - { - // - // Apply Filter ... - return source.Where(r => r.PropValuesContains(filter)); - } - - /// - /// Apply Search Filter on a Query - /// - /// - /// - /// - /// - /// - public static async Task> ApplyFilterAsync( - this IQueryable source, - string filter - ) - where T : XBaseEntity - { - // - // Where Clause ... - Expression> whereClause = r => r - .PropValuesContains(filter); - - // - // Generate Where Function ... - var whereFunc = whereClause.Compile(); - - // - // Get Enumerable ... - var enumerator = source - .AsAsyncEnumerable(); - - // - var result = new List(); - await - foreach (var entity in enumerator) - { - // - var isApproved = whereFunc(entity); - if (isApproved) - { - result.Add(entity); - } - } - - // - return result.AsQueryable(); - } - - /// - /// Apply Search Filter on a Enumerable - /// - /// - /// - /// - /// - /// - public static async Task> ApplyFilterAsync( - this IEnumerable source, - string filter - ) - where T : XBaseEntity - { - // - // Where Clause ... - Expression> whereClause = r => r - .PropValuesContains(filter); - - // - // Generate Where Function ... - var whereFunc = whereClause.Compile(); - - // - // Get Enumerable ... - var enumerator = source - .ToList() - .AsQueryable(); - - // - var result = new List(); - foreach (var entity in enumerator) - { - // - var isApproved = whereFunc(entity); - if (isApproved) - { - result.Add(entity); - } - } - - // - return result - .AsEnumerable(); - } - - /// - /// Apply Search Filter on a Enumerable - /// - /// - /// - /// - /// - public static IEnumerable ApplyFilter( - this IEnumerable source, - string filter - ) - where T : class - { - // - // Apply Filter ... - return source.Where(r => r.PropValuesContains(filter)); - } - - /// - /// provide a way to Order an IQueryable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedQueryable OrderBy( - this IQueryable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - - // - // Create x => x.PropName - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - ParameterExpression arg = Expression.Parameter(entityType, "x"); - MemberExpression property = Expression.Property(arg, propertyName); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); - - // - // Get System.Linq.Queryable.OrderBy() method. - var enumarableType = typeof(System.Linq.Queryable); - var method = enumarableType.GetMethods() - .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition) - .Where(m => - { - // - var parameters = m.GetParameters().ToList(); - - // - // Put more restriction here to ensure selecting the right overload - return parameters.Count == 2; // overload that has 2 parameters - }).Single(); - - // - // The linq's OrderBy has two generic types, which provided here ... - MethodInfo genericMethod = method - .MakeGenericMethod(entityType, propertyInfo.PropertyType); - - /* - Call query.OrderBy(selector), with query and selector: x=> x.PropName - Note that we pass the selector as Expression to the method and we don't compile it. - - By doing so EF can extract "order by" columns and generate SQL for it. - */ - var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, selector }); - - // - return newQuery; - } - - /// - /// provide a way to Order an IEnumerable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedEnumerable OrderBy( - this IEnumerable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - return query.OrderBy(x => propertyInfo.GetValue(x, null)); - } - - /// - /// provide a way to Order an IQueryable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedQueryable OrderByDescending( - this IQueryable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - - // - // Create x => x.PropName - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - ParameterExpression arg = Expression.Parameter(entityType, "x"); - MemberExpression property = Expression.Property(arg, propertyName); - var selector = Expression.Lambda(property, new ParameterExpression[] { arg }); - - // - // Get System.Linq.Queryable.OrderBy() method. - var enumarableType = typeof(System.Linq.Queryable); - var method = enumarableType.GetMethods() - .Where(m => m.Name == "OrderByDescending" && m.IsGenericMethodDefinition) - .Where(m => - { - // - var parameters = m.GetParameters().ToList(); - - // - // Put more restriction here to ensure selecting the right overload - return parameters.Count == 2; // overload that has 2 parameters - }).Single(); - - // - // The linq's OrderBy has two generic types, which provided here ... - MethodInfo genericMethod = method - .MakeGenericMethod(entityType, propertyInfo.PropertyType); - - /* - Call query.OrderBy(selector), with query and selector: x=> x.PropName - Note that we pass the selector as Expression to the method and we don't compile it. - - By doing so EF can extract "order by" columns and generate SQL for it. - */ - var newQuery = (IOrderedQueryable)genericMethod - .Invoke(genericMethod, new object[] { query, selector }); - - // - return newQuery; - } - - /// - /// provide a way to Order an IEnumerable by string FieldName ... - /// - /// - /// - /// - /// - public static IOrderedEnumerable OrderByDescending( - this IEnumerable query, - string propertyName - ) - { - // - var entityType = typeof(TSource); - var propertyInfo = entityType.GetProperty(propertyName); - if (propertyInfo.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - return query.OrderByDescending(x => propertyInfo.GetValue(x, null)); - } - - /// - /// Apply Sorting on a query - /// - /// - /// - /// - /// - /// - /// - /// - public static IQueryable ApplySorting( - this IQueryable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : XBaseEntity - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Sorting on a query - /// - /// - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplySorting( - this IEnumerable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : XBaseEntity - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Sorting on a Enumerable - /// - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplySorting( - this IEnumerable source, - string sortBy, - bool isAscending, - IDictionary>> columnsMap = null - ) - where T : class - { - // - if (columnsMap == null) - { - // - columnsMap = source.FirstOrDefault() - .GetDefaultColumnsMap(); - - // - if (columnsMap == null) - { - return source; - } - } - - // - // Validate SortBy ... - var sortByItem = columnsMap.Keys - .FirstOrDefault(p => - p.ToNormalString() == sortBy.ToNormalString()); - if (sortByItem.IsNullOrEmpty()) - { - return source; - } - - // - // Apply Sorting ... - if (isAscending) - { - return source.OrderBy(sortByItem); - } - else - { - return source.OrderByDescending(sortByItem); - } - } - - /// - /// Apply Paging on a qury - /// - /// - /// - /// - /// - /// - public static IQueryable ApplyPaging( - this IQueryable source, - int? page, - int? pageSize - ) - { - // - if (!page.HasValue || - page <= 0) - { - page = 1; - } - - // - if (!pageSize.HasValue || - pageSize <= 0 || - pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE) - { - pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE; - } - - // - var pageVal = page.GetValueOrDefault(); - var pageSizeVal = pageSize.GetValueOrDefault(); - - // - return source - .Skip((pageVal - 1) * pageSizeVal) - .Take(pageSizeVal); - } - - /// - /// Apply Paging on a Enumerable - /// - /// - /// - /// - /// - /// - public static IEnumerable ApplyPaging( - this IEnumerable source, - int? page, - int? pageSize - ) - { - // - if (!page.HasValue || - page <= 0) - { - page = 1; - } - - // - if (!pageSize.HasValue || - pageSize <= 0 || - pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE) - { - pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE; - } - - // - var pageVal = page.GetValueOrDefault(); - var pageSizeVal = pageSize.GetValueOrDefault(); - - // - return source - .Skip((pageVal - 1) * pageSizeVal) - .Take(pageSizeVal); - } - - /// - /// Count Query Pages based on Specified Total Number ... - /// - /// - /// - /// - public static int CountPages(this XQuery source, int totalItems) - { - // - int result = 0; - - // - // Validate and Calculate ... - if (!source.IsNull() && source.PageSize > 0 && totalItems > 0) - { - // - result = totalItems / source.PageSize; - if (totalItems % source.PageSize > 0) - { - result++; - } - } - - // - return result; - } - - /// - /// Normalize an XQuery based on Data Service Configurations ... - /// - /// - /// - /// - public static XQuery NormalizeQuery( - this XQuery source, - XDataServiceConfiguration configuration // - ) - { - // - if (source.IsNull()) - { - source = new XQuery(); - } - - // - // Page Size Normalization ... - if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize; - } - if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize; - } - - // - return source; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XDatabaseDescriptorExtensions.cs - -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Constants; - -namespace xDataService.Extensions -{ - public static class XDatabaseDescriptorExtensions - { - /// - /// Validate a Database Descriptor ... - /// - /// - /// - public static bool IsValid(this XDatabaseDescriptor source) - { - // - var result = - !source.IsNull() && - !source.Name.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Chack a Descriptor Has Provider or not ... - /// - /// - /// - public static bool HasProvider(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.Provider != XDbProviders.None; - - // - return result; - } - - /// - /// Check a Descriptor Has EF Core Context or not ... - /// - /// - /// - public static bool HasContext(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - source.Provider != XDbProviders.MongoDB && - !source.Context.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Repositories or not ... - /// - /// - /// - public static bool HasRepositories(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - !source.Repositories.IsNull() && - source.Repositories.HasChild(); - - // - return result; - } - - /// - /// Check a Descriptor Has MongoDB Convention Packs ... - /// - /// - /// - public static bool HasConventionPacks(this XDatabaseDescriptor source) - { - // - var result = - source.IsValid() && - source.HasProvider() && - source.Provider == XDbProviders.MongoDB && - !source.ConventionPacks.IsNull(); - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XDataServiceConfigurationExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Constants; -using xDataService.Configuration; - -namespace xDataService.Extensions { - public static class XDataServiceConfigurationExtensions { - /// - /// Extract Provider enum from Provider Type ... - /// - /// - /// - public static XDbProviders ToDbProvider (this string source) { - // - if (source.IsNullOrEmpty ()) { - return XDbProviders.None; - } - - // - source = source.ToNormalString (); - - // - var result = source == ProviderType.MySQL.ToNormalString () ? - XDbProviders.MySQL : - source == ProviderType.SQLite.ToNormalString () ? - XDbProviders.SQLite : - source == ProviderType.SQLServer.ToNormalString () ? - XDbProviders.SQLServer : - source == ProviderType.MongoDB.ToNormalString () ? - XDbProviders.MongoDB : - XDbProviders.None; - - // - return result; - } - - /// - /// Retrieve Mongo URI from ConnectionString - /// - /// - /// - public static string GetMongoDbURI (this XDataBaseConfiguration source) { - // - var parts = source.GetConnectionParts (); - var result = parts - .Where (p => p.Trim ().StartsWith ("Uri=")) - .FirstOrDefault (); - result = result.Replace ("Uri=", "").Trim (); - - // - return result; - } - - /// - /// Retrieve Mongo Database Name from Connaction string - /// - /// - /// - public static string GetMongoDbDatabase (this XDataBaseConfiguration source) { - // - var parts = source.GetConnectionParts (); - var result = parts - .Where (p => p.Trim ().StartsWith ("Database=")) - .FirstOrDefault (); - result = result.Replace ("Database=", "").Trim (); - - // - return result; - } - - // - #region Private ... - private static string[] GetConnectionParts (this XDataBaseConfiguration source) { - // - var result = source.ConnectionString.Split (';'); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XGraphQLExtensions.cs - -using GraphQL; -using xModels.Dtos; -using GraphQL.Types; -using xDataService.Constants; - -namespace xDataService.Extensions { - public static class XGraphQLExtensions { - public static TKey GetIdArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.GetIdArgument().Name); - } - - public static bool GetIgnoreSoftDeletedArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.IgnoreSoftDeletedArgument.Name); - } - - public static string GetSearchQueryArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.SearchQueryArgument.Name); - } - - public static XQuery GetQueryArgument (this IResolveFieldContext source) { - return source.GetArgument (XGraphQLHelper.QueryArgument.Name); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XMongoDbExtensions.cs - -using System; -using System.Linq; -using MongoDB.Bson; -using MongoDB.Driver; -using xDataService.Mongo; -using MongoDB.Driver.Linq; -using System.Collections.Generic; - -namespace xDataService.Extensions { - public static class XMongoDbExtensions { - public static Guid ToGuid (this ObjectId source) { - // - var bytes = source - .ToByteArray () - .Concat (new byte[] { 5, 5, 5, 5 }) - .ToArray (); - - // - var result = new Guid (bytes); - - // - return result; - } - - public static ObjectId ToObjectId (this Guid source) { - // - var bytes = source - .ToByteArray () - .Take (12) - .ToArray (); - - // - var result = new ObjectId (bytes); - - // - return result; - } - - public static IAsyncEnumerable ToAsyncEnumerable (this IAsyncCursorSource asyncCursorSource) { - return new XAsyncEnumerableAdapter (asyncCursorSource); - } - - public static async IAsyncEnumerable ToAsyncEnumerable (this IAsyncCursor source) { - while (await source.MoveNextAsync ()) { - foreach (var current in source.Current) { - yield return current; - } - } - } - - public static XMongoAsyncCursor ToAsyncCursor (this IQueryable source) { - return new XMongoAsyncCursor (source); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XReferenceExtensions.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using System.ComponentModel; -using System.Collections.Generic; - -namespace xDataService.Extensions -{ - public static class XReferenceExtensions - { - /// - /// Converts an XReference to String Representation ... - /// - /// - /// - /// - /// - public static string ToXReferenceString( - this XReference source, - char? splitter = '_' - ) - { - // - var result = string.Empty; - - // - // Normalize Splitter ... - if (!splitter.HasValue) - { - splitter = '_'; - } - - // - if (!source.IsNullOrDefault() && source.Index >= 0 && !source.ReferencedTo.IsNull()) - { - result = $"{source.ProvidedFor}{splitter.Value}{source.ReferencedTo}{splitter.Value}{source.Index}"; - } - - // - return result; - } - - /// - /// Parse an String and Extract to XReference if it's Described ... - /// - /// - /// - /// - /// - public static XReference FromXReference( - this string source, - char? splitter = '_' - ) - { - // - XReference result = null; - - // - // Normalize Splitter ... - if (!splitter.HasValue) - { - splitter = '_'; - } - - // - if (!source.IsNullOrEmpty()) - { - // - var parts = source.Split(splitter.Value); - if (parts.Count() >= 3) - { - // - T referencedTo; - try - { - referencedTo = (T)Convert.ChangeType(parts[1], typeof(T)); - } - catch - { - referencedTo = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(parts[1]); - } - - // - // Parse String Parts ... - result = new XReference - { - ReferencedTo = referencedTo, - Index = (int)Convert.ChangeType(parts[2], typeof(int)), - ProvidedFor = (string)Convert.ChangeType(parts[0], typeof(string)), - }; - } - } - - // - return result; - } - - /// - /// Converts a Collection of XReference to it's String Representation ... - /// - /// - /// - /// - public static string ToXReferenceString(this IEnumerable> source) - { - // - var result = string.Empty; - - // - if (!source.IsNull() && source.HasChild()) - { - // - var stringList = new List(); - foreach (var s in source) - { - // - var sr = ToXReferenceString(s); - if (!sr.IsNullOrEmpty()) - { - stringList.Add(sr); - } - } - - // - result = stringList.ToListString(); - } - - // - return result; - } - public static string ToXReferenceString(this ICollection> source) - { - // - var result = source - .AsEnumerable() - .ToXReferenceString(); - - // - return result; - } - public static string ToXReferenceString(this IList> source) - { - // - var result = source - .AsEnumerable() - .ToXReferenceString(); - - // - return result; - } - - /// - /// Parse an string to XReference Collection Representation ... - /// - /// - /// - /// - public static IList> ParseXReferenceList(this string source) - { - // - var result = new List>(); - - // - if (!source.IsNullOrEmpty()) - { - // - var stringList = source.ParseListString(); - if (!stringList.IsNull() && stringList.HasChild()) - { - // - foreach (var s in stringList) - { - // - var sr = FromXReference(s); - if (!sr.IsNullOrDefault()) - { - result.Add(sr); - } - } - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Extensions\XRepositoryDescriptorExtensions.cs - -using xModels.Base; -using xDataService.Db; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Extensions -{ - public static class XRepositoryDescriptorExtensions - { - // - #region Hasers ... - /// - /// Validate a Descriptor ... - /// - /// - /// - public static bool IsValid(this XRepositoryDescriptor source) - { - var result = - !source.IsNull() && - !source.Key.IsNull() && - !source.Entity.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Events Service or not ... - /// - /// - /// - public static bool HasEvents(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.EventsService.IsNull() && - !source.EventsImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has EF Core Context or not ... - /// - /// - /// - public static bool HasContext(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.Context.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has GraphQL Support or not ... - /// - /// - /// - public static bool HasGraphSupport(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - source.HasRepository() && - !source.GraphType.IsNull() && - !source.GraphQuery.IsNull() && - !source.GraphSchema.IsNull() && - !source.GraphTypeKey.IsNull() && - !source.GraphTypeHelperService.IsNull() && - !source.GraphTypeHelperImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Key Generator Service or not ... - /// - /// - /// - public static bool HasKeyGenerator(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.KeyGeneratorService.IsNull() && - !source.KeyGeneratorImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Repository Service or not ... - /// - /// - /// - public static bool HasRepository(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - !source.RepositoryService.IsNull() && - !source.RepositoryImplementation.IsNull(); - - // - return result; - } - - /// - /// Check a Descriptor Has Seeder or not ... - /// - /// - /// - public static bool HasSeeder(this XRepositoryDescriptor source) - { - // - var result = - source.IsValid() && - source.HasRepository() && - !source.SeederService.IsNull() && - !source.SeederImplementation.IsNull(); - - // - return result; - } - #endregion - - // - #region Builders ... - public static XRepositoryDescriptor AddEntity( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - { - // - if (source.IsNull()) - { - source = new XRepositoryDescriptor(); - } - - // - source.Key = typeof(TKey); - source.Entity = typeof(TEntity); - - // - return source; - } - - public static XRepositoryDescriptor AddEvents( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.EventsService = typeof(TEventsService); - source.EventsImplementation = typeof(TEventsImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddKeyGenerator( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.KeyGeneratorService = typeof(TKeyGeneratorService); - source.KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddSeeder( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.SeederService = typeof(TSeederService); - source.SeederImplementation = typeof(TSeederImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddEFRepository( - this XRepositoryDescriptor source - ) - where TContext : XDbContext - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseEFRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddMongoRepository( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseMongoRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - - public static XRepositoryDescriptor AddInMemoryRepository( - this XRepositoryDescriptor source - ) - where TEntity : XBaseEntity - where TRepositoryService : IXBaseRepository - where TRepositoryImplementation : XBaseInMemoryRepository - { - // - if (source.IsNull()) - { - // - source = new XRepositoryDescriptor(); - source = source.AddEntity(); - } - - // - source.RepositoryService = typeof(TRepositoryService); - source.RepositoryImplementation = typeof(TRepositoryImplementation); - - // - return source; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphObjectType.cs - -using xModels.Base; -using GraphQL.Types; - -namespace xDataService.GraphQL -{ - /// - /// Base Entity GraphType Object ... - /// - /// - /// - public abstract class XBaseGraphObjectType : ObjectGraphType - where TEntity : XBaseEntity { - public XBaseGraphObjectType () { - // - Name = $"{typeof(TEntity).Name}GraphType"; - - // - Field (x => x.Id); - Field (x => x.Deleted); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLEventType.cs - -using xModels.Base; -using GraphQL.Types; -using xDataService.Models; - -namespace xDataService.GraphQL { - public class XBaseGraphQLEventType : ObjectGraphType> - where TGraphType : IGraphType - where TEntity : XBaseEntity { - public XBaseGraphQLEventType () { - // - Name = nameof (XBaseGraphQLEventType); - - // - Field (x => x.Model, type : typeof (TGraphType)); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLQuery.cs - -using System; -using xModels.Base; -using GraphQL.Types; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Constants; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using xDataService.Configuration; - -namespace xDataService.GraphQL -{ - public abstract class XBaseGraphQLQuery : ObjectGraphType, IXBaseGraphQLQuery - where TEntity : XBaseEntity - where TGraph : IGraphType - where TGraphKey : IGraphType - { - // - protected readonly XDataServiceConfiguration configuration; - protected readonly IXBaseRepository repository; - protected readonly IXBaseGraphQLTypeHelper helper; - - // - public XBaseGraphQLQuery( - XDataServiceConfiguration configuration, - IXBaseRepository repository, - IXBaseGraphQLTypeHelper helper - ) - { - // - this.helper = helper; - this.repository = repository; - this.configuration = configuration; - - // - Name = GetType().Name; - - // - #region Retrieve ... - // - // Get ... - FieldAsync( - name: helper.GetInQuerySingleName(), - arguments: new QueryArguments( - XGraphQLHelper.GetIdArgument(), - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .GetAsync( - includeBuilder: null, - id: context.GetIdArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // GetAll ... - FieldAsync>( - name: helper.GetInQueryCollectionName(), - arguments: new QueryArguments( - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .GetAllAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // FindOne ... - FieldAsync( - name: helper.GetFindOneName(), - arguments: new QueryArguments( - XGraphQLHelper.SearchQueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async (context) => - { - // - var searchQuery = context.GetSearchQueryArgument(); - Expression> whereClase = pe => pe - .PropValuesContains(searchQuery); - - // - return await repository - .FindOneAsync( - includeBuilder: null, - predicate: whereClase, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject(); - } - ); - - // - // FindMany ... - FieldAsync>( - name: helper.GetFindManyName(), - arguments: new QueryArguments( - XGraphQLHelper.SearchQueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async (context) => - { - // - var searchQuery = context.GetSearchQueryArgument(); - Expression> whereClase = pe => pe - .PropValuesContains(searchQuery); - - // - return await repository - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - predicate: whereClase, - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject(); - } - ); - - // - // Query ... - FieldAsync>( - name: helper.GetQueryName(), - arguments: new QueryArguments( - XGraphQLHelper.QueryArgument, - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .QueryAsync( - predicate: null, - orderBuilder: null, - includeBuilder: null, - query: context.GetQueryArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - .ToDynamicObject() - ); - - // - // Count ... - FieldAsync( - name: helper.GetCountName(), - arguments: new QueryArguments( - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository - .CountAsync( - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - ); - - // - // Exists ... - FieldAsync( - name: helper.GetExistsName(), - arguments: new QueryArguments( - XGraphQLHelper.GetIdArgument(), - XGraphQLHelper.IgnoreSoftDeletedArgument - ), - resolve: async context => - await repository.IsExistsAsync( - id: context.GetIdArgument(), - ignoreSoftDeleteds: context.GetIgnoreSoftDeletedArgument() - ) - ); - #endregion - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLSubscription.cs - -using xModels.Base; -using GraphQL.Types; -using GraphQL.Resolvers; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Providers; -using xDataService.Interfaces; -using System.Collections.Generic; - -namespace xDataService.GraphQL { - public abstract class XBaseGraphQLSubscription : ObjectGraphType - where TGraph : IGraphType - where TEntity : XBaseEntity { - public XBaseGraphQLSubscription (IXBaseRepositoryEvents eventProvider = null) { - // - Name = GetType ().Name; - - // - // Check if base repository patter registered ... - if (!eventProvider.IsNull ()) { - // - // Add ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.AddEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnAddObservable; - }) - }); - - // - // Add Many ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.AddManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnAddManyObservable; - }) - }); - - // - // Update ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.UpdateEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnUpdateObservable; - }) - }); - - // - // Update Mnay ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.UpdateManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnUpdateManyObservable; - }) - }); - - // - // Remove ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.RemoveEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver> ( - context => context.Source as XBaseEventModel - ), - Subscriber = new EventStreamResolver> (context => { - return eventProvider.OnRemoveObservable; - }) - }); - - // - // Remove Many ... - AddField (new EventStreamFieldType { - // - Name = nameof (XBaseRepositoryEvents.RemoveManyEvent), - Type = typeof (XBaseGraphQLEventType), - Resolver = new FuncFieldResolver>> ( - context => context.Source as XBaseEventModel> - ), - Subscriber = new EventStreamResolver>> (context => { - return eventProvider.OnRemoveManyObservable; - }) - }); - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\GraphQL\XBaseGraphQLTypeHelper.cs - -using xModels.Base; -using xCommons.Extensions; -using xDataService.Interfaces; -using xDataService.Configuration; - -namespace xDataService.GraphQL -{ - public abstract class XBaseGraphQLTypeHelper : IXBaseGraphQLTypeHelper - where TEntity : XBaseEntity - { - // - private readonly XDataServiceConfiguration configuration; - - // - protected XBaseGraphQLTypeHelper( - XDataServiceConfiguration configuration = null - ) - { - this.configuration = configuration; - } - - // - public abstract string GetInQueryCollectionName(); - - public abstract string GetInQuerySingleName(); - - // - public string GetFindOneName() - { - return $"find{GetInQuerySingleName().ToNormalString().Capitalize()}"; - } - - public string GetFindManyName() - { - return $"find{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetQueryName() - { - return $"query{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetCountName() - { - return $"count{GetInQueryCollectionName().ToNormalString().Capitalize()}"; - } - - public string GetExistsName() - { - return $"exists{GetInQuerySingleName().ToNormalString().Capitalize()}"; - } - - public string GetGraphQLPath(string baseGraphPath = null) - { - // - baseGraphPath = baseGraphPath.IsNullOrEmpty() ? - configuration.IsNull() || configuration.GraphQLBasePath.IsNullOrEmpty() ? - "" : - configuration.GraphQLBasePath : - baseGraphPath; - - // - var basePath = baseGraphPath - .EndsWith("/") ? - baseGraphPath - .Substring(0, baseGraphPath.Length - 1) : - baseGraphPath; - - // - return $"{basePath}/{GetInQueryCollectionName().ToNormalString()}"; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Helpers\XCursorHelper.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using System.Collections.Generic; - -namespace xDataService.Helpers { - public partial class XCursorHelper { - public static string ToCursor (T id) { - // - // Check Numbers ... - if (id.ToString ().IsDigits ()) { - return Convert - .ToBase64String (BitConverter - .GetBytes (Convert.ToInt32 (id)) - ); - } else - // - // Check Guid ... - if (id.ToString ().IsGuid ()) { - return Convert - .ToBase64String (new Guid (id.ToString ()) - .ToByteArray ()); - } else - // - // Assume as String ... - { - return Convert - .ToBase64String (id - .ToString ().ToBytes ()); - } - } - - public static T FromCursor (string cursor) { - // - // Check Numbers ... - var returnType = typeof (T); - if (returnType == typeof (int) || - returnType == typeof (long) || - returnType == typeof (decimal)) { - return Convert.ChangeType ((BitConverter - .ToInt32 (Convert - .FromBase64String (cursor), - 0 - )) - .ToDynamicObject (), returnType); - } else - // - // Check Guid ... - if (returnType == typeof (Guid)) { - return Convert.ChangeType ((new Guid ( - Convert.FromBase64String (cursor) - )) - .ToDynamicObject (), returnType); - } else - // - // Assume as String ... - { - return Convert.ChangeType (( - Convert.FromBase64String (cursor) - ) - .ToDynamicObject (), returnType); - } - } - - public static (string firstCursor, string lastCursor) GetFirstAndLastCursor (IEnumerable ids) { - // - if (ids?.Any () != true) { - return (null, null); - } - - // - var firstCursor = ToCursor (ids.First ()); - var lastCursor = ToCursor (ids.Last ()); - - // - return (firstCursor, lastCursor); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Helpers\XDataServiceHelper.cs - -using System; -using GraphQL; -using System.Linq; -using xModels.Base; -using GraphQL.Types; -using GraphQL.Server; -using xDataService.Db; -using System.Reflection; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.GraphQL; -using xExceptions.Constants; -using xDataService.Constants; -using xDataService.Providers; -using xDataService.Extensions; -using xDataService.Interfaces; -using GraphQL.Server.Ui.Voyager; -using System.Collections.Generic; -using MongoDB.Bson.Serialization; -using GraphQL.Server.Ui.Playground; -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using MySql.EntityFrameworkCore.Extensions; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Helpers -{ - public static class XDataServiceHelper - { - /// - /// Register DbContext ... - /// - /// - /// - /// - /// - public static void AddXDbContext( - IServiceCollection source, - XDatabaseDescriptor databaseDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - // - var isValid = - databaseDescriptor.IsValid() && - databaseDescriptor.HasProvider(); - if (!isValid) - { - XException.InvalidConfiguration.Throw(); - } - - // - switch (databaseDescriptor.Provider) - { - // - // MySQL ... - case XDbProviders.MySQL: - // - source.AddEntityFrameworkMySQL(); - source.AddDbContext(cfg => - { - // - cfg.UseMySQL( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // SQLite ... - case XDbProviders.SQLite: - // - source.AddEntityFrameworkSqlite(); - source.AddDbContext(cfg => - { - // - cfg.UseSqlite( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // Oracle ... - case XDbProviders.Oracle: - // - source.AddEntityFrameworkOracle(); - source.AddDbContext(cfg => - { - // - cfg.UseOracle( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // SQLServer ... - case XDbProviders.SQLServer: - // - source.AddEntityFrameworkSqlServer(); - source.AddDbContext(cfg => - { - // - cfg.UseSqlServer( - databaseDescriptor.ConnectionString, - databaseDescriptor.OptionsBuilder - ); - }, lifetime); - break; - - // - // Mongo DB ... - case XDbProviders.MongoDB: - // - #region XBaseEntity Mappers ... - // - // Map ID as BsonId here ... - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - BsonClassMap.RegisterClassMap>(cm => - { - // - cm.AutoMap(); - cm.MapIdMember(c => c.Id); - }); - #endregion - - // - // Check Has Convention Packs ... - isValid = databaseDescriptor.HasConventionPacks(); - if (isValid) - { - // - ConventionRegistry.Register( - nameof( - databaseDescriptor.ConventionPacks - ), - databaseDescriptor.ConventionPacks, - type => !type.FullName - .IsNullOrEmpty() - ); - } - break; - } - - // - isValid = - databaseDescriptor.Provider == XDbProviders.MySQL || - databaseDescriptor.Provider == XDbProviders.SQLite || - databaseDescriptor.Provider == XDbProviders.Oracle || - databaseDescriptor.Provider == XDbProviders.SQLServer; - if (isValid) - { - // - AddXUnitOfWorks( - source, - lifetime - ); - } - } - - // - #region Repository ... - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - >( - IServiceCollection source, - XInMemoryRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XInMemoryRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TSeederService : IXBaseDbSeeder - where TSeederImplementation : XBaseDbSeeder - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - >( - IServiceCollection source, - XMongoRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XMongoRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TSeederImplementation : XBaseDbSeeder - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext - >( - IServiceCollection source, - XEFRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - } - - /// - /// Register Repository ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXRepository< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext, - TSeederService, - TSeederImplementation - >( - IServiceCollection source, - XEFRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - var isValid = repositoryDescriptor.IsValid(); - if (!isValid) - { - return; - } - - // - // Register KeyGenerator ... - isValid = repositoryDescriptor.HasKeyGenerator(); - if (isValid) - { - // - AddXKeyGenerator( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Events ... - isValid = repositoryDescriptor.HasEvents(); - if (isValid) - { - // - AddXEvents( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Graph ... - isValid = repositoryDescriptor.HasGraphSupport(); - if (isValid) - { - // - AddXGraphQL( - source, - repositoryDescriptor, - lifetime - ); - } - - // - // Register Repository ... - isValid = repositoryDescriptor.HasRepository(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.RepositoryService, - repositoryDescriptor.RepositoryImplementation, - lifetime - ) - ); - } - - // - // DbSeeder ... - isValid = repositoryDescriptor.HasSeeder(); - if (isValid) - { - // - source.Add( - new ServiceDescriptor( - repositoryDescriptor.SeederService, - repositoryDescriptor.SeederImplementation, - lifetime - ) - ); - } - } - - /// - /// Use GraphQL ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void UseXGraphQL< - TEntity, - TKey, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IApplicationBuilder source, - string graphBasePath, - string graphPath, - bool withPlayGround = false - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - source.UseGraphQL(graphPath); - source.UseGraphQLWebSockets(); - - // - if (withPlayGround) - { - // - source.UseGraphQLPlayground(new GraphQLPlaygroundOptions - { - Path = "/ui/playground", - GraphQLEndPoint = graphBasePath - }); - - // - source.UseGraphQLVoyager(new GraphQLVoyagerOptions - { - Path = "/ui/voyager", - GraphQLEndPoint = graphBasePath - }); - } - } - #endregion - - // - #region Entity Assembly Detector ... - /// - /// Extract Assemblies which Contains Entity ... - /// - /// - public static List ExtractEntityAssemblies() - { - // - var result = new List(); - - // - var allAssemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach (var assembly in allAssemblies) - { - // - try - { - // - bool hasEntity = assembly - .GetExportedTypes() - .Any(t => t.IsXEntity()); - if (hasEntity) - { - result.Add(assembly); - } - } - catch { } - } - - // - return result; - } - - /// - /// Register All Entities using Model Builder ... - /// - /// - public static void RegisterAllEntities(this ModelBuilder modelBuilder) - { - // - // Extract Entity Container Assemblies ... - var entityAssemblies = ExtractEntityAssemblies(); - foreach(var assembly in entityAssemblies) - { - modelBuilder.ApplyConfigurationsFromAssembly(assembly); - } - } - - #endregion - - // - #region Private ... - /// - /// Register Unit of Works ... - /// - /// - /// - /// - public static void AddXUnitOfWorks( - IServiceCollection source, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - // - source.Add( - new ServiceDescriptor( - typeof(IXUnitOfWorks), - typeof(XUnitOfWorks), - lifetime - ) - ); - } - - /// - /// Register Key Generator Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXKeyGenerator< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.KeyGeneratorService.IsNull() && - !repositoryDescriptor.KeyGeneratorImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register ... - source.Add( - new ServiceDescriptor( - repositoryDescriptor.KeyGeneratorService, - repositoryDescriptor.KeyGeneratorImplementation, - lifetime - ) - ); - } - - /// - /// Register Events Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXEvents< - TEntity, - TKey, - TEventsService, - TEventsImplementation - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TEventsImplementation : XBaseRepositoryEvents - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.EventsService.IsNull() && - !repositoryDescriptor.EventsImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register ... - source.Add( - new ServiceDescriptor( - repositoryDescriptor.EventsService, - repositoryDescriptor.EventsImplementation, - lifetime - ) - ); - } - - /// - /// Register GraphQL Service ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void AddXGraphQL< - TEntity, - TKey, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - >( - IServiceCollection source, - XRepositoryDescriptor repositoryDescriptor, - ServiceLifetime lifetime = ServiceLifetime.Scoped - ) - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - // - // Validate ... - var isValid = - !source.IsNull() && - !repositoryDescriptor.IsNull() && - !repositoryDescriptor.GraphType.IsNull() && - !repositoryDescriptor.GraphQuery.IsNull() && - !repositoryDescriptor.GraphSchema.IsNull() && - !repositoryDescriptor.GraphTypeKey.IsNull() && - !repositoryDescriptor.GraphTypeHelperService.IsNull() && - !repositoryDescriptor.GraphTypeHelperImplementation.IsNull(); - if (!isValid) - { - return; - } - - // - // Register Graph Type ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, // ServiceLifetime.Singleton, - serviceType: repositoryDescriptor.GraphType, - implementationType: repositoryDescriptor.GraphType - ) - ); - - // - // Register Graph Events ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, // ServiceLifetime.Singleton, - serviceType: typeof(XBaseGraphQLEventType), - implementationType: typeof(XBaseGraphQLEventType) - ) - ); - - // - // Register Graph Type Helper ... - source.Add( - new ServiceDescriptor( - lifetime: ServiceLifetime.Singleton, - serviceType: repositoryDescriptor.GraphTypeHelperService, - implementationType: repositoryDescriptor.GraphTypeHelperImplementation - ) - ); - - // - // Register Graph Query ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, - serviceType: repositoryDescriptor.GraphQuery, - implementationType: repositoryDescriptor.GraphQuery - ) - ); - - // - // Register Graph Schema ... - source.Add( - new ServiceDescriptor( - lifetime: lifetime, - serviceType: repositoryDescriptor.GraphSchema, - implementationType: repositoryDescriptor.GraphSchema - ) - ); - - // - source.AddScoped(); - - // - // Register Graph Type Schema ... - var builder = source.GetRegisteredService(); - if (builder.IsNull()) - { - // - Action options = x => - { - // - x.EnableMetrics = true; - x.UnhandledExceptionDelegate = context => - { - Console.WriteLine("XGraphQL Error: " + context.OriginalException.Message); - }; - }; - builder = source.AddGraphQL(options) - .AddNewtonsoftJson(deserializerSettings => { }, serializerSettings => { }) - .AddWebSockets() - .AddDataLoader() - .AddGraphTypes(lifetime); - } - builder.AddGraphTypes( - serviceLifetime: lifetime, - typeFromAssembly: repositoryDescriptor.GraphSchema - ); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Helpers\XGraphQLHelper.cs - -using xModels.Dtos; -using GraphQL.Types; -using xDataService.Models; - -namespace xDataService.Constants { - public static class XGraphQLHelper { - public static QueryArgument GetIdArgument () - where TKey : IGraphType { - return new QueryArgument { - Name = "id", - Description = "the id of entity, which you want to retrieve ..." - }; - } - - public static QueryArgument IgnoreSoftDeletedArgument = new QueryArgument { - Name = "ignoreSoftDeleteds", - DefaultValue = true, - Description = "determines result should ignore soft deleted items or not ..." - }; - - public static QueryArgument SearchQueryArgument = new QueryArgument { - Name = "searchQuery", - Description = "the value which had to looking for ..." - }; - - public static QueryArgument QueryArgument = new QueryArgument { - Name = "query", - DefaultValue = new XQuery (), - Description = "determines query structure info for retrieving data ..." - }; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseDbSeeder.cs - -using xModels.Base; -using System.Threading.Tasks; -using xDataService.Configuration; - -namespace xDataService.Interfaces -{ - /// - /// Db Seeder used to seed data on Database on startup time ... - /// - public interface IXBaseDbSeeder - where TEntity : XBaseEntity - { - /// - /// Holds Entity Name ... - /// - string Entity { get; } - - /// - /// Holds Database Name ... - /// - string Database { get; } - - /// - /// Repository Service for Data Manipulation ... - /// - IXBaseRepository Repository { get; } - - /// - /// DataServiceConfiguration ... - /// - XDataServiceConfiguration DataServiceConfiguration { get; } - - /// - /// do all seeding action by helping of Repositories here ... - /// - /// - Task Seed(); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseEnricher.cs - -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Interfaces -{ - public interface IXBaseEnricher - { - Task EnrichAsync( - TSource source, - TDest destination, - CancellationToken cancellationToken = default - ); - - Task EnrichRangeAsync( - IEnumerable sources, - IEnumerable destinations, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseGraphQLQuery.cs - -using xModels.Base; -using GraphQL.Types; - -namespace xDataService.Interfaces -{ - public interface IXBaseGraphQLQuery - where TEntity : XBaseEntity - where TGraph : IGraphType - where TGraphKey : IGraphType - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseGraphQLTypeHelper.cs - -using xModels.Base; - -namespace xDataService.Interfaces -{ - public interface IXBaseGraphQLTypeHelper - where TEntity : XBaseEntity - { - string GetInQuerySingleName(); - - string GetInQueryCollectionName(); - - string GetFindOneName(); - - string GetFindManyName(); - - string GetQueryName(); - - string GetCountName(); - - string GetExistsName(); - - string GetGraphQLPath(string baseGraphPath = null); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseReferencedProvider.cs - -using xModels.Dtos; -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Interfaces -{ - /// - /// in Some Cases we have Entities Which Can Referenced for Specified - /// Provider and Types ... - /// this interface Globaly introduce all available Actions for those ... - /// - /// TKey: type of Provider Models Keys ... - /// TModel: type of Dto which Referenced ... - /// - public interface IXBaseReferencedProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - string Provider { get; } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - Task GetReference( - TKey providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - Task> GetAllReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - Task>> GetAllReferencings( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Count References ... - /// - /// - /// - /// - Task CountReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - Task> QueryReferences( - XQuery query, - TKey providedForId, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - Task RemoveReferences( - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - public interface IXBaseRepository : IDisposable { } - - /// - /// Base Repository Pattern Contracts in XDashboard's Data Service ... - /// use for Data Manipulation ... - /// - /// - /// - public interface IXBaseRepository : IXBaseRepository - where T : XBaseEntity - { - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ); - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ); - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - Task SaveChangesAsync( - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - TKey GetKey(T item); - - /// - /// Set Key of Entity ... - /// - /// - /// - void SetKey( - ref T item, - TKey id - ); - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - void Detach(T item); - - /// - /// Detach an Enumerable of Entities ... - /// - /// - void Detach(IEnumerable items); - - /// - /// Detach a Query Result of Entity ... - /// - /// - void Detach(XQueryResult query); - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Base Repository Actions Providing Using Controllers ... - /// - /// - /// - public interface IXBaseRepositoryController - where TEntity : XBaseEntity - { - // - IXBaseRepository Repository { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - - // - #region Add ... - Task> Add( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task> AddOrUpdate( - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - CancellationToken cancellationToken = default - ); - - Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - - Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryEvents.cs - -using System; -using xDataService.Models; -using System.Collections.Generic; - -namespace xDataService.Interfaces { - public interface IXBaseRepositoryEvents { - // - void AddEvent (XBaseEventModel model); - void UpdateEvent (XBaseEventModel model); - void RemoveEvent (XBaseEventModel model); - - // - void AddManyEvent (XBaseEventModel> model); - void UpdateManyEvent (XBaseEventModel> model); - void RemoveManyEvent (XBaseEventModel> model); - - // - IObservable> OnAddObservable { get; } - IObservable> OnUpdateObservable { get; } - IObservable> OnRemoveObservable { get; } - - // - IObservable>> OnAddManyObservable { get; } - IObservable>> OnUpdateManyObservable { get; } - IObservable>> OnRemoveManyObservable { get; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseRepositoryService.cs - -using System; -using AutoMapper; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Manipulating Data Using Services based on Dto Mapping ... - /// - /// - /// - /// - public interface IXBaseRepositoryService : IDisposable - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - /// - /// Mapper Instance ... - /// - IMapper Mapper { get; } - - /// - /// Repository Implementation for Data Manipulations ... - /// - IXBaseRepository Repository { get; } - - /// - /// Mapping Profile Configuration ... - /// - /// this Configuration used for Mapping TEntity to Dto and reverse ... - /// default mapping prepared on Constructing time, other custom maps - /// must handled manually if required ... - /// - MapperConfiguration MapperConfiguration { get; } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - Task AddAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add or update a Dto (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - Task AddOrUpdateAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// add a range of new Dtos ... - /// - /// - /// - /// - /// - Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update a range of Dtos ... - /// - /// - /// - /// - /// - Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Dto ... - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TDto item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove a range of exists Dtos ... - /// - /// - /// - /// - /// - /// - Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Count ... - /// - /// count all exists Dtos ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - #endregion - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXBaseServiceController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Interfaces -{ - /// - /// an Interface for Base RepositoryService Actions Providing Using Controllers ... - /// - /// - /// - /// - public interface IXBaseServiceController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - IXBaseRepositoryService RepositoryService { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - - // - #region Add ... - Task> Add( - TDto item, - CancellationToken cancellationToken = default - ); - - Task> AddOrUpdate( - TDto item, - CancellationToken cancellationToken = default - ); - - Task AddMany( - XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Retrieve ... - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Update ... - Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ); - - Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Exists ... - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeletedss = true, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove ... - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - - Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = true, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXDatabaseDescriptor.cs - -using System; -using xDataService.Db; -using xDataService.Models; -using xDataService.Constants; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.Extensions.Configuration; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Interfaces -{ - /// - /// Data Base Descriptor ... - /// - public interface IXDatabaseDescriptor - { - // - #region Props ... - /// - /// Database Name ... - /// - /// - string Name { get; set; } - - /// - /// Database Provider ... - /// - /// - XDbProviders Provider { get; set; } - - /// - /// Db Context Type ... - /// - /// - Type Context { get; set; } - - /// - /// Database Connecion String ... - /// - /// - string ConnectionString { get; set; } - - /// - /// Data Service Configuration ... - /// - /// - XDataBaseConfiguration Configuration { get; set; } - - /// - /// Repositories Descriptions ... - /// - /// - IList Repositories { get; set; } - - /// - /// Mongo Convention Packs ... - /// - ConventionPack ConventionPacks { get; set; } - - /// - /// DbContext Options Builder ... - /// - /// - Action OptionsBuilder { get; set; } - #endregion - - // - #region Configure ... - /// - /// Configure Database Descriptor using Registered Services ... - /// - /// - void Configure( - IServiceCollection services - ); - - /// - /// Configure Database Descriptor using IConfiguration ... - /// - /// - void Configure( - IConfiguration configuration - ); - - /// - /// Configure Database Descriptor using Database Configuration ... - /// - /// - void Configure( - XDataBaseConfiguration configuration - ); - - /// - /// Configure Database Descriptor using Provider and Connection String ... - /// - /// - /// - void Configure( - XDbProviders provider, - string connectionString - ); - #endregion - } - - /// - /// Data Base Descriptor ... - /// - /// - public interface IXDatabaseDescriptor : IXDatabaseDescriptor - where TContext : XDbContext - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXEntityRegisterar.cs - -using System; -using xModels.Base; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Interfaces -{ - /// - /// an Interface to Intruduce Entities for Dynamic Registration ... - /// - public interface IXEntityRegisterar - { - /// - /// Database Name ... - /// - string Name { get; } - - /// - /// Returns all entity types this plugin wants registered in the DbContext - /// - IEnumerable GetEntityTypes(); - - /// - /// Optional: Apply additional per-entity configuration - /// - void ConfigureEntities(ModelBuilder modelBuilder); - - /// - /// Add XDataService Based Entity to List ... - /// - /// - /// - void AddEntity() - where TEntity : XBaseEntity; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXKeyGenerator.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; - -namespace xDataService.Interfaces -{ - /// - /// Typed Base Key Generator ... - /// - /// - /// - public interface IXKeyGenerator - where TEntity : XBaseEntity - { - bool IsEmpty(TKey id); - Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXSequentialGuid.cs - -using System; - -namespace xDataService.Interfaces { - /// - /// this service provide Sequential GUID mechanism for Entity Ids ... - /// - public interface IXSequentialGuid { - Guid GetCurrentGuid (); - Guid Next (); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Interfaces\IXUnitOfWorks.cs - -using System; -using xModels.Base; -using xDataService.Db; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Interfaces { - /// - /// Provide Unit Of Works Design Pattern for Db Transactions ... - /// Only Used on EFCore ... - /// - /// - public interface IXUnitOfWorks : IDisposable - where TDbContext : XDbContext { - TDbContext DbContext { get; } - DbSet GetDbSet () where T : XBaseEntity; - int SaveChanges (); - Task SaveChangesAsync ( - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XBaseEventModel.cs - -namespace xDataService.Models { - /// - /// Pass Data on Repository Events ... - /// - /// - public class XBaseEventModel { - public T Model { get; set; } - - public XBaseEventModel (T model) { - Model = model; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XDatabaseDescriptor.cs - -using System; -using System.Linq; -using xDataService.Db; -using xDataService.DI; -using xCommons.Extensions; -using xDataService.Constants; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.Extensions.Configuration; -using MongoDB.Bson.Serialization.Conventions; -using Microsoft.Extensions.DependencyInjection; - -namespace xDataService.Models -{ - /// - /// Data Base Descriptor ... - /// - public abstract class XDatabaseDescriptor : IXDatabaseDescriptor - { - // - #region Props ... - /// - /// Database Name ... - /// - /// - public virtual string Name { get; set; } - - /// - /// Database Provider ... - /// - /// - public virtual XDbProviders Provider { get; set; } - - /// - /// Db Context... - /// - /// - public virtual Type Context { get; set; } = null; - - /// - /// Database Connecion String ... - /// - /// - public virtual string ConnectionString { get; set; } - - /// - /// Data Service Configuration ... - /// - /// - public virtual XDataBaseConfiguration Configuration { get; set; } - - /// - /// Repositories Descriptions ... - /// - /// - public virtual IList Repositories { get; set; } = null; - - /// - /// Mongo Convention Packs ... - /// - public ConventionPack ConventionPacks { get; set; } = null; - - /// - /// DbContext Options Builder ... - /// - /// - public Action OptionsBuilder { get; set; } = null; - #endregion - - // - #region Constructor ... - /// - /// Constructor of Descriptor ... - /// - /// - /// - /// - public XDatabaseDescriptor( - string name, - IList repositories = null - ) - { - // - Name = name; - Repositories = repositories; - } - #endregion - - // - #region Configure ... - /// - /// Configure Database Descriptor using Registered Services ... - /// - /// - public void Configure( - IServiceCollection services - ) - { - // - bool isValid = !Name.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var xDataServiceConfiguration = services.GetRegisteredService(); - isValid = - !xDataServiceConfiguration.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Any(k => k == Name); - if (!isValid) - { - return; - } - - // - var database = xDataServiceConfiguration.Databases[Name]; - isValid = !database.IsNullOrDefault(); - if (!isValid) - { - return; - } - - // - Configure(database); - } - - /// - /// Configure Database Descriptor using IConfiguration ... - /// - /// - public void Configure( - IConfiguration configuration - ) - { - // - bool isValid = !Name.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var xDataServiceConfiguration = configuration.GetXDataServiceConfiguration(); - isValid = - !xDataServiceConfiguration.IsNullOrDefault() && - xDataServiceConfiguration.Databases.HasChild() && - xDataServiceConfiguration.Databases.Keys.Any(k => k == Name); - if (!isValid) - { - return; - } - - // - var database = xDataServiceConfiguration.Databases[Name]; - isValid = !database.IsNullOrDefault(); - if (!isValid) - { - return; - } - - // - Configure(database); - } - - /// - /// Configure Database Descriptor using Database Configuration ... - /// - /// - public void Configure( - XDataBaseConfiguration configuration - ) - { - // - Configuration = configuration; - Provider = configuration.Provider; - ConnectionString = configuration.ConnectionString; - } - - /// - /// Configure Database Descriptor using Provider and Connection String ... - /// - /// - /// - public void Configure( - XDbProviders provider, - string connectionString - ) - { - // - Provider = provider; - ConnectionString = connectionString; - Configuration = new XDataBaseConfiguration - { - Provider = provider, - ConnectionString = connectionString - }; - } - #endregion - } - - /// - /// Data Base Descriptor ... - /// - /// - public abstract class XDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor - where TContext : XDbContext - { - /// - /// Constructor of Descriptor ... - /// - /// - /// - /// - /// - public XDatabaseDescriptor( - string name, - IList repositories = null - ) : base( - name: name, - repositories: repositories - ) - { - Context = typeof(TContext); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XGraphQueryResult.cs - -using xModels.Dtos; -using GraphQL.Types; - -namespace xDataService.Models { - public class XGraphQueryResult : ObjectGraphType> - where TGraph : IGraphType { - public XGraphQueryResult () { - // - Name = $"{typeof(TGraph).Name}QueryResult"; - - // - Field> (nameof (XQueryResult.Items)); - Field (x => x.Page); - Field (x => x.PageSize); - Field (x => x.TotalPages); - Field (x => x.TotalFilteredItems); - Field (x => x.TotalItems); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XGraphQueryType.cs - -using xModels.Dtos; -using GraphQL.Types; - -namespace xDataService.Models { - public class XGraphQueryType : InputObjectGraphType { - public XGraphQueryType () { - // - Name = "query"; - - // - Field (x => x.Filter); - Field (x => x.ContainsDetail); - Field (x => x.SortBy); - Field (x => x.IsAscending); - Field (x => x.Page); - Field (x => x.PageSize); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XReference.cs - -namespace xDataService.Models -{ - public class XReference - { - public int Index { get; set; } - public T ReferencedTo { get; set; } - public string ProvidedFor { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Models\XRepositoryDescriptor.cs - -using System; -using xModels.Base; -using GraphQL.Types; -using xDataService.Db; -using xDataService.GraphQL; -using xDataService.Providers; -using xDataService.Interfaces; - -namespace xDataService.Models -{ - /// - /// a Global non Generic Repository Descriptor ... - /// - public class XRepositoryDescriptor - { - /// - /// Entity Key Type ... - /// - /// - public Type Key { get; set; } = null; - - /// - /// Entity Type ... - /// - /// - public Type Entity { get; set; } = null; - - /// - /// Context Type ... - /// - /// - public Type Context { get; set; } = null; - - /// - /// Graph Type Key ... - /// - /// - public Type GraphTypeKey { get; set; } = null; - - /// - /// Graph Type ... - /// - /// - public Type GraphType { get; set; } = null; - - /// - /// Entity Type GraphQL Schema ... - /// - /// - public Type GraphSchema { get; set; } = null; - - /// - /// Entity GraphQL Type Helper ... - /// - /// - public Type GraphTypeHelperService { get; set; } = null; - - /// - /// Entity GraphQL Type Helper ... - /// - /// - public Type GraphTypeHelperImplementation { get; set; } = null; - - /// - /// Entity GrapQL Query ... - /// - /// - public Type GraphQuery { get; set; } = null; - - /// - /// Repository Event Provider ... - /// - /// - public Type EventsService { get; set; } = null; - - /// - /// Repository Event Provider ... - /// - /// - public Type EventsImplementation { get; set; } = null; - - /// - /// Repository Key Generator for Entity ... - /// - /// - public Type KeyGeneratorService { get; set; } = null; - - /// - /// Repository Key Generator for Entity ... - /// - /// - public Type KeyGeneratorImplementation { get; set; } = null; - - /// - /// Repository Data Access Design Pattern ... - /// - /// - public Type RepositoryService { get; set; } = null; - - /// - /// Repository Data Access Design Pattern ... - /// - /// - public Type RepositoryImplementation { get; set; } = null; - - /// - /// Database Data Seeder ... - /// - public Type SeederService { get; set; } = null; - - /// - /// Database Data Seeder ... - /// - public Type SeederImplementation { get; set; } = null; - } - - /// - /// a Repository Descriptor ... - /// - /// - /// - public class XRepositoryDescriptor : XRepositoryDescriptor - where TEntity : XBaseEntity - { - public XRepositoryDescriptor() : base() - { - // - Key = typeof(TKey); - Entity = typeof(TEntity); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - > : XRepositoryDescriptor - where TEntity : XBaseEntity - where TKeyGeneratorService : IXKeyGenerator - where TKeyGeneratorImplementation : XKeyGenerator - { - public XRepositoryDescriptor() : base() - { - // - KeyGeneratorService = typeof(TKeyGeneratorService); - KeyGeneratorImplementation = typeof(TKeyGeneratorImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation - > - where TEntity : XBaseEntity - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - { - public XRepositoryDescriptor() : base() - { - // - EventsService = typeof(TEventsService); - EventsImplementation = typeof(TEventsImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XRepositoryDescriptor() : base() - { - // - GraphType = typeof(TGraph); - GraphTypeKey = typeof(TGraphKey); - GraphQuery = typeof(TGraphQuery); - GraphSchema = typeof(TGraphSchema); - GraphTypeHelperService = typeof(TGraphTypeHelperService); - GraphTypeHelperImplementation = typeof(TGraphTypeHelperImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XInMemoryRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XInMemoryRepositoryDescriptor() : base() - { - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XInMemoryRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TSeederImplementation : XBaseDbSeeder - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TRepositoryImplementation : XBaseInMemoryRepository - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XInMemoryRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XMongoRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XMongoRepositoryDescriptor() : base() - { - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XMongoRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TRepositoryImplementation : XBaseMongoRepository - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XMongoRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XEFRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TEventsService : IXBaseRepositoryEvents - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XEFRepositoryDescriptor() : base() - { - // - Context = typeof(TContext); - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } - - /// - /// a Repository Descriptor ... - /// - public class XEFRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema, - TRepositoryService, - TRepositoryImplementation, - TContext, - TSeederService, - TSeederImplementation - > : XRepositoryDescriptor< - TEntity, - TKey, - TKeyGeneratorService, - TKeyGeneratorImplementation, - TEventsService, - TEventsImplementation, - TGraph, - TGraphKey, - TGraphQuery, - TGraphTypeHelperService, - TGraphTypeHelperImplementation, - TGraphSchema - > - where TGraphSchema : Schema - where TContext : XDbContext - where TGraphKey : IGraphType - where TEntity : XBaseEntity - where TGraph : XBaseGraphObjectType - where TSeederService : IXBaseDbSeeder - where TEventsService : IXBaseRepositoryEvents - where TSeederImplementation : XBaseDbSeeder - where TKeyGeneratorService : IXKeyGenerator - where TRepositoryService : IXBaseRepository - where TEventsImplementation : XBaseRepositoryEvents - where TKeyGeneratorImplementation : XKeyGenerator - where TGraphTypeHelperService : IXBaseGraphQLTypeHelper - where TGraphQuery : XBaseGraphQLQuery - where TRepositoryImplementation : XBaseEFRepository - where TGraphTypeHelperImplementation : XBaseGraphQLTypeHelper - { - public XEFRepositoryDescriptor() : base() - { - // - SeederService = typeof(TSeederService); - SeederImplementation = typeof(TSeederImplementation); - - // - Context = typeof(TContext); - RepositoryService = typeof(TRepositoryService); - RepositoryImplementation = typeof(TRepositoryImplementation); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Mongo\XAsyncEnumerableAdapter.cs - -using MongoDB.Driver; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XAsyncEnumerableAdapter : IAsyncEnumerable { - // - private readonly IAsyncCursorSource asyncCursorSource; - - // - public XAsyncEnumerableAdapter (IAsyncCursorSource asyncCursorSource) { - this.asyncCursorSource = asyncCursorSource; - } - - // - public IAsyncEnumerator GetAsyncEnumerator (CancellationToken cancellationToken) => - new XAsyncEnumeratorAdapter (asyncCursorSource, cancellationToken); - } - - public class XAsyncEnumeratorAdapter : IAsyncEnumerator { - private readonly IAsyncCursorSource asyncCursorSource; - private readonly CancellationToken cancellationToken; - private IAsyncCursor asyncCursor; - private IEnumerator batchEnumerator; - - public T Current => batchEnumerator.Current; - - public XAsyncEnumeratorAdapter ( - IAsyncCursorSource asyncCursorSource, - CancellationToken cancellationToken - ) { - // - this.asyncCursorSource = asyncCursorSource; - this.cancellationToken = cancellationToken; - } - - public async ValueTask MoveNextAsync () { - // - if (asyncCursor == null) { - asyncCursor = await asyncCursorSource - .ToCursorAsync (cancellationToken); - } - - // - if (batchEnumerator != null && - batchEnumerator.MoveNext ()) { - return true; - } - - // - if (asyncCursor != null && - await asyncCursor.MoveNextAsync (cancellationToken)) { - // - batchEnumerator?.Dispose (); - batchEnumerator = asyncCursor.Current.GetEnumerator (); - - // - return batchEnumerator.MoveNext (); - } - - // - return false; - } - - public async ValueTask DisposeAsync () { - // - await Task.CompletedTask; - asyncCursor?.Dispose (); - asyncCursor = null; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoAsyncCursor.cs - -using MongoDB.Driver; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XMongoAsyncCursor : IAsyncCursor { - public IEnumerable Current { get; } - private IEnumerator CurrentEnumerator { get; } - - public XMongoAsyncCursor (IEnumerable source) { - this.Current = source; - this.CurrentEnumerator = source.GetEnumerator (); - } - - public void Dispose () { - CurrentEnumerator.Dispose (); - } - - public bool MoveNext (CancellationToken cancellationToken = default) { - return CurrentEnumerator.MoveNext (); - } - - public Task MoveNextAsync (CancellationToken cancellationToken = default) { - return Task.Run ( - () => CurrentEnumerator.MoveNext (), - cancellationToken : cancellationToken - ); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoQueryable.cs - -using System; -using System.Linq; -using xModels.Base; -using MongoDB.Driver; -using System.Threading; -using System.Collections; -using MongoDB.Driver.Linq; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; - -namespace xDataService.Mongo { - public class XMongoQueryable : IMongoQueryable - where TEntity : XBaseEntity { - private readonly IMongoCollection collection; - - public Type ElementType { get; } - public IQueryable Items { get; } - public Expression Expression { get; } - public IQueryProvider Provider { get; } - - public XMongoQueryable ( - IQueryable items, - IMongoCollection collection - ) { - // - this.Items = items; - this.collection = collection; - - // - Provider = items.Provider; - Expression = items.Expression; - ElementType = items.ElementType; - } - - public IEnumerator GetEnumerator () { - return Items.GetEnumerator (); - } - - public QueryableExecutionModel GetExecutionModel () { - return collection.AsQueryable ().GetExecutionModel (); - } - - public IAsyncCursor ToCursor (CancellationToken cancellationToken = default) { - return new XMongoAsyncCursor (Items); - } - - public Task> ToCursorAsync (CancellationToken cancellationToken = default) { - return Task.Run (() => new XMongoAsyncCursor (Items) as IAsyncCursor); - } - - IEnumerator IEnumerable.GetEnumerator () { - return Items.GetEnumerator (); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Mongo\XMongoReadPreferenceResolver.cs - -using MongoDB.Driver; - -namespace xDataService.Mongo { - public static class XMongoReadPreferenceResolver { - public static ReadPreference GetEffectiveReadPreference ( - IClientSessionHandle session, - ReadPreference explicitReadPreference, - ReadPreference defaultReadPreference) { - if (explicitReadPreference != null) { - return explicitReadPreference; - } - - if (session.IsInTransaction) { - var transactionReadPreference = session.WrappedCoreSession.CurrentTransaction.TransactionOptions.ReadPreference; - if (transactionReadPreference != null) { - return transactionReadPreference; - } - } - - return defaultReadPreference ?? ReadPreference.Primary; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseDbSeeder.cs - -using System.Linq; -using xModels.Base; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Constants; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; - -namespace xDataService.Providers -{ - public abstract class XBaseDbSeeder : IXBaseDbSeeder - where TEntity : XBaseEntity - { - // - #region Properties ... - /// - /// Holds Entity Name ... - /// - public string Entity { get; } - - /// - /// Holds Database Name ... - /// - public string Database { get; } - - /// - /// Repository Service for Data Manipulation ... - /// - public IXBaseRepository Repository { get; } - - /// - /// DataServiceConfiguration ... - /// - public XDataServiceConfiguration DataServiceConfiguration { get; } - #endregion - - // - #region Constructor ... - public XBaseDbSeeder( - string entity, - string database, - IXBaseRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) - { - // - this.Entity = entity; - this.Database = database; - this.Repository = repository; - this.DataServiceConfiguration = dataServiceConfiguration; - } - #endregion - - public async Task Seed() - { - // - // Validate Seed ... - var isValid = - DataServiceConfiguration.SeedingMode != XDbSeedingMode.None && - DataServiceConfiguration - .Databases - .Any(db => - db.Key == Database && - db.Value.SeedItems - .Any(si => - si.Key == Entity && - si.Value.HasChild())); - if (!isValid) - { - return; - } - - // - // Extract Seeding Items ... - var seedItems = DataServiceConfiguration - .Databases[Database] - .SeedItems[Entity] - .ToList(); - foreach (var item in seedItems) - { - // - try - { - // - var entity = item - .ToJSON() - .FromJSON(); - - // - // Check Item Exists or not ... - var isExist = false; - TEntity exists = null; - var asyncEnumerable = this.Repository.GetAllAsAsyncEnumerable(); - await foreach (var e in asyncEnumerable) - { - // - isExist = e.IsSameContent( - dest: entity, - propertyBlackList: new List - { - nameof(entity.Id), - nameof(entity.Deleted) - }); - if (isExist) - { - exists = e; - break; - } - } - - // - // Seed Based on Seed Mode ... - var seedMode = DataServiceConfiguration.SeedingMode; - switch (seedMode) - { - // - case XDbSeedingMode.AddIfNotExists: - // - if (!isExist) - { - // - exists = await Repository.AddAsync( - item: entity, - saveChanges: true - ); - } - break; - - // - case XDbSeedingMode.AddOrUpdate: - // - exists = exists.UpdateData( - updateWith: entity, - propertyBlackList: new List - { - nameof(entity.Id), - nameof(entity.Deleted) - } - ); - - // - await Repository.AddOrUpdateAsync(exists); - break; - } - } - catch - { } - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEFRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using xDataService.Db; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for EF DBs using - /// EF Core Capabilities ... - /// - /// - /// - /// - public abstract class XBaseEFRepository : IXBaseRepository - where T : XBaseEntity - where TDbContext : XDbContext - { - // - #region Properties ... - // - public readonly DbSet dbSet; - private readonly IXKeyGenerator keyGenerator; - public readonly IXUnitOfWorks unitOfWorks; - public readonly XDataServiceConfiguration configuration; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - #endregion - - // - #region Constructor ... - public XBaseEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - // - this.unitOfWorks = unitOfWorks; - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.dbSet = unitOfWorks.GetDbSet(); - this.baseRepositoryEvents = baseRepositoryEvents; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - var entry = await dbSet.AddAsync( - entity: item, - cancellationToken: cancellationToken - ); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: GetKey(item), - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - return await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - else - { - // - return await UpdateAsync( - item: item, - id: GetKey(item), - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Preparing Ids and Keys ... - await dbSet.AddRangeAsync( - await Task - .WhenAll( - items - .Select(async i => await HandleKeyAsync(i)) - ), - cancellationToken: cancellationToken - ); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Get Exists Entity ... - var existsEntity = await GetAsync( - id: id, - ignoreSoftDeleteds: false, - cancellationToken: cancellationToken - ); - - // - // Update Data ... - existsEntity.UpdateData(item); - var entry = dbSet.Attach(existsEntity); - entry.State = EntityState.Modified; - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - items - .ToList() - .ForEach(i => - { - var entry = dbSet.Attach(i); - entry.State = EntityState.Modified; - }); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateManyEvent(new XBaseEventModel>(null)); - } - - // - // Return result base on action Succeed ... - return isSucceed; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Item ... - var item = await GetAsync( - id, - ignoreSoftDeleteds: false, - cancellationToken: cancellationToken - ); - if (item.IsNullOrDefault()) - { - return null; - } - - // - // Handle Remove ... - EntityEntry entry = null; - if (softDelete && configuration.EnableSoftDelete) - { - // - item.Deleted = true; - entry = dbSet.Update(item); - } - else - { - entry = dbSet.Remove(item); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveEvent(new XBaseEventModel(entry.Entity)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - entry.Entity : - null; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Remove ... - if (softDelete && configuration.EnableSoftDelete) - { - // - foreach (var item in items) - { - item.Deleted = true; - } - - // - dbSet.UpdateRange(items); - } - else - { - dbSet.RemoveRange(items); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = 0; - - // - if (ignoreSoftDeleteds) - { - // - result = await dbSet.CountAsync( - predicate: x => !x.Deleted, - cancellationToken: cancellationToken - ); - } - else - { - result = await dbSet.CountAsync(cancellationToken); - } - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = dbSet - .AsQueryable(); - - // - // Apply Predicate ... - if (!predicate.IsNull()) - { - result = result - .Where(predicate); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - // Apply Ordering ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken)) - .FirstOrDefault(x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var list = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - var whereClause = predicate.Compile(); - var result = list.FirstOrDefault(x => whereClause(x)); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken)) - .Where(predicate.Compile()); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = (await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .ToListAsync(cancellationToken)) - .Any(predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - return await unitOfWorks.SaveChangesAsync(cancellationToken); - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(T item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref T item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(T item) - { - // - if (item.IsNull()) - { - return; - } - - // - Entry(item).State = EntityState.Detached; - } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) - { - // - if (items.IsNull() || !items.HasChild()) - { - return; - } - - // - items - .ToList() - .ForEach(item => - { - Detach(item); - }); - } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) - { - // - if (query.IsNull() || query.Items.HasChild()) - { - return; - } - - // - Detach(query.Items); - } - #endregion - #endregion - - // - #region Others ... - public void Dispose() - { - unitOfWorks.Dispose(); - } - - public string GetPropValues(T item) - { - // - var props = item.GetType().GetProperties(); - var vals = props.Select(p => p.GetValue(p.Name)); - - // - return vals.ToJSON(); - } - - public EntityEntry Entry(T item) - { - return unitOfWorks.DbContext.Entry(item); - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEntityRegisterar.cs - -using System; -using xModels.Base; -using xDataService.Interfaces; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Providers -{ - /// - /// Base Entity Registerar ... - /// - public abstract class XBaseEntityRegisterar : IXEntityRegisterar - { - /// - /// Private Entity Types Collection ... - /// - private readonly List entityTypes = []; - - /// - /// Name ... - /// - public string Name { get; } - - protected XBaseEntityRegisterar(string name) - { - Name = name; - } - - /// - /// Add Specified Entity to Collection ... - /// - /// - /// - public void AddEntity() - where TEntity : XBaseEntity - { - entityTypes.Add(typeof(TEntity)); - } - - /// - /// Retrieve Registered Entity Types ... - /// - /// - public IEnumerable GetEntityTypes() - { - return entityTypes; - } - - /// - /// Configure Dynamic Entities ... - /// - /// - public virtual void ConfigureEntities(ModelBuilder modelBuilder) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseEntityTypeConfiguration.cs - -using xModels.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xDataService.Providers -{ - /// - /// Configure an Entity Specifications ... - /// - /// - /// - public abstract class XBaseEntityTypeConfiguration : IEntityTypeConfiguration - where TEntity : XBaseEntity - { - public abstract void Configure(EntityTypeBuilder builder); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseInMemoryRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using System.Collections.Concurrent; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for InMemory Stores using - /// EF Core Capabilities ... - /// - /// - /// - public abstract class XBaseInMemoryRepository : IXBaseRepository - where TEntity : XBaseEntity - { - // - #region Props ... - private readonly XDataServiceConfiguration configuration; - private readonly IXKeyGenerator keyGenerator; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - private static readonly ConcurrentDictionary store = new ConcurrentDictionary(); - #endregion - - // - #region Constructor ... - public XBaseInMemoryRepository( - XDataServiceConfiguration configuration, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.baseRepositoryEvents = baseRepositoryEvents; - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - var isSucceed = false; - - // - // Add Item to Dictionary ... - try - { - // - store[item.Id] = item; - isSucceed = true; - } - catch - { - isSucceed = false; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - - // - // Return Item ... - return item; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: item.Id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - var isSucceed = false; - if (isExists) - { - // - try - { - // - item = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - isSucceed = true; - } - catch - { - isSucceed = false; - } - } - else - { - // - try - { - // - item = await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - isSucceed = true; - } - catch - { - isSucceed = false; - } - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - if (isExists) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - else - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - } - - // - return item; - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - - // - // Notify Event ... - if ( - isValid && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - TEntity item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isExists) - { - return null; - } - - // - var isSucceed = false; - var exists = store[id]; - - // - try - { - // - exists = exists.UpdateData( - exists, - propertyBlackList: new List { nameof(exists.Id) } - ); - store[id] = exists; - - // - isSucceed = true; - } - catch - { - isSucceed = false; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - - // - return exists; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return result; - } - - // - foreach (var item in items) - { - // - var updated = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - if (!updated.IsNullOrDefault() && !result) - { - result = true; - } - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: id, - cancellationToken: cancellationToken - ); - if (!isExists) - { - return null; - } - - // - TEntity result = null; - if (softDelete && configuration.EnableSoftDelete) - { - // - store[id].Deleted = true; - result = store[id]; - } - else - { - // - result = store[id]; - store.TryRemove(id, out _); - } - - // - return result; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TEntity item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await RemoveAsync( - item: item, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .CountAsync(cancellationToken); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .AnyAsync( - cancellationToken: cancellationToken, - predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = store.Values.AsQueryable(); - - // - // Predicate ... - if (!predicate.IsNull()) - { - result = result.Where(predicate); - } - - // - // Apply Orders ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - if (asNoTracking) - { - result = result.AsNoTracking(); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(x => GetKey(x).ToString() == id.ToString()) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync(); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - // - return await Task.Run( - () => 0, - cancellationToken - ); - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(TEntity item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref TEntity item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - TEntity item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(TEntity item) { } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) { } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) { } - #endregion - #endregion - - // - #region Others ... - public void Dispose() - { } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseMongoRepository.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using MongoDB.Driver; -using System.Threading; -using MongoDB.Driver.Linq; -using xCommons.Extensions; -using xDataService.Models; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Pattern Implementation Specially for Mongo DBs using - /// EF Core Capabilities ... - /// - /// - /// - public abstract class XBaseMongoRepository : IXBaseRepository - where T : XBaseEntity - { - // - #region Properties ... - private readonly string collectionName; - public List> bulkCollection; - public readonly IMongoCollection collection; - private readonly IXKeyGenerator keyGenerator; - public readonly XDataBaseConfiguration dbConfiguration; - public readonly XDataServiceConfiguration configuration; - private readonly IXBaseRepositoryEvents baseRepositoryEvents; - #endregion - - // - #region Constructor ... - protected XBaseMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXKeyGenerator keyGenerator = null, - IXBaseRepositoryEvents baseRepositoryEvents = null - ) - { - // - this.keyGenerator = keyGenerator; - this.configuration = configuration; - this.collectionName = collectionName - .IsNullOrEmpty() ? - typeof(T).Name : - collectionName; - this.dbConfiguration = dbConfiguration; - this.baseRepositoryEvents = baseRepositoryEvents; - - // - var client = new MongoClient(dbConfiguration.GetMongoDbURI()); - var database = client.GetDatabase(dbConfiguration.GetMongoDbDatabase()); - - // - bulkCollection = new List>(); - collection = database.GetCollection( - this.collectionName - ); - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Entity ... - /// - /// - /// - /// - /// - public async Task AddAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - // Add Action model to Bulk Collection ... - bulkCollection.Add(new InsertOneModel(item)); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// add or update an Entity (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public async Task AddOrUpdateAsync( - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isExists = await IsExistsAsync( - id: GetKey(item), - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isExists) - { - // - // Handle Key ... - item = await HandleKeyAsync( - item: item, - cancellationToken: cancellationToken - ); - - // - // Add Action model to Bulk Collection ... - bulkCollection - .Add(new InsertOneModel(item)); - } - else - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, item.Id); - - // - // Add Action model to Bulk Collection ... - bulkCollection - .Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - if (isExists) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - else - { - // - baseRepositoryEvents - .AddEvent(new XBaseEventModel(item)); - } - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// add a range of new Entities ... - /// - /// - /// - /// - /// - public async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - await AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - - // - // Notify Event ... - if ( - isValid && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .AddManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Update ... - /// - /// Update an Entity values ... - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - T item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, id); - - // - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = false }); - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .UpdateEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// Update a range of Entities ... - /// - /// - /// - /// - /// - public async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - var isValid = !items.IsNull() && items.HasChild(); - if (!isValid) - { - return result; - } - - // - foreach (var item in items) - { - // - var updated = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - if (!updated.IsNullOrDefault() && !result) - { - result = true; - } - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Retrieve Item ... - var item = await GetAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (item.IsNull()) - { - return null; - } - - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, id); - - // - // Check SoftDelete ... - if (softDelete && configuration.EnableSoftDelete) - { - // - // Set Soft Delete ... - item.Deleted = true; - - // - // Update ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - else - { - // - // Delete ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new DeleteOneModel(filter)); - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveEvent(new XBaseEventModel(item)); - } - - // - // Return result base on action Succeed ... - return isSucceed ? - item : - null; - } - - /// - /// remove an Entity ... - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - T item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RemoveAsync( - id: item.Id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove a range of exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // loop through items ... - foreach (var item in items) - { - // - // Filter ... - var filter = Builders.Filter.Eq(i => i.Id, item.Id); - - // - // Check Soft Delete ... - if (softDelete && configuration.EnableSoftDelete) - { - // - // Set Soft Delete ... - item.Deleted = true; - - // - // Update ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new ReplaceOneModel(filter, item) { IsUpsert = true }); - } - else - { - // - // Delete ... - // Add Action model to Bulk Collection ... - bulkCollection.Add(new DeleteOneModel(filter)); - } - } - - // - // Check action is Succeeded or not ... - var isSucceed = false; - if (saveChanges) - { - // - // Get Modified Count ... - var qResult = await SaveChangesAsync(cancellationToken); - - // - // set isSucceed Value based on Changes ... - isSucceed = qResult > 0; - } - - // - // Notify Event ... - if ( - isSucceed && - !baseRepositoryEvents.IsNull() - ) - { - // - baseRepositoryEvents - .RemoveManyEvent(new XBaseEventModel>(null)); - } - } - #endregion - - // - #region Count ... - /// - /// count all exists Entities ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .CountAsync(cancellationToken); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - int count = totalItems.HasValue ? totalItems.Value : await CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve whole items as queryable ... - /// - /// a flag for Tracking behaviour - /// an Expression for Filter Items ... - /// an Order Builder expression for Ordering Query ... - /// an Include Builder expression for Including Navigation Properties ... - /// - public IQueryable AsQueryable( - bool asNoTracking = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - var result = collection - .AsQueryable(); - - // - // Apply Predicate ... - if (!predicate.IsNull()) - { - result = result - .Where(predicate); - } - - // - // Apply Includes ... - if (!includeBuilder.IsNull()) - { - // - // Since Mongo Queryable doesnt Support Includes ... - // we ignore this ... - result = (IMongoQueryable)includeBuilder(result); - } - - // - // Apply Ordering ... - if (!orderBuilder.IsNull()) - { - result = (IMongoQueryable)orderBuilder(result); - } - - // - return result; - } - - /// - /// retrieve an Entity by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(x => GetKey(x).ToString() == id.ToString()) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve all exists Entities - /// as Async Enumerable ... - /// - /// - /// - /// - /// - public IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .AsAsyncEnumerable(); - - // - return result; - - } - - /// - /// find an Entity by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - predicate: predicator, - includeBuilder: includeBuilder - ) - .Where(predicate) - .FirstOrDefaultAsync(cancellationToken); - - // - return result; - } - - /// - /// find a collection of Entities by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - predicate: predicator, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ) - .Where(predicate) - .ToListAsync(cancellationToken); - - // - return result; - } - - /// - /// retrieve Entities based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = query.NormalizeQuery(configuration); - - // - var items = await GetAllAsync(); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = items.ToList(), - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check an Entity exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - // Prepare Ignore Soft Deleted Predicator ... - Expression> predicator = null; - if (ignoreSoftDeleteds) - { - predicator = x => !x.Deleted; - } - var result = await AsQueryable( - asNoTracking: true, - orderBuilder: null, - includeBuilder: null, - predicate: predicator - ) - .AnyAsync( - cancellationToken: cancellationToken, - predicate: x => GetKey(x).ToString() == id.ToString()); - - // - return result; - } - #endregion - - // - #region Unit Of Work ... - /// - /// Save all unsaved Transactions on DbContext ... - /// used fo Unit Of Works Design Pattern ... - /// - /// - /// - public async Task SaveChangesAsync( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Write all Bulk Models which stored inside bulkCollection ... - var result = await collection - .BulkWriteAsync( - options: null, - requests: bulkCollection, - cancellationToken: cancellationToken - ); - - // - // Clear Bulk Collection ... - bulkCollection.Clear(); - - // - // Return number of Modified Documents ... - var resultCount = (int)result.ModifiedCount + - (int)result.InsertedCount + - (int)result.DeletedCount; - - // - return resultCount; - } - catch (Exception ex) - { - // - // Log Thrown Exception ... - Console.WriteLine($"XMongo Repository Exception: {ex.Message} ..."); - - // - // Return less than zero value ... - return -1; - } - } - #endregion - - // - #region Key ... - /// - /// Retrieve Key of Entity ... - /// - /// - /// - public TKey GetKey(T item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - return keyString.FromJSON(); - } - - /// - /// Set Key of Entity ... - /// - /// - /// - public void SetKey( - ref T item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Handle Checking Key ... - /// - /// - /// - /// - public async Task HandleKeyAsync( - T item, - CancellationToken cancellationToken = default - ) - { - // - var keyType = typeof(TKey); - - // - // Handle Guid Key Type ... - // Since EFCore has AutoIncrement on int Ids, there is no need to handle int Key types ... - if ( - ( - keyType == typeof(Guid) || - keyType == typeof(string) - ) && - keyGenerator.IsEmpty(item.Id) - ) - { - // - var newKey = await keyGenerator.GenerateKey(this); - - // - SetKey(ref item, newKey); - } - - // - return item; - } - #endregion - - // - #region Detach ... - /// - /// Detach an Entity ... - /// - /// - public void Detach(T item) { } - - /// - /// Detach an Enumerable of Entities ... - /// - /// - public void Detach(IEnumerable items) { } - - /// - /// Detach a Query Result of Entity ... - /// - /// - public void Detach(XQueryResult query) { } - #endregion - #endregion - - // - #region Others ... - public void Dispose() { } - - public string GetPropValues(T item) - { - // - var props = item.GetType().GetProperties(); - var vals = props.Select(p => p.GetValue(p.Name)); - - // - return vals.ToJSON(); - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseRepositoryEvents.cs - -using System; -using xDataService.Models; -using System.Reactive.Linq; -using xDataService.Interfaces; -using System.Reactive.Subjects; -using System.Collections.Generic; - -namespace xDataService.Providers { - /// - /// Some Events can be Raised on Some Actions Happens on Repositories ... - /// this is the Base Events Class ... - /// - /// - public abstract class XBaseRepositoryEvents : IXBaseRepositoryEvents { - // - private readonly ISubject> onAddSubject; - private readonly ISubject> onUpdateSubject; - private readonly ISubject> onRemoveSubject; - - // - private readonly ISubject>> onAddManySubject; - private readonly ISubject>> onUpdateManySubject; - private readonly ISubject>> onRemoveManySubject; - - // - protected XBaseRepositoryEvents () { - // - onAddSubject = new ReplaySubject> (1); - onUpdateSubject = new ReplaySubject> (1); - onRemoveSubject = new ReplaySubject> (1); - - // - onAddManySubject = new ReplaySubject>> (1); - onUpdateManySubject = new ReplaySubject>> (1); - onRemoveManySubject = new ReplaySubject>> (1); - } - - // - public void AddEvent (XBaseEventModel model) => onAddSubject.OnNext (model); - - public void UpdateEvent (XBaseEventModel model) => onUpdateSubject.OnNext (model); - - public void RemoveEvent (XBaseEventModel model) => onRemoveSubject.OnNext (model); - - // - public void AddManyEvent (XBaseEventModel> model) => onAddManySubject.OnNext (model); - public void UpdateManyEvent (XBaseEventModel> model) => onUpdateManySubject.OnNext (model); - public void RemoveManyEvent (XBaseEventModel> model) => onRemoveManySubject.OnNext (model); - - // - public IObservable> OnAddObservable => onAddSubject.AsObservable (); - - public IObservable> OnUpdateObservable => onUpdateSubject.AsObservable (); - - public IObservable> OnRemoveObservable => onRemoveSubject.AsObservable (); - - // - public IObservable>> OnAddManyObservable => onAddManySubject.AsObservable (); - public IObservable>> OnUpdateManyObservable => onUpdateManySubject.AsObservable (); - public IObservable>> OnRemoveManyObservable => onRemoveManySubject.AsObservable (); - - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XBaseRepositoryService.cs - -using System; -using AutoMapper; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Interfaces; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; - -namespace xDataService.Providers -{ - /// - /// a Base Repository Service Implementation which Use a Repository Patterns Implementatin - /// and provides Data Manipulation Methods using Dtos instead of Entities ... - /// - /// it can be use of following Repository Patterns Implementation: - /// - /// - /// - /// - public abstract class XBaseRepositoryService : IXBaseRepositoryService - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Properties ... - /// - /// Mapper Instance ... - /// - public IMapper Mapper { get; } - - /// - /// Repository Implementation for Data Manipulations ... - /// - public IXBaseRepository Repository { get; } - - /// - /// Mapping Profile Configuration ... - /// - /// this Configuration used for Mapping TEntity to Dto and reverse ... - /// default mapping prepared on Constructing time, other custom maps - /// must handled manually if required ... - /// - public MapperConfiguration MapperConfiguration { get; } - #endregion - - // - #region Constructor ... - public XBaseRepositoryService( - IXBaseRepository repository, - IEnumerable mapperProfiles = null - ) - { - // - Repository = repository; - - // - // Preparing Mapping Configurations ... - MapperConfiguration = new MapperConfiguration(cfg => - { - // - // Add Default Profiles ... - - // - // Entity To Dto ... - cfg.CreateMap() - .ForMember(dest => dest.Deleted, opt => opt.Ignore()); - cfg.CreateMap, XQueryResult>(); - - // - // Dto to Entity ... - cfg.CreateMap() - .ForMember(dest => dest.Deleted, opt => opt.Ignore()); - cfg.CreateMap, XQueryResult>(); - - // - // Add Provided Profiles if Provided ... - // if Same Profiles Provided, here resolved ... - if (!mapperProfiles.IsNull() && - mapperProfiles.HasChild()) - { - cfg.AddProfiles(mapperProfiles); - } - }); - - // - // Make Mapper Instance using prepared Configuration ... - Mapper = MapperConfiguration.CreateMapper(); - } - #endregion - - // - #region Actions ... - // - #region Add ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - public virtual async Task AddAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - // Validate ... - bool isValid = !item.IsNull(); - if (!isValid) - { - return result; - } - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.AddAsync( - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// add or update a Dto (add if not exists/update if exists) ... - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateAsync( - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - // Validate ... - bool isValid = !item.IsNull(); - if (!isValid) - { - return result; - } - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.AddOrUpdateAsync( - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// add a range of new Dtos ... - /// - /// - /// - /// - /// - public virtual async Task AddRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !items.IsNull() && - items.HasChild(); - if (!isValid) - { - return; - } - - // - try - { - // - var entities = Mapper.Map>(items); - - // - await Repository.AddRangeAsync( - items: entities, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { } - } - #endregion - - // - #region Update ... - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.UpdateAsync( - id: item.Id, - item: entity, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// Update a range of Dtos ... - /// - /// - /// - /// - /// - public virtual async Task UpdateRangeAsync( - IEnumerable items, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !items.IsNull() && - items.HasChild(); - if (!result) - { - return result; - } - - // - try - { - // - var entitis = Mapper.Map>(items); - - // - result = await Repository.UpdateRangeAsync( - items: entitis, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { - result = false; - } - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// remove an Dto ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TDto item, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = Mapper.Map(item); - - // - entity = await Repository.RemoveAsync( - item: entity, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// remove a range of exists Dtos ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveRangeAsync( - IEnumerable items, - bool softDelete = true, - bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !items.IsNull() && - items.HasChild(); - if (!isValid) - { - return; - } - - // - var entities = Mapper.Map>(items); - - // - try - { - // - await Repository.RemoveRangeAsync( - items: entities, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - } - catch - { } - } - #endregion - - // - #region Count ... - /// - /// count all exists Dtos ... - /// - /// - /// - /// - public virtual async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// count all exists Entities Pages by providing page size ... - /// - /// - /// - /// - /// - /// - public virtual async Task PagesCountAsync( - int pageSize, - int? totalItems = null, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.PagesCountAsync( - pageSize: pageSize, - totalItems: totalItems, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Exists ... - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - public virtual async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.GetAsync( - id: id, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - public virtual async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - IEnumerable result = Enumerable.Empty(); - - // - try - { - // - var entities = await Repository.GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entities); - } - catch - { } - - // - return result; - } - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default - ) - { - // - var entityEnumerable = Repository.GetAllAsAsyncEnumerable( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - await foreach (var entity in entityEnumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var dto = Mapper.Map(entity); - yield return dto; - } - } - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - TDto result = null; - - // - try - { - // - var entity = await Repository.FindOneAsync( - predicate: predicate, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map(entity); - } - catch - { } - - // - return result; - } - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - IEnumerable result = Enumerable.Empty(); - - // - try - { - // - var entities = await Repository.FindManyAsync( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entities); - } - catch - { } - - // - return result; - } - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - XQueryResult result = null; - - // - try - { - // - var entityResult = await Repository.QueryAsync( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - result = Mapper.Map>(entityResult); - } - catch - { } - - // - return result; - } - #endregion - - public virtual void Dispose() - { } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XEntityRegisterarHandlerService.cs - -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using xCommons.Extensions; -using xDataService.Interfaces; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xDataService.Providers -{ - public class XEntityRegisterarHandlerService - { - /// - /// a Collection for Extract Registerars Services ... - /// - private readonly List registerars = []; - - /// - /// a Collection for Holding all Entity Types ... - /// - public IReadOnlyList AllEntityTypes { get; private set; } - - /// - /// Retrieve Specified Registerars Entity Types ... - /// - /// - /// - public IReadOnlyList GetEntityTypes(string[] names = null) - { - // - var items = new List(); - - // - if (!names.IsNull() && names.HasChild()) - { - // - items = [.. registerars - .Where(r => names.Contains(r.Name)) - .SelectMany(r => r.GetEntityTypes())]; - } - - // - return items.AsReadOnly(); - } - - /// - /// Load all Dynamically Registered Entities ... - /// - public void HandleRegisteredEntities() - { - // - var entityTypes = new List(); - var path = Path.Combine (AppContext.BaseDirectory); - var files = Directory.GetFiles(path, "*.dll"); - foreach (var dll in files) - { - // - // Retrieve DLL Assembly ... - var assembly = Assembly.LoadFrom(dll); - - // - // Extract Registerar Types ... - var registerarTypes = assembly - .GetExportedTypes() - .Where(t => - !t.IsAbstract && - typeof(IXEntityRegisterar).IsAssignableFrom(t)); - foreach (var registerarType in registerarTypes) - { - // - // Create Instance of Registerar Type ... - var registerar = (IXEntityRegisterar)Activator.CreateInstance(registerarType); - if (!registerar.IsNull()) - { - // - // Add Registerar Instance to Collection ... - registerars.Add(registerar); - - // - // Add Registerar Provided Entities to Collection ... - entityTypes.AddRange(registerar.GetEntityTypes()); - } - } - - // - // Converts to Readonly List ... - AllEntityTypes = entityTypes.AsReadOnly(); - } - } - - /// - /// Configure all Dynamically Registered Entities ... - /// - /// - /// - public void HandleApplyRegisteredEntitiesConfigurations( - ModelBuilder modelBuilder, - string[] names = null - ) - { - // - var selectedRegisterars = - !names.IsNull() && - names.HasChild() - ? registerars - .Where(r => names.Contains(r.Name)) - : registerars; - - // - // Loop Through Extracted Registerars ... - foreach(var registerar in selectedRegisterars) - { - // - // Configure Specified Registerars Entities ... - registerar.ConfigureEntities(modelBuilder); - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XGuidKeyGenerator.cs - -using System; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Guid Key Generator ... - /// - /// - public class XGuidKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - private readonly IXSequentialGuid sequentialGuid; - - public XGuidKeyGenerator( - IXSequentialGuid sequentialGuid = null - ) - { - this.sequentialGuid = sequentialGuid; - } - - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - return await Task.Run(() => - { - // - // Check if provided SequentialGuid ... - if (sequentialGuid.IsNull()) - { - return Guid.NewGuid(); - } - else - { - return sequentialGuid.Next(); - } - }, cancellationToken: cancellationToken); - } - - public override bool IsEmpty(Guid id) - { - // - var result = id.IsNull() || id.IsDefaultGuid(); - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XIntKeyGenerator.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Extensions; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Int Key Generator ... - /// - /// - public class XIntKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - var items = (await repository.GetAllAsync()) - .OrderByDescending(nameof(XBaseEntity.Id)); - var last = items - .FirstOrDefault(); - - // - var result = last.IsNull() ? 1 : last.Id + 1; - - // - return result; - } - - public override bool IsEmpty(int id) - { - // - var result = id <= 0; - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XKeyGenerator.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - public abstract class XKeyGenerator : IXKeyGenerator - where TEntity : XBaseEntity - { - public abstract Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ); - - public abstract bool IsEmpty(TKey id); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XLongKeyGenerator.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Extensions; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Long Key Generator ... - /// - /// - public class XLongKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - var items = (await repository.GetAllAsync()) - .OrderByDescending(nameof(XBaseEntity.Id)); - var last = items - .FirstOrDefault(); - - // - var result = last.IsNull() ? 1 : last.Id + 1; - - // - return result; - } - - public override bool IsEmpty(long id) - { - // - var result = id <= 0; - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XSequentialGuid.cs - -using System; -using xDataService.Interfaces; - -namespace xDataService.Helpers -{ - /// - /// this service provide Sequential GUID mechanism for Entity Ids ... - /// - public class XSequentialGuid : IXSequentialGuid - { - private static int[] sqlOrderMap = null; - private static int[] SQLORDERMAP - { - get - { - if (sqlOrderMap == null) - { - sqlOrderMap = new int[16] { - 3, - 2, - 1, - 0, - 5, - 4, - 7, - 6, - 9, - 8, - 15, - 14, - 13, - 12, - 11, - 10 - }; - // 3 - the least significant byte in Guid ByteArray [for SQL Server ORDER BY clause] - // 10 - the most significant byte in Guid ByteArray [for SQL Server ORDERY BY clause] - } - return sqlOrderMap; - } - } - - private Guid currentGuid; - - public XSequentialGuid() - { - currentGuid = Guid.NewGuid(); - } - - public Guid GetCurrentGuid() - { - return currentGuid; - } - - public Guid Next() - { - byte[] bytes = currentGuid.ToByteArray(); - for (int mapIndex = 0; mapIndex < 16; mapIndex++) - { - int bytesIndex = SQLORDERMAP[mapIndex]; - bytes[bytesIndex]++; - if (bytes[bytesIndex] != 0) - { - break; // No need to increment more significant bytes - } - } - currentGuid = new Guid(bytes); - return currentGuid; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xDataService\Providers\XStringKeyGenerator.cs - -using System; -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xDataService.Interfaces; - -namespace xDataService.Providers -{ - /// - /// Default Guid Key Generator ... - /// - /// - - public class XStringKeyGenerator : XKeyGenerator, IXKeyGenerator - where TEntity : XBaseEntity - { - private readonly IXSequentialGuid sequentialGuid; - - public XStringKeyGenerator(IXSequentialGuid sequentialGuid = null) - { - this.sequentialGuid = sequentialGuid; - } - - public override async Task GenerateKey( - IXBaseRepository repository, - CancellationToken cancellationToken = default - ) - { - // - await Task.CompletedTask; - - // - if (sequentialGuid.IsNull()) - { - return Guid.NewGuid().ToString(); - } - else - { - return sequentialGuid.Next().ToString(); - } - } - - public override bool IsEmpty(string id) - { - return id.IsNullOrEmpty(); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xEventService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xEventService-20261109_152621.txt deleted file mode 100644 index f99a3eb..0000000 --- a/Documents/GeneratedContext/xDashboard-xEventService-20261109_152621.txt +++ /dev/null @@ -1,2460 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Configuration\XEventServiceConfiguration.cs - -using xEventService.Models; -using xEventService.Constants; - -namespace xEventService.Configuration -{ - /// - /// a configuration class for describing how to connect rabbit mq server - /// and how channels must be declared ... - /// - public class XEventServiceConfiguration - { - /// - /// Message Broker Address ... - /// - public string Url { get; set; } - - /// - /// Max Retries to Sending Message ... - /// - public int MaxRetries { get; set; } = 3; - - /// - /// Allowed Message Broker ... - /// - public XEventBroker Broker { get; set; } = XEventBroker.None; - - /// - /// ZeroMQ Specific Options ... - /// Only used when Broker is XZeroMQ ... - /// - public XZeroMQOptions ZeroMQ { get; set; } = new XZeroMQOptions(); - - /// - /// RabbitMQ Specific Options ... - /// Only used when Broker is XRabbitMQ ... - /// - public XRabbitMQOptions RabbitMQ { get; set; } = new XRabbitMQOptions(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Constants\ConfigurationNodeNames.cs - -namespace xEventService.Constants -{ - public partial struct ConfigurationNodeNames { - public const string EVENT_SERVICE_NODE_NAME = "EventServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Constants\XEventBroker.cs - -using xExceptions.Attributes; - -namespace xEventService.Constants -{ - /// - /// Available Brokers ... - /// - public enum XEventBroker - { - [StringValue(XEventServiceConstants.None)] - None, - - [StringValue(XEventServiceConstants.XKafka)] - XKafka, - - [StringValue(XEventServiceConstants.XZeroMQ)] - XZeroMQ, - - [StringValue(XEventServiceConstants.XRabbitMQ)] - XRabbitMQ, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Constants\XEventServiceConstants.cs - -namespace xEventService.Constants -{ - public struct XEventServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XEventServiceDILogTag = "XEventService"; - - // - // Defaults ... - public const string XDefaultTopic = "XSaherelm"; - public const string XDefaultConsumerGroup = "XSaherElmGroup"; - - // - public const string None = "None"; - public const string XKafka = "XKafka"; - public const string PubSub = "PubSub"; - public const string XZeroMQ = "XZeroMQ"; - public const string PushPull = "PushPull"; - public const string XRabbitMQ = "XRabbitMQ"; - - // - public const string XWildcard = "*"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Constants\XRabbitMQExchangeType.cs - -using xExceptions.Attributes; - -namespace xEventService.Constants -{ - /// - /// Available RabbitMQ Exchange Types ... - /// - public struct XRabbitMQExchangeTypes - { - public const string None = "none"; - public const string Direct = "direct"; - public const string Fanout = "fanout"; - public const string Topic = "topic"; - public const string Headers = "headers"; - } - - /// - /// RabbitMQ Exchange Type Enum ... - /// - public enum XRabbitMQExchangeType - { - [StringValue(XRabbitMQExchangeTypes.None)] - None, - - [StringValue(XRabbitMQExchangeTypes.Direct)] - Direct, - - [StringValue(XRabbitMQExchangeTypes.Fanout)] - Fanout, - - [StringValue(XRabbitMQExchangeTypes.Topic)] - Topic, - - [StringValue(XRabbitMQExchangeTypes.Headers)] - Headers, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Constants\XZeroMQPattern.cs - -using xExceptions.Attributes; - -namespace xEventService.Constants -{ - public enum XZeroMQPattern - { - [StringValue(XEventServiceConstants.None)] - None, - - [StringValue(XEventServiceConstants.PubSub)] - PubSub, - - [StringValue(XEventServiceConstants.PushPull)] - PushPull - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\DI\XDIHelperExtension.cs - -using System; -using xCommons.Extensions; -using xExceptions.Constants; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xEventService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Extract EventService Configurations ... - /// - /// - /// - public static XEventServiceConfiguration GetXEventServiceConfiguration( - this IConfiguration source - ) - { - // - var configSection = source - .GetSection(ConfigurationNodeNames.EVENT_SERVICE_NODE_NAME); - var result = configSection.Get(); - - // - return result; - } - - /// - /// Register Event Service Configurations ... - /// - /// - /// - public static void AddXEventServiceConfiguration( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - var config = configuration.GetXEventServiceConfiguration(); - services.AddXEventServiceConfiguration(config); - } - - /// - /// Register Event Service Configurations ... - /// - /// - /// - public static void AddXEventServiceConfiguration( - this IServiceCollection services, - XEventServiceConfiguration configuration - ) - { - // - // Validate ... - var isValid = configuration.IsValid() && - (configuration.Broker == XEventBroker.XKafka || - (configuration.Broker == XEventBroker.XZeroMQ && - configuration.ZeroMQ.IsValid()) || - (configuration.Broker == XEventBroker.XRabbitMQ && - configuration.RabbitMQ.IsValid())); - if (!isValid) - { - // - Log("Registration Failed, due Invalid Configuration ..."); - XException.InvalidConfiguration.Throw(); - } - - // - // Register Configuration as Singleton ... - services.AddSingleton(configuration); - } - - // - #region Private ... - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XEventServiceConstants.XEventServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Extensions\XEventServiceExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using xEventService.Constants; -using xEventService.Configuration; - -namespace xEventService.Extensions -{ - /// - /// Extensions for Event Service ... - /// - public static class XEventServiceExtensions - { - /// - /// Validate Event Broker ... - /// - /// - /// - public static bool IsValid(this XEventBroker source) - { - // - var result = - !source.IsNull() && - source != XEventBroker.None; - - // - return result; - } - - /// - /// Validate Event Service Configuration ... - /// - /// - /// - public static bool IsValid(this XEventServiceConfiguration source) - { - // - var result = - !source.IsNullOrDefault() && - source.Broker.IsValid() && - !source.Url.IsNullOrEmpty() && - source.Url.IsValidUrl(); - - // - return result; - } - - /// - /// Validate RabbitMQ Exchange Type ... - /// - /// - /// - public static bool IsValid(this XRabbitMQExchangeType source) - { - // - var result = source != XRabbitMQExchangeType.None; - - // - return result; - } - - /// - /// Validate RabbitMQ Configuration ... - /// - /// - /// - public static bool IsValid(this XRabbitMQOptions source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Exchange.IsNullOrEmpty() && - source.ExchangeType.IsValid(); - - // - return result; - } - - /// - /// Validate an Event Message ... - /// - /// - /// - public static bool IsValid(this XEventMessage source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Action.IsNullOrEmpty() && - !source.Sender.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate an Event Request ... - /// - /// - /// - public static bool IsValid(this XEventRequest source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Topic.IsNullOrEmpty() && - source.Message.IsValid(); - - // - return result; - } - - /// - /// Validate ZeroMQ Pattern ... - /// - /// - /// - public static bool IsValid(this XZeroMQPattern source) - { - // - var result = source != XZeroMQPattern.None; - - // - return result; - } - - /// - /// Validate ZeroMQ Options ... - /// - /// - /// - public static bool IsValid(this XZeroMQOptions source) - { - // - var result = - !source.IsNullOrDefault() && - source.Pattern.IsValid(); - - // - return result; - } - - /// - /// Validate an Array is Wildcard passed or not ... - /// - /// - /// - public static bool IsAllowedWildcard(this string[] source) - { - // - var result = - source is not null && - source.Length == 1 && - source.Any(s => - s == XEventServiceConstants.XWildcard); - - // - return result; - } - - /// - /// Validate a Collection is Valid for Kafka Consumer ... - /// - /// - /// - public static bool IsAllowedCollection( - this string[] source - ) - { - // - var result = source.HasChild(); - - // - return result; - } - - /// - /// Validate Sender ... - /// - /// - /// - /// - public static bool IsValidSender( - this XEventMessage source, - string[] allowedSenders - ) - { - // - // Validate Source and Collection ... - var result = - source.IsValid() && - allowedSenders - .IsAllowedCollection(); - if (!result) - { - return result; - } - - // - // Validate Sender ... - result = - allowedSenders.IsAllowedWildcard() || - allowedSenders.Any(x => - x.Equals( - source.Sender, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Validate Action ... - /// - /// - /// - /// - public static bool IsValidAction( - this XEventMessage source, - string[] allowedActions - ) - { - // - // Validate Source and Collection ... - var result = - source.IsValid() && - allowedActions - .IsAllowedCollection(); - if (!result) - { - return result; - } - - // - // Validate Action ... - result = - allowedActions.IsAllowedWildcard() || - allowedActions.Any(x => - x.Equals( - source.Action, - System.StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Completely Validate a Message, based on providing: - /// - Allowed Actions - /// - Allowed Senders - /// - /// - /// - /// - /// - public static bool IsValid( - this XEventMessage source, - string[] allowedSenders, - string[] allowedActions - ) - { - // - var result = - source.IsValid() && - source.IsValidAction(allowedActions) && - source.IsValidSender(allowedSenders); - - // - return result; - } - - /// - /// Parse Url and Extract Host address ... - /// - /// - /// - public static string GetRabbitMQHost(this XEventServiceConfiguration source) - { - // - var result = string.Empty; - - // - if (!source.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - var parts = source.Url.Split(':'); - if (parts.Length != 2) - { - XException.InvalidConfiguration.Throw(); - } - - // - result = parts[0]; - if (result.IsNullOrEmpty() || - !result.IsValidUrl() - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - return result; - } - - /// - /// Parse Url and Extract Port Number ... - /// - /// - /// - public static int GetRabbitMQPort(this XEventServiceConfiguration source) - { - // - int result = -1; - - // - if (!source.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - - // - var parts = source.Url.Split(':'); - if (parts.Length != 2) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Try Parse Port as Integer ... - int.TryParse(parts[1], out result); - if (result <= 0) - { - XException.InvalidConfiguration.Throw(); - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Interfaces\IXEventServiceProvider.cs - -namespace xEventService.Interfaces -{ - public interface IXEventServiceProvider : IXProducerServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Interfaces\IXKafkaProducerService.cs - -namespace xEventService.Interfaces -{ - /// - /// a Service for Produce Kafka Messages ... - /// - public interface IXKafkaProducerService : IXProducerServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Interfaces\IXProducerServiceBase.cs - -using System; -using System.Threading; -using xEventService.Models; -using System.Threading.Tasks; -using xEventService.Constants; - -namespace xEventService.Interfaces -{ - public interface IXProducerServiceBase : IDisposable - { - /// - /// Sending Message ... - /// - /// an Instance of to Provides Kafka Messaging requirement ... - /// - /// - Task SendMessageAsync( - XEventRequest request, - CancellationToken cancellationToken = default - ); - - /// - /// Sending a Message ... - /// - /// an Instance of to Provides Kafka Messaging requirement ... - /// Topic for Sending Message ... - /// - /// - Task SendMessageAsync( - XEventMessage message, - string topic = XEventServiceConstants.XDefaultTopic, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Interfaces\IXRabbitMQProducerService.cs - -using System.Threading; -using xEventService.Models; -using System.Threading.Tasks; - -namespace xEventService.Interfaces -{ - /// - /// RabbitMQ Producer Service Implementation ... - /// - public interface IXRabbitMQProducerService : IXProducerServiceBase - { - /// - /// Sending a Message to Default Exchange ... - /// - /// - /// an Instance of ... - /// - /// - /// Target Exchange Name. if empty, uses default from configuration ... - /// - /// - /// Routing Key for message routing ... - /// - /// - /// - Task SendMessageAsync( - XEventMessage message, - string exchange = null, - string routingKey = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Interfaces\IXZeroMQProducerService.cs - -namespace xEventService.Interfaces -{ - public interface IXZeroMQProducerService : IXProducerServiceBase - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Models\XEventMessage.cs - -using System; -using Newtonsoft.Json; -using System.Collections.Generic; - -namespace xEventService.Models -{ - /// - /// a Message Descriptor for Events ... - /// - public class XEventMessage - { - /// - /// Specified Action for Fire ... - /// - [JsonRequired] - public string Action { get; set; } - - /// - /// Specified Action Sender ... - /// - [JsonRequired] - public string Sender { get; set; } - - /// - /// Sending Time ... - /// - [JsonRequired] - public DateTime Offset { get; set; } - - /// - /// Specified Message ... - /// - public string Message { get; set; } - - /// - /// Metadata for Message ... - /// - public IDictionary Payload { get; set; } = new Dictionary(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Models\XEventRequest.cs - -using xEventService.Constants; - -namespace xEventService.Models -{ - /// - /// a Request for Sending an Event ... - /// - public class XEventRequest - { - /// - /// Specified Which Kafka Topic ... - /// - public string Topic { get; set; } = XEventServiceConstants.XDefaultTopic; - - /// - /// Specified Kafka Meesage to Send ... - /// - public XEventMessage Message { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Models\XRabbitMQOptions.cs - -using xEventService.Constants; - -namespace xEventService.Models -{ - /// - /// RabbitMQ-specific connection and messaging options ... - /// - public class XRabbitMQOptions - { - - /// - /// Connection Username ... - /// - public string Username { get; set; } = "guest"; - - /// - /// Connection Password ... - /// - public string Password { get; set; } = "guest"; - - /// - /// Virtual Host ... - /// - public string VirtualHost { get; set; } = "/"; - - /// - /// Default Exchange Name ... - /// - public string Exchange { get; set; } = "x.saherelm.events"; - - /// - /// Default Exchange Type (fanout, direct, topic, headers) ... - /// - public XRabbitMQExchangeType ExchangeType { get; set; } = XRabbitMQExchangeType.Fanout; - - /// - /// Default Queue Name ... - /// if empty, a dynamic queue will be generated ... - /// - public string Queue { get; set; } = string.Empty; - - /// - /// Default Routing Key ... - /// - public string RoutingKey { get; set; } = string.Empty; - - /// - /// Exchange Durable Flag ... - /// - public bool ExchangeDurable { get; set; } = true; - - /// - /// Exchange AutoDelete Flag ... - /// - public bool ExchangeAutoDelete { get; set; } = false; - - /// - /// Queue Durable Flag ... - /// - public bool QueueDurable { get; set; } = true; - - /// - /// Queue Exclusive Flag ... - /// - public bool QueueExclusive { get; set; } = false; - - /// - /// Queue AutoDelete Flag ... - /// - public bool QueueAutoDelete { get; set; } = false; - - /// - /// Enable Automatic Recovery on Connection Loss ... - /// - public bool AutomaticRecoveryEnabled { get; set; } = true; - - /// - /// Network Recovery Interval in Seconds ... - /// - public int NetworkRecoveryIntervalSeconds { get; set; } = 5; - - /// - /// Prefetch Count for Consumer ... - /// - public ushort PrefetchCount { get; set; } = 1; - - /// - /// Enable Manual Acknowledgement ... - /// - public bool ManualAck { get; set; } = true; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Models\XZeroMQOptions.cs - -using xEventService.Constants; - -namespace xEventService.Models -{ - public class XZeroMQOptions - { - /// - /// Socket Pattern (PubSub, PushPull) ... - /// - public XZeroMQPattern Pattern { get; set; } = XZeroMQPattern.PubSub; - - /// - /// Bind or Connect ... - /// True for Server (Bind), False for Client (Connect) ... - /// - public bool IsServer { get; set; } = false; - - /// - /// High Water Mark for Sending ... - /// - public int SendHighWaterMark { get; set; } = 1000; - - /// - /// High Water Mark for Receiving ... - /// - public int ReceiveHighWaterMark { get; set; } = 1000; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XBaseEventConsumerBackgroundService.cs - -using System; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - /// - /// Base Event Consumer Service ... - /// - public abstract class XBaseEventConsumerBackgroundService : XResumableBackgroundService - { - /// - /// Consumed Topic Messages ... - /// - protected readonly string topic; - - /// - /// Allowed Senders ... - /// - protected readonly string[] allowedSenders; - - /// - /// Allowed Actions ... - /// - protected readonly string[] allowedActions; - - /// - /// Configuration ... - /// - protected readonly XEventServiceConfiguration configuration; - - protected XBaseEventConsumerBackgroundService( - string[] allowedActions, - string[] allowedSenders, - IServiceProvider serviceProvider, - XEventServiceConfiguration configuration, - ILogger logger, - string topic = XEventServiceConstants.XDefaultTopic - ) : base(serviceProvider, logger) - { - // - // Validate Actions ... - if (!allowedActions - .IsAllowedCollection() || - !allowedSenders - .IsAllowedCollection() || - !configuration.IsValid() - ) - { - XException.InvalidArgs.Throw(); - } - - // - this.topic = topic; - this.configuration = configuration; - this.allowedActions = allowedActions; - this.allowedSenders = allowedSenders; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XBaseEventProducerService.cs - -using xCommons.Extensions; -using xExceptions.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - public abstract class XBaseEventProducerService - { - protected readonly XEventServiceConfiguration configuration; - protected readonly ILogger logger; - - protected XBaseEventProducerService( - XEventServiceConfiguration configuration, - ILogger logger - ) - { - // - this.logger = logger; - this.configuration = configuration; - - // - // Validate Configurations ... - if (!configuration.IsValid()) - { - XException.InvalidConfiguration.Throw(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XEventServiceProvider.cs - -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Interfaces; -using xEventService.Configuration; - -namespace xEventService.Providers -{ - public class XEventServiceProvider : IXEventServiceProvider - { - // - private readonly XEventServiceConfiguration configuration; - private readonly IXKafkaProducerService kafkaProducerService; - private readonly IXZeroMQProducerService zeroMQProducerService; - private readonly IXRabbitMQProducerService rabbitMQProducerService; - - public XEventServiceProvider( - XEventServiceConfiguration configuration, - IXKafkaProducerService kafkaProducerService = null, - IXZeroMQProducerService zeroMQProducerService = null, - IXRabbitMQProducerService rabbitMQProducerService = null - ) - { - // - this.configuration = configuration; - this.kafkaProducerService = kafkaProducerService; - this.zeroMQProducerService = zeroMQProducerService; - this.rabbitMQProducerService = rabbitMQProducerService; - - // - // Validate ... - var isValid = configuration.IsValid() && - configuration.Broker == XEventBroker.XKafka - ? kafkaProducerService != null - : configuration.Broker == XEventBroker.XZeroMQ - ? zeroMQProducerService != null - : configuration.Broker == XEventBroker.XRabbitMQ - ? rabbitMQProducerService != null - : false; - if (!isValid) - { - XException.InvalidConfiguration.Throw(); - } - } - - /// - /// Send Message to Broker Using XEventRequest instance ... - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!request.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await SendMessageAsync( - topic: request.Topic, - message: request.Message, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Send Message to Broker Using XMessage instance ... - /// - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventMessage message, - string topic = XEventServiceConstants.XDefaultTopic, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - if (!message.IsValid()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = false; - switch (configuration.Broker) - { - // - case XEventBroker.XKafka: - result = await kafkaProducerService.SendMessageAsync( - topic: topic, - message: message, - cancellationToken: cancellationToken - ); - break; - - // - case XEventBroker.XZeroMQ: - result = await zeroMQProducerService.SendMessageAsync( - topic: topic, - message: message, - cancellationToken: cancellationToken - ); - break; - - // - case XEventBroker.XRabbitMQ: - result = await rabbitMQProducerService.SendMessageAsync( - topic: topic, - message: message, - cancellationToken: cancellationToken - ); - break; - } - - // - return result; - } - - /// - /// Dispose ... - /// - public void Dispose() - { - // - if (kafkaProducerService != null) - { - kafkaProducerService.Dispose(); - } - - // - if (zeroMQProducerService != null) - { - zeroMQProducerService.Dispose(); - } - - // - if (rabbitMQProducerService != null) - { - rabbitMQProducerService.Dispose(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XKafkaConsumerServiceBase.cs - -using System; -using Confluent.Kafka; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - /// - /// an Abstract Kafka Consumer Service ... - /// - public abstract class XKafkaConsumerServiceBase : XBaseEventConsumerBackgroundService - { - /// - /// Kafka Consumer Class ... - /// - protected readonly IConsumer consumer; - - protected XKafkaConsumerServiceBase( - string[] allowedActions, - string[] allowedSenders, - IServiceProvider serviceProvider, - XEventServiceConfiguration configuration, - ILogger logger, - string topic = XEventServiceConstants.XDefaultTopic - ) : base( - topic: topic, - logger: logger, - configuration: configuration, - allowedActions: allowedActions, - allowedSenders: allowedSenders, - serviceProvider: serviceProvider - ) - { - // - // Validating Configuration ... - if (configuration.Broker != XEventBroker.XKafka) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Prepare Kafka Consumer Configuration ... - var config = new ConsumerConfig - { - EnableAutoCommit = false, - BootstrapServers = configuration.Url, - AutoOffsetReset = AutoOffsetReset.Earliest, - GroupId = XEventServiceConstants.XDefaultConsumerGroup, - }; - consumer = new ConsumerBuilder(config).Build(); - } - - /// - /// Default Action Execution for Background Services ... - /// - /// - /// - protected override async Task ExecuteAsync( - CancellationToken cancellationToken = default - ) - { - // - // For Fix Blocking Synchronous ... - await Task.Yield(); - using var cts = new CancellationTokenSource(); - - // - // Subscribe to Topic ... - consumer.Subscribe(topic); - logger.LogInformation($"Kafka Cosume Topic: {topic} ..."); - - // - // Consuming ... - while (!cancellationToken.IsCancellationRequested) - { - try - { - // - // Consuming Topic ... - var consumeResult = consumer.Consume(cancellationToken); - if (!consumeResult.IsNullOrDefault() && - !consumeResult.Message.IsNullOrDefault() - ) - { - // - var message = consumeResult - .Message - .Value - .FromJSON(); - if (message.IsValid( - allowedSenders: allowedSenders, - allowedActions: allowedActions) - ) - { - // - await DoWorkAsync( - payload: message, - cancellationToken: cancellationToken - ); - } - } - } - catch (ConsumeException ex) - { - // - logger.LogError($"Kafka Consumer Result Parsing Error: {ex.Message} ..."); - await Task.Delay(1000, cancellationToken); - } - catch (Exception ex) - { - // - logger.LogError($"Kafka Consumer Result Parsing Error: {ex.Message} ..."); - await Task.Delay(1000, cancellationToken); - } - } - } - - /// - /// Dispose Object ... - /// - public override void Dispose() - { - // - if (consumer != null) - { - consumer.Close(); - consumer.Dispose(); - } - - // - GC.SuppressFinalize(this); - base.Dispose(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XKafkaProducerService.cs - -using System; -using Confluent.Kafka; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Interfaces; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - public class XKafkaProducerService : XBaseEventProducerService, IXKafkaProducerService - { - private readonly IProducer producer; - - public XKafkaProducerService( - ILogger logger, - XEventServiceConfiguration configuration - ) : base(configuration, logger) - { - // - // Validate Configurations ... - if (!configuration.IsValid() || - configuration.Broker != XEventBroker.XKafka - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Prepare Kafka Producer Configuration ... - var config = new ProducerConfig - { - Acks = Acks.All, - BootstrapServers = configuration.Url, - MessageSendMaxRetries = configuration.MaxRetries, - }; - producer = new ProducerBuilder(config).Build(); - } - - /// - /// Sending Message ... - /// - /// an Instance of to Provides Kafka Messaging requirement ... - /// - /// - public async Task SendMessageAsync( - XEventRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = request.IsValid(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await SendMessageAsync( - topic: request.Topic, - message: request.Message, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Sending a Message ... - /// - /// an Instance of to Provides Kafka Messaging requirement ... - /// Topic for Sending Message ... - /// - /// - public async Task SendMessageAsync( - XEventMessage message, - string topic = XEventServiceConstants.XDefaultTopic, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = message.IsValid() && - !topic.IsNullOrEmpty(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - try - { - // - var response = await producer.ProduceAsync( - topic: topic, - message: new Message - { - Value = message - .ToJSON(camelCase: true) - }, - cancellationToken: cancellationToken - ); - - // - result = !response.IsNullOrDefault(); - } - catch (Exception ex) - { - // - logger.LogError($"Kafka Produce Error: {ex.Message} ..."); - result = false; - } - - // - return result; - } - - /// - /// Dispose Required Objects ... - /// - public void Dispose() - { - // - if (producer != null) - { - producer.Dispose(); - } - - // - GC.SuppressFinalize(this); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XRabbitMQConsumerServiceBase.cs - -using System; -using System.Text; -using RabbitMQ.Client; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using RabbitMQ.Client.Events; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - /// - /// an Abstract Kafka Consumer Service ... - /// - public abstract class XRabbitMQConsumerServiceBase : XBaseEventConsumerBackgroundService - { - // - protected IModel channel; - protected IConnection connection; - protected AsyncEventingBasicConsumer consumer; - - protected XRabbitMQConsumerServiceBase( - string[] allowedActions, - string[] allowedSenders, - IServiceProvider serviceProvider, - XEventServiceConfiguration configuration, - ILogger logger, - string topic = XEventServiceConstants.XDefaultTopic - ) : base( - topic: topic, - logger: logger, - configuration: configuration, - allowedActions: allowedActions, - allowedSenders: allowedSenders, - serviceProvider: serviceProvider - ) - { - // - // Validating Configuration ... - if (!configuration.RabbitMQ.IsValid() || - configuration.Broker != XEventBroker.XRabbitMQ - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - SetupConnection(); - DeclareTopology(topic); - consumer = new AsyncEventingBasicConsumer(channel); - } - - /// - /// Default Action Execution for Background Services ... - /// - /// - /// - protected override async Task ExecuteAsync( - CancellationToken cancellationToken = default - ) - { - // - // For Fix Blocking Synchronous ... - await Task.Yield(); - using var cts = new CancellationTokenSource(); - logger.LogInformation($"RabbitMQ Cosume Topic: {topic} ..."); - - // - // Subscribe to Topic ... - consumer.Received += async (model, ea) => - { - // - try - { - // - var body = ea.Body.ToArray(); - var json = Encoding.UTF8.GetString(body); - var message = json.FromJSON(); - if (!message.IsNullOrDefault() && - message.IsValid( - allowedSenders: allowedSenders, - allowedActions: allowedActions) - ) - { - // - await DoWorkAsync( - payload: message, - cancellationToken: cancellationToken - ); - } - - // - if (configuration.RabbitMQ.ManualAck) - { - // - channel.BasicAck( - multiple: false, - deliveryTag: ea.DeliveryTag - ); - } - } - catch (Exception ex) - { - // - logger.LogError($"RabbitMQ Cosume Error: {ex.Message} ..."); - if (configuration.RabbitMQ.ManualAck) - { - // - channel.BasicNack( - requeue: true, - multiple: false, - deliveryTag: ea.DeliveryTag - ); - } - } - }; - - // - consumer.Shutdown += (model, ea) => - { - return Task.CompletedTask; - }; - - // - channel.BasicQos( - prefetchSize: 0, - global: false, - prefetchCount: configuration.RabbitMQ.PrefetchCount - ); - - // - channel.BasicConsume( - queue: GetQueueName(), - consumer: consumer, - autoAck: !configuration.RabbitMQ.ManualAck - ); - - // - while (!cancellationToken.IsCancellationRequested) - { - await Task.Delay(1000, cancellationToken); - } - } - - /// - /// Overriding Stop Action ... - /// - /// - /// - public override async Task StopAsync(CancellationToken cancellationToken) - { - // - if (channel != null) - { - // - channel.Close(); - channel.Dispose(); - } - - // - if (connection != null) - { - // - connection.Close(); - connection.Dispose(); - } - - // - await base.StopAsync(cancellationToken); - } - - /// - /// Dispose Implementation ... - /// - public override void Dispose() - { - // - if (channel != null) - { - channel.Dispose(); - } - - // - if (connection != null) - { - connection.Dispose(); - } - - // - GC.SuppressFinalize(this); - base.Dispose(); - } - - // - #region Private ... - private string GetQueueName() - { - // - var result = string.Empty; - if (!configuration.RabbitMQ.Queue.IsNullOrEmpty()) - { - result = configuration.RabbitMQ.Queue; - } - - // - if (result.IsNullOrEmpty()) - { - // - var exchangeName = topic ?? configuration.RabbitMQ.Exchange; - var digits = Guid.NewGuid().ToString().GetDigits(); - result = $"{exchangeName}[{digits}]"; - } - - // - return result; - } - - private void SetupConnection() - { - var factory = new ConnectionFactory - { - DispatchConsumersAsync = true, - Port = configuration.GetRabbitMQPort(), - HostName = configuration.GetRabbitMQHost(), - UserName = configuration.RabbitMQ.Username, - Password = configuration.RabbitMQ.Password, - NetworkRecoveryInterval = TimeSpan.FromSeconds( - configuration.RabbitMQ.NetworkRecoveryIntervalSeconds - ), - VirtualHost = configuration.RabbitMQ.VirtualHost, - AutomaticRecoveryEnabled = configuration.RabbitMQ.AutomaticRecoveryEnabled, - }; - - // - connection = factory.CreateConnection(); - channel = connection.CreateModel(); - } - - private void DeclareTopology(string topic) - { - // - channel.ExchangeDeclare( - arguments: null, - exchange: topic ?? configuration.RabbitMQ.Exchange, - durable: configuration.RabbitMQ.ExchangeDurable, - autoDelete: configuration.RabbitMQ.ExchangeAutoDelete, - type: configuration.RabbitMQ.ExchangeType.GetStringValue() - ); - - // - var queueName = GetQueueName(); - - // - channel.QueueDeclare( - arguments: null, - queue: queueName, - durable: configuration.RabbitMQ.QueueDurable, - exclusive: configuration.RabbitMQ.QueueExclusive, - autoDelete: configuration.RabbitMQ.QueueAutoDelete - ); - - // - channel.QueueBind( - arguments: null, - queue: queueName, - exchange: topic ?? configuration.RabbitMQ.Exchange, - routingKey: configuration.RabbitMQ.RoutingKey - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XRabbitMQProducerService.cs - -using System; -using System.Text; -using RabbitMQ.Client; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Interfaces; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - /// - /// RabbitMQ Producer Service Implementation ... - /// - public class XRabbitMQProducerService : XBaseEventProducerService, IXRabbitMQProducerService - { - private IModel channel; - private IConnection connection; - private readonly object connectionLock = new(); - - public XRabbitMQProducerService( - ILogger logger, - XEventServiceConfiguration configuration - ) : base(configuration, logger) - { - // - // Validate Configurations ... - if (!configuration.IsValid() || - !configuration.RabbitMQ.IsValid() || - configuration.Broker != XEventBroker.XRabbitMQ - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Initialize Connection ... - CreateConnection(); - } - - /// - /// Sending Message with Full Request Descriptor ... - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = request.IsValid(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await SendMessageAsync( - message: request.Message, - exchange: request.Topic, - cancellationToken: cancellationToken, - routingKey: configuration.RabbitMQ.RoutingKey - ); - - // - return result; - } - - /// - /// Sending a Message to Topic ... - /// - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventMessage message, - string topic = XEventServiceConstants.XDefaultTopic, - CancellationToken cancellationToken = default - ) - { - // - var result = await SendMessageAsync( - request: new XEventRequest - { - Topic = topic, - Message = message - }, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Sending a Message to Exchange ... - /// - /// - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventMessage message, - string exchange = null, - string routingKey = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = message.IsValid(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize Exchange ... - if (exchange.IsNullOrEmpty()) - { - exchange = configuration.RabbitMQ.Exchange; - } - - // - // Normalize Routing Key ... - if (routingKey.IsNull()) - { - routingKey = configuration.RabbitMQ.RoutingKey; - } - - // - try - { - // - // Ensure Connection is Alive ... - EnsureChannel(); - - // - // Serialize Message ... - var body = Encoding.UTF8.GetBytes( - message.ToJSON(camelCase: true) - ); - - // - // Prepare Message Properties ... - var properties = channel.CreateBasicProperties(); - properties.Persistent = true; - properties.ContentType = "application/json"; - properties.Timestamp = new AmqpTimestamp( - DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ); - properties.MessageId = Guid.NewGuid().ToString(); - properties.Type = message.Action; - properties.AppId = message.Sender; - - // - // Publish Message ... - await Task.Run(() => - { - // - channel.BasicPublish( - exchange: exchange, - routingKey: routingKey, - mandatory: false, - basicProperties: properties, - body: body - ); - }, - cancellationToken: cancellationToken); - - // - result = true; - } - catch (Exception ex) - { - // - logger.LogError($"RabbitMQ Produce Error: {ex.Message} ..."); - result = false; - } - - // - return result; - } - - /// - /// Dispose Object ... - /// - public void Dispose() - { - // - try - { - // - if (channel != null) - { - // - channel.Close(); - channel.Dispose(); - channel = null; - } - - // - if (connection != null) - { - // - connection.Close(); - connection.Dispose(); - connection = null; - } - } - catch - { } - - // - GC.SuppressFinalize(this); - } - - // - #region Private ... - /// - /// Create Connection to RabbitMQ Server ... - /// - private void CreateConnection() - { - // - var factory = new ConnectionFactory - { - Port = configuration.GetRabbitMQPort(), - HostName = configuration.GetRabbitMQHost(), - UserName = configuration.RabbitMQ.Username, - Password = configuration.RabbitMQ.Password, - VirtualHost = configuration.RabbitMQ.VirtualHost, - AutomaticRecoveryEnabled = configuration.RabbitMQ.AutomaticRecoveryEnabled, - NetworkRecoveryInterval = TimeSpan.FromSeconds( - configuration.RabbitMQ.NetworkRecoveryIntervalSeconds - ), - DispatchConsumersAsync = true - }; - - // - connection = factory.CreateConnection(); - } - - /// - /// Check Connection is Alive ... - /// - private bool IsConnected() - { - // - var result = - !connection.IsNullOrDefault() && - connection.IsOpen && - !channel.IsNull() && - channel.IsOpen; - - // - return result; - } - - /// - /// Ensure Channel is Open and Exchange/Queue Declared ... - /// - private void EnsureChannel() - { - // - if (IsConnected()) - { - return; - } - - // - lock (connectionLock) - { - // - // Double Check after Lock ... - if (IsConnected()) - { - return; - } - - // - // Recreate Connection if Dead ... - if (connection is null || !connection.IsOpen) - { - CreateConnection(); - } - - // - // Create Channel ... - channel = connection.CreateModel(); - - // - // Declare Exchange ... - channel.ExchangeDeclare( - arguments: null, - exchange: configuration.RabbitMQ.Exchange, - durable: configuration.RabbitMQ.ExchangeDurable, - autoDelete: configuration.RabbitMQ.ExchangeAutoDelete, - type: configuration.RabbitMQ.ExchangeType.GetStringValue() - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XZeroMQConsumerServiceBase.cs - -using NetMQ; -using System; -using System.Text; -using NetMQ.Sockets; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - /// - /// an Abstract ZeroMQ Consumer Service ... - /// - public abstract class XZeroMQConsumerServiceBase : XBaseEventConsumerBackgroundService - { - // - private NetMQSocket socket; - - protected XZeroMQConsumerServiceBase( - string[] allowedActions, - string[] allowedSenders, - IServiceProvider serviceProvider, - XEventServiceConfiguration configuration, - ILogger logger, - string topic = XEventServiceConstants.XDefaultTopic - ) : base( - topic: topic, - logger: logger, - configuration: configuration, - allowedActions: allowedActions, - allowedSenders: allowedSenders, - serviceProvider: serviceProvider - ) - { - // - // Validating Configuration ... - if (!configuration.ZeroMQ.IsValid() || - configuration.Broker != XEventBroker.XZeroMQ) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Initialize ... - InitializeSocket(); - } - - /// - /// Default Action Execution for Background Services ... - /// - /// - /// - protected override async Task ExecuteAsync( - CancellationToken cancellationToken = default - ) - { - // - await Task.Yield(); - logger.LogInformation($"ZeroMQ Cosume Topic: {topic} ..."); - while (!cancellationToken.IsCancellationRequested) - { - // - try - { - // - string receivedTopic = string.Empty; - byte[] body = null; - - // - if (configuration.ZeroMQ.Pattern == XZeroMQPattern.PubSub) - { - // - if (socket.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out receivedTopic)) - { - // - if (socket.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(100), out body)) - { - // Process - } - else - { - logger.LogError($"ZeroMQ Cosume Error ..."); - } - } - } - else - { - if (socket.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(100), out body)) - { - // Process - } - else - { - logger.LogError($"ZeroMQ Cosume Error ..."); - } - } - - // - if (body != null && body.Length > 0) - { - // - var json = Encoding.UTF8.GetString(body); - var message = json.FromJSON(); - if (!message.IsNullOrDefault() && - message.IsValid( - allowedSenders: allowedSenders, - allowedActions: allowedActions) - ) - { - // - await DoWorkAsync( - payload: message, - cancellationToken: cancellationToken - ); - } - } - else - { - await Task.Delay(10, cancellationToken); - } - } - catch (Exception ex) - { - // - logger.LogError($"ZeroMQ Cosume Error: {ex.Message} ..."); - await Task.Delay(1000, cancellationToken); - } - } - } - - public override async Task StopAsync(CancellationToken cancellationToken) - { - // - if (socket != null) - { - socket.Close(); - } - - // - await base.StopAsync(cancellationToken); - } - - /// - /// Dispose Object ... - /// - public override void Dispose() - { - // - if (socket != null) - { - socket.Dispose(); - } - - // - GC.SuppressFinalize(this); - base.Dispose(); - } - - // - #region Private ... - private void InitializeSocket() - { - // - if (configuration.ZeroMQ.Pattern == XZeroMQPattern.PubSub) - { - // - socket = new SubscriberSocket(); - socket.Options.ReceiveHighWatermark = configuration.ZeroMQ.ReceiveHighWaterMark; - - // - // Subscribe to specific topic or all - if (topic.IsNullOrEmpty() || topic == XEventServiceConstants.XWildcard) - { - ((SubscriberSocket)socket).SubscribeToAnyTopic(); - } - else - { - ((SubscriberSocket)socket).Subscribe(topic); - } - } - else - { - // - socket = new PullSocket(); - socket.Options.ReceiveHighWatermark = configuration.ZeroMQ.ReceiveHighWaterMark; - } - - // - if (configuration.ZeroMQ.IsServer) - { - socket.Bind(configuration.Url); - } - else - { - socket.Connect(configuration.Url); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xEventService\Providers\XZeroMQProducerService.cs - -using NetMQ; -using System; -using System.Text; -using NetMQ.Sockets; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xEventService.Constants; -using xEventService.Extensions; -using xEventService.Interfaces; -using xEventService.Configuration; -using Microsoft.Extensions.Logging; - -namespace xEventService.Providers -{ - public class XZeroMQProducerService : XBaseEventProducerService, IXZeroMQProducerService - { - // - private NetMQSocket socket; - private readonly object socketLock = new(); - - public XZeroMQProducerService( - XEventServiceConfiguration configuration, - ILogger logger - ) : base(configuration, logger) - { - // - // Validate Configurations ... - if (!configuration.IsValid() || - !configuration.ZeroMQ.IsValid() || - configuration.Broker != XEventBroker.XZeroMQ - ) - { - XException.InvalidConfiguration.Throw(); - } - - // - InitializeSocket(); - } - - /// - /// Sending Message with Full Request Descriptor ... - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventRequest request, - CancellationToken cancellationToken = default - ) - { - // - var result = request.IsValid(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await SendMessageAsync( - message: request.Message, - topic: request.Topic, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Sending a Message to Topic ... - /// - /// - /// - /// - /// - public async Task SendMessageAsync( - XEventMessage message, - string topic = XEventServiceConstants.XDefaultTopic, - CancellationToken cancellationToken = default - ) - { - // - var result = message.IsValid(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize Topic ... - if (topic.IsNullOrEmpty()) - { - topic = XEventServiceConstants.XDefaultTopic; - } - - // - try - { - // - var json = message.ToJSON(camelCase: true); - var body = Encoding.UTF8.GetBytes(json); - await Task.Run(() => - { - // - lock (socketLock) - { - // - if (configuration.ZeroMQ.Pattern == XZeroMQPattern.PubSub) - { - socket.SendMoreFrame(topic).SendFrame(body); - } - else - { - socket.SendFrame(body); - } - } - }, cancellationToken); - - // - result = true; - } - catch (Exception) - { - result = false; - } - - // - return result; - } - - /// - /// Dispose Object ... - /// - public void Dispose() - { - // - try - { - // - lock (socketLock) - { - // - if (socket != null) - { - // - socket.Close(); - socket.Dispose(); - socket = null; - } - } - } - catch { } - - // - GC.SuppressFinalize(this); - } - - // - #region Private ... - /// - /// Initialize Socket ... - /// - private void InitializeSocket() - { - // - lock (socketLock) - { - // - if (configuration.ZeroMQ.Pattern == XZeroMQPattern.PubSub) - { - // - socket = new PublisherSocket(); - socket.Options.SendHighWatermark = configuration.ZeroMQ.SendHighWaterMark; - } - else - { - // - socket = new PushSocket(); - socket.Options.SendHighWatermark = configuration.ZeroMQ.SendHighWaterMark; - } - - // - if (configuration.ZeroMQ.IsServer) - { - socket.Bind(configuration.Url); - } - else - { - socket.Connect(configuration.Url); - } - } - } - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xExceptions-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xExceptions-20261109_152620.txt deleted file mode 100644 index 079a537..0000000 --- a/Documents/GeneratedContext/xDashboard-xExceptions-20261109_152620.txt +++ /dev/null @@ -1,253 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xExceptions\Attributes\StringValueAttribute.cs - -using System; - -namespace xExceptions.Attributes -{ - /// - /// an attribute which attached to enums to carry propper string - /// - public partial class StringValueAttribute : Attribute { - public string StringValue { get; set; } - - public StringValueAttribute (string value) { - this.StringValue = value; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xExceptions\Constants\XException.cs - -using xExceptions.Attributes; - -namespace xExceptions.Constants -{ - public enum XException { - // - #region Invalid Exceptions 1xx ... - [StringValue ("Invalid Data ...")] - InvalidData = 100, - - // - [StringValue ("Invalid Date ...")] - InvalidDate = 101, - - // - [StringValue ("Bad Request ...")] - BadRequest = 102, - - // - [StringValue ("Invalid Args ...")] - InvalidArgs = 103, - - // - [StringValue ("Invalid Message ...")] - InvalidMessage = 104, - - // - [StringValue ("Invalid Token ...")] - InvalidToken = 105, - - // - [StringValue ("Invalid Verification Code ...")] - InvalidVerificationCode = 106, - - // - [StringValue ("Invalid Email Address ...")] - InvalidEmailAddress = 107, - - // - [StringValue ("Invalid Mobile Number ...")] - InvalidMobileNumber = 108, - - // - [StringValue ("Invalid Password ...")] - InvalidPassword = 109, - - // - [StringValue ("Inavlid Url ...")] - InavlidUrl = 110, - - // - [StringValue ("Invalid Device ...")] - InvalidDevice = 111, - - // - [StringValue ("Invalid Profile Image ...")] - InvalidProfileImage = 112, - - // - [StringValue ("Invalid File ...")] - InavlidFile = 113, - - // - [StringValue ("Invalid Username ...")] - InvalidUserName = 114, - #endregion - - // - #region Not (...) Exceptions 2xx ... - // - [StringValue ("Not Found ...")] - NotFound = 200, - - // - [StringValue ("Not Allowed ...")] - NotAllowed = 201, - - // - [StringValue ("Not Authorized ...")] - NotAuthorized = 202, - - // - [StringValue ("Not Visible ...")] - NotVisible = 203, - #endregion - - // - #region User/Registration/Account/Bann Exceptions 3xx ... - // - [StringValue ("Account Locked out Until:{0}")] - AccountLockedOut = 300, - - // - [StringValue ("Login Failed ...")] - LoginFailed = 301, - - // - [StringValue ("User Registered Before ...")] - UserRegisteredBefore = 302, - - // - [StringValue ("User Disabled ...")] - UserDisabled = 303, - // - [StringValue ("Device Banned Until:{0}")] - DeviceBanned = 304, - - // - [StringValue ("You can't Request Verification code Until:{0}")] - VerificationCodeResendNotAllowed = 305, - - // - [StringValue ("Passwords Same ...")] - PasswordsSame = 306, - - // - [StringValue ("Mobiles Same ...")] - MobilesSame = 307, - - // - [StringValue ("Emails Same ...")] - EmailsSame = 308, - - // - [StringValue ("Mobile In Used ...")] - MobileInUsed = 309, - - // - [StringValue ("Email In Used ...")] - EmailInUsed = 310, - - // - [StringValue ("Mobile Not Confirmed ...")] - MobileNotConfirmed = 311, - - // - [StringValue ("Email Not Confirmed ...")] - EmailNotConfirmed = 312, - - // - [StringValue ("Post Banned ...")] - PostBanned = 313, - - // - [StringValue ("User Banned ...")] - UserBanned = 314, - #endregion - - // - #region General Exceptions 4xx ... - // - [StringValue ("Unknown Error ...")] - Unknown = 400, - - // - [StringValue ("Duplicate ...")] - Duplicate = 401, - - // - [StringValue ("Action Failed ...")] - ActionFailed = 402, - - // - [StringValue ("Expired Date ...")] - ExpiredDate = 403, - - // - [StringValue ("Unavailable ...")] - Unavailable = 404, - - // - [StringValue ("Max Allowed Tag Exceeded ...")] - MaxAllowedTagExceeded = 405, - - // - [StringValue ("Timed out ...")] - Timeout = 406, - #endregion - - // - #region File Exceptions 5xx ... - // - [StringValue ("Empty File ...")] - EmptyFile = 500, - - // - [StringValue ("max File size exceeded ...")] - MaxFileSizeExceeded = 501, - - // - [StringValue ("Unsupported File Type ...")] - UnsupportedFileType = 502, - - // - [StringValue ("Max Allowed Media Exceeded ...")] - MaxAllowedMediaExceeded = 503, - #endregion - - // - #region Configuration Exceptions 6xx ... - // - [StringValue ("Invalid Configuration ...")] - InvalidConfiguration = 600, - - // - [StringValue ("Storage Service Initiallization Failed ...")] - StorageServiceInitialFailed = 601, - - // - [StringValue ("Message Service Initialization Failed ...")] - MessageServiceInitialFailed = 602, - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xExceptions\Models\XError.cs - -namespace xExceptions.Models { - public partial class XError { - /// - /// th ID of Error - /// - /// - public int Id { get; set; } - - /// - /// the String Value of Error - /// - /// - public string Message { get; set; } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xFileService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xFileService-20261109_152620.txt deleted file mode 100644 index 889424d..0000000 --- a/Documents/GeneratedContext/xDashboard-xFileService-20261109_152620.txt +++ /dev/null @@ -1,3351 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Configurations\Entities\XFileEntityConfiguration.cs - -using System; -using xDataService.Providers; -using xFileService.Constants; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xFileService.Configurations.Entities -{ - public class XFileEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XFileServiceConstants.XFileTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Constants\XFileServiceConstants.cs - -using xFileService.Models.Entities; - -namespace xFileService.Constants -{ - public struct XFileServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XFileServiceDILogTag = "XFileService"; - - // - // Table Mapping Identifiers ... - public const string XFileTable = "Files"; - - // - // GraphQL Collection Mappings ... - public const string XFileSingleName = "file"; - public const string XFileCollectionName = "files"; - - // - // Hubs ... - public const string XFileDtoHub = "fileDto"; - public const string XFileEntityHub = "fileEntity"; - - // - // Custome Constants ... - public const string XFileTagProvided = nameof(XFile); - - public const string XAdminRole = "admin"; - - // - // EF Repositories Helper Extensions ... - public const string GetXFileEFRepositoryDescriptor = "GetXFileEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Controllers\XFileProviderControllerBase.cs - -using System; -using System.Linq; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xFileService.Interfaces; -using xTagService.Controllers; -using Microsoft.AspNetCore.Mvc; -using xFileService.Models.Dtos; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xFileService.Providers.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xFileService.Controllers -{ - public abstract class XFileProviderControllerBase : XBaseProvidedHasTagControllerBase, IXFileProviderController - { - private readonly IXFileProvider provider; - - protected XFileProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXFileProvider provider, - IXFileTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - tagProvided, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { - this.provider = provider; - } - - // - #region Tools ... - /// - /// Stream Specified File ... - /// - /// - /// - /// - [HttpGet("{id}/Stream/ById")] - public virtual async Task Stream( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider.Stream( - id: id, - cancellationToken: cancellationToken - ); - - // - return result; - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Stream Specified File ... - /// - /// - /// - /// - [HttpGet("{name}/Stream/ByName")] - public virtual async Task Stream( - [FromRoute] string name, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider.Stream( - name: name, - cancellationToken: cancellationToken - ); - - // - return result; - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Download Specified File ... - /// - /// - /// - /// - [HttpGet("{id}/Download/ById")] - public virtual async Task Download( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider.Download( - id: id, - cancellationToken: cancellationToken - ); - - // - return result; - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Download Specified File ... - /// - /// - /// - /// - [HttpGet("{name}/Download/ByName")] - public virtual async Task Download( - string name, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider.Download( - name: name, - cancellationToken: cancellationToken - ); - - // - return result; - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Upload Files ... - /// - /// - /// - /// - [HttpPost("Upload")] - [RequestSizeLimit(966_367_641)] - public virtual async Task>> Upload( - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Retrieve User Info ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Upload( - files: files, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Files ... - /// - /// - /// - /// - [HttpDelete("")] - public virtual async Task>> Remove( - [FromQuery] string ids, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Retrieve User Info ... - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - ids: ids, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Reference ... - /// - /// Check an Item Has Reference to Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/Reference/IsProvidedFor")] - public virtual async Task> IsProvidedFor( - [FromRoute] Guid id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotEmpty(providedFor) - .AddNotNull(forProvidedId) - .ValidateGroupAsync(); - - // - var result = await provider.IsProvidedFor( - id: id, - providedFor: providedFor, - forProvidedId: forProvidedId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add a Reference to Item for Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("{id}/Reference")] - public virtual async Task AddReference( - [FromRoute] Guid id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - [FromQuery] int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotEmpty(providedFor) - .AddNotNull(forProvidedId) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - await provider.AddReference( - id: id, - forIndex: forIndex, - userInfo: userInfo, - providedFor: providedFor, - connectionId: connectionId, - forProvidedId: forProvidedId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove a Reference from Item for Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}/Reference")] - public virtual async Task RemoveReference( - [FromRoute] Guid id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - [FromQuery] int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotEmpty(providedFor) - .AddNotNull(forProvidedId) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - await provider.RemoveReference( - id: id, - forIndex: forIndex, - userInfo: userInfo, - providedFor: providedFor, - connectionId: connectionId, - forProvidedId: forProvidedId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve References of Specified Itemfor providedFor ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/References")] - public virtual async Task>>> GetReferences( - [FromRoute] Guid id, - [FromQuery] string providedFor, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotEmpty(providedFor) - .ValidateGroupAsync(); - - // - var result = await provider.GetReferences( - id: id, - providedFor: providedFor, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Controllers\XFileRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xFileService.Controllers -{ - public abstract class XFileRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XFileRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXFileRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Controllers\XFileRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xFileService.Models.Entities; -using xFileService.Providers.Entities; -using xFileService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xFileService.Controllers -{ - public abstract class XFileRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XFileRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXFileRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Controllers\XFileServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using xFileService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xFileService.Controllers -{ - public abstract class XFileServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XFileServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXFileRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Controllers\XFileServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xFileService.Models.Dtos; -using xPushService.Controllers; -using xFileService.Providers.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xFileService.Controllers -{ - public abstract class XFileServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XFileServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXFileServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xPushService.Helpers; -using xFileService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xFileService.Providers; -using xFileService.Constants; -using xFileService.Interfaces; -using xFileService.Providers.Dtos; -using Microsoft.AspNetCore.Builder; -using xFileService.Interfaces.Dtos; -using xFileService.Providers.Entities; -using xFileService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xFileService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXFileService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddFileService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXFileService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddFileService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XFileService Middleware ... - /// - /// - /// - public static void UseXFileService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XFile Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XFileServiceConstants.XFileDtoHub); - pushHelper.AddHub(XFileServiceConstants.XFileEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XFile Repository Descriptor ... - if (!descriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XFileServiceConstants.XFileServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddFileService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - descriptor = typeof(XFileServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XFileServiceConstants.GetXFileEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - descriptor = XFileServiceHelper.GetXFileMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - descriptor = XFileServiceHelper.GetXFileInMemoryRepositoryDescriptor(); - break; - } - - // - // Register XFile Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: descriptor - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXFileServiceProvider), typeof(XFileServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXFileRepositoryService), typeof(XFileRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXFileRepositoryProvider), typeof(XFileRepositoryProvider), lifeTime) - ); - - // - // Register Additional Service ... - services.Add( - new ServiceDescriptor(typeof(IXFileTagProvider), typeof(XFileTagProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXFileTagProvided), typeof(XFileTagProvided), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXFileProvider), typeof(XFileProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Extensions\XModelExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Extensions; -using xFileService.Models.Dtos; -using System.Collections.Generic; -using xFileService.Models.Entities; - -namespace xFileService.Extensions -{ - public static class XModelExtensions - { - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XFile source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XFileDto source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XFile UpdateReferences( - this XFile source, - IList> references, - bool forceClean = true - ) - { - // - XFile result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XFileDto UpdateReferences( - this XFileDto source, - IList> references, - bool forceClean = true - ) - { - // - XFileDto result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Helpers\XFileServiceHelper.cs - -using System; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xFileService.Models.Entities; -using xFileService.Providers.GraphQL; -using xFileService.Providers.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Helpers -{ - public static class XFileServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileEFRepository, - TContext - > GetXFileEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileEFRepository, - TContext, - IXFileSeeder, - TSeederImplementation - > GetXFileEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileEFRepository, - TContext, - IXFileSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileMongoRepository - > GetXFileMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileMongoRepository, - IXFileSeeder, - TSeederImplementation - > GetXFileMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileMongoRepository, - IXFileSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileInMemoryRepository - > GetXFileInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileInMemoryRepository, - IXFileSeeder, - TSeederImplementation - > GetXFileInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XFile, - Guid, - IXFileKeyGenerator, - XFileKeyGenerator, - IXFileRepositoryEvents, - XFileRepositoryEvents, - XFileGraphType, - GuidGraphType, - XFileGraphQuery, - IXFileGraphQLTypeHelper, - XFileGraphQLTypeHelper, - XFileGraphSchema, - IXFileRepository, - XFileInMemoryRepository, - IXFileSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\IXFileProvider.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xTagService.Interfaces; -using xFileService.Models.Dtos; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xFileService.Providers.Dtos; -using xIdentityService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces -{ - public interface IXFileProvider : IXBaseProvidedHasTag, IXBaseReferenced - { - // - #region Tools ... - /// - /// Stream Specified File ... - /// - /// - /// - /// - Task Stream( - Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Stream Specified File ... - /// - /// - /// - /// - Task Stream( - string name, - CancellationToken cancellationToken = default - ); - - /// - /// Download Specified File ... - /// - /// - /// - /// - Task Download( - Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Download Specified File ... - /// - /// - /// - /// - Task Download( - string name, - CancellationToken cancellationToken = default - ); - - /// - /// Upload Files ... - /// - /// - /// - /// - /// - /// - Task> Upload( - IFormFileCollection files, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Upload File ... - /// - /// - /// - /// - /// - /// - Task Upload( - IFormFile file, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Files ... - /// - /// - /// - /// - /// - /// - Task> Remove( - string ids, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified File Streaming Info ... - /// - /// - /// - /// - Task GetFileDescriptor( - Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified File Streaming Info ... - /// - /// - /// - /// - Task GetFileDescriptor( - string fileName, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\IXFileProviderController.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using xTagService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using xFileService.Models.Dtos; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xFileService.Providers.Dtos; -using xIdentityService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces -{ - public interface IXFileProviderController : IXBaseProvidedHasTagController, IXBaseReferencedController - { - // - #region Tools ... - /// - /// Stream Specified File ... - /// - /// - /// - /// - [HttpGet("{id}/Stream/ById")] - Task Stream( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Stream Specified File ... - /// - /// - /// - /// - [HttpGet("{name}/Stream/ByName")] - Task Stream( - [FromRoute] string name, - CancellationToken cancellationToken = default - ); - - /// - /// Download Specified File ... - /// - /// - /// - /// - [HttpGet("{id}/Download/ById")] - Task Download( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Download Specified File ... - /// - /// - /// - /// - [HttpGet("{name}/Download/ByName")] - Task Download( - string name, - CancellationToken cancellationToken = default - ); - - /// - /// Upload Files ... - /// - /// - /// - /// - [HttpPost("Upload")] - [RequestSizeLimit(966_367_641)] - Task>> Upload( - [FromForm] IFormFileCollection files, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Files ... - /// - /// - /// - /// - [HttpDelete("")] - Task>> Remove( - [FromQuery] string ids, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\IXFileTagProvided.cs - -using System; -using xTagService.Interfaces; -using xFileService.Models.Dtos; -using xFileService.Providers.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces -{ - public interface IXFileTagProvided : IXTagProvided - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\IXFileTagProvider.cs - -using System; -using xTagService.Interfaces; - -namespace xFileService.Interfaces -{ - public interface IXFileTagProvider : IXBaseTagProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Dtos\IXFileDtoHub.cs - -using System; -using xPushService.Interfaces; -using xFileService.Models.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Dtos -{ - public interface IXFileDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Dtos\IXFileRepositoryService.cs - -using System; -using xDataService.Interfaces; -using xFileService.Models.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Dtos -{ - public interface IXFileRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Dtos\IXFileServiceProvider.cs - -using System; -using xPushService.Interfaces; -using xFileService.Models.Dtos; -using xFileService.Providers.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Dtos -{ - public interface IXFileServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileEntityHub.cs - -using System; -using xPushService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileRepository.cs - -using System; -using xDataService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileRepositoryEvents.cs - -using xDataService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xFileService.Models.Entities; -using xFileService.Providers.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Interfaces\Entities\IXFileSeeder.cs - -using System; -using xDataService.Interfaces; -using xFileService.Models.Entities; - -namespace xFileService.Interfaces.Entities -{ - public interface IXFileSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Models\Dtos\XFileDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xCommons.Constants; - -namespace xFileService.Models.Dtos -{ - public class XFileDto : XBaseGuidIDEntityDto - { - public XFileType Type { get; set; } - public string Name { get; set; } - public string Thumb { get; set; } - public string Path { get; set; } - public string ThumbPath { get; set; } - public DateTime UploadedOn { get; set; } - public string FileName { get; set; } - - public string OwnerId { get; set; } - public XPersonDto Owner { get; set; } - - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Models\Dtos\XFileStreamDescriptorDto.cs - -using System.IO; -using xModels.Base; - -namespace xFileService.Models.Dtos -{ - public class XFileStreamDescriptorDto : XBaseDto - { - public Stream Stream { get; set; } - public string MIMEType { get; set; } - public string Name { get; set; } - public string Path { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Models\Entities\XFile.cs - -using System; -using xModels.Base; -using xCommons.Constants; -using System.ComponentModel.DataAnnotations; - -namespace xFileService.Models.Entities -{ - /// - /// Specified File in Server ... - /// - public class XFile : XBaseGuidIDEntity - { - /// - /// Specified File Type ... - /// - /// - public XFileType Type { get; set; } - - /// - /// User Identifier ... - /// - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// File Name on Server ... - /// - /// - [Required] - [StringLength(255)] - public string Name { get; set; } - - /// - /// File Path On Server ... - /// - /// - [Required] - public string Path { get; set; } - - /// - /// Thumbnail FIle Name ... - /// if File Type Supported Thumbnail ... - /// - /// - public string Thumb { get; set; } - - /// - /// Thumbnail File Path ... - /// if File Type Supported Thumbnail ... - /// - /// - public string ThumbPath { get; set; } - - /// - /// File Uploading Time ... - /// - /// - public DateTime UploadedOn { get; set; } - - /// - /// Request For Upload File Name on Client ... - /// - /// - public string FileName { get; set; } - - /// - /// Comma Separated List Which Provides Pointer to Specified - /// Model for Describe ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\XFileEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xFileService.Configurations.Entities; - -namespace xFileService.Providers -{ - public class XFileEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XFileEntityRegisterar() - : base(nameof(XFileEntityRegisterar)) - { - // - // Add XFile Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XFileEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\XFileProvider.cs - -using System; -using System.IO; -using System.Linq; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using xTagService.Providers; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xFileService.Constants; -using xFileService.Extensions; -using xFileService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using xFileService.Models.Dtos; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xStorageService.Interfaces; -using xFileService.Providers.Dtos; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; -using Microsoft.AspNetCore.StaticFiles; -using Microsoft.Extensions.FileProviders; - -namespace xFileService.Providers -{ - public class XFileProvider : XBaseProvidedHasTag, IXFileProvider - { - private readonly IXFileServiceProvider provider; - private readonly IXStorageProvider storageProvider; - - public XFileProvider( - IXFileTagProvider tagProvider, - IXFileServiceProvider provider, - IXStorageProvider storageProvider - ) : base( - provider: provider, - tagProvider: tagProvider, - permittedRoles: [XFileServiceConstants.XAdminRole] - ) - { - this.provider = provider; - this.storageProvider = storageProvider; - } - - public override bool IsOwned( - XFile item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - !item.OwnerId.IsNullOrEmpty() && - userInfo.UserId == item.OwnerId; - - // - return result; - } - - public override bool IsOwned( - XFileDto item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - !item.OwnerId.IsNullOrEmpty() && - userInfo.UserId == item.OwnerId; - - // - return result; - } - - // - #region Tools ... - /// - /// Stream Specified File ... - /// - /// - /// - /// - public virtual async Task Stream( - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !id.IsNull() && - !id.IsDefaultGuid(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Generate Stream Info and Validate it ... - var stream = await GetFileDescriptor( - id: id, - cancellationToken: cancellationToken - ); - if (stream.IsNull()) - { - XException.NotFound.Throw(); - } - - // - // Generate Result Model ... - var result = new FileStreamResult( - stream.Stream, - stream.MIMEType - ) - { - FileDownloadName = stream.Name - }; - - // - return result; - } - - /// - /// Stream Specified File ... - /// - /// - /// - /// - public virtual async Task Stream( - string name, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !name.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Generate Stream Info and Validate it ... - var stream = await GetFileDescriptor( - fileName: name, - cancellationToken: cancellationToken - ); - if (stream.IsNull()) - { - XException.NotFound.Throw(); - } - - // - // Generate Result Model ... - var result = new FileStreamResult( - stream.Stream, - stream.MIMEType - ) - { - FileDownloadName = stream.Name - }; - - // - return result; - } - - /// - /// Download Specified File ... - /// - /// - /// - /// - public virtual async Task Download( - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !id.IsNull() && - !id.IsDefaultGuid(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Generate Stream Info and Validate it ... - var stream = await GetFileDescriptor( - id: id, - cancellationToken: cancellationToken - ); - if (stream.IsNull()) - { - XException.NotFound.Throw(); - } - - // - // Generate Result Model ... - var result = new PhysicalFileResult( - stream.Path, - stream.MIMEType - ) - { - FileDownloadName = stream.Name - }; - - // - return result; - } - - /// - /// Download Specified File ... - /// - /// - /// - /// - public virtual async Task Download( - string name, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !name.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Generate Stream Info and Validate it ... - var stream = await GetFileDescriptor( - fileName: name, - cancellationToken: cancellationToken - ); - if (stream.IsNull()) - { - XException.NotFound.Throw(); - } - - // - // Generate Result Model ... - var result = new PhysicalFileResult( - stream.Path, - stream.MIMEType - ) - { - FileDownloadName = stream.Name - }; - - // - return result; - } - - /// - /// Upload Files ... - /// - /// - /// - /// - /// - /// - public virtual async Task> Upload( - IFormFileCollection files, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !files.IsNull() && - files.HasChild() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Save Files On Server Side Physically ... - // and Validate it ... - var uploadResults = await storageProvider - .HandleFilesSave(files); - isValid = uploadResults.HasChild(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Prepare Result ... - var result = new List(); - foreach (var ur in uploadResults) - { - // - var fileType = storageProvider.GetFileType(ur.FileName); - - // - // Create Item Model ... - var item = new XFileDto - { - Type = fileType, - FileName = ur.Name, - Name = ur.FileName, - Path = ur.FilePath, - Thumb = ur.Thmbnail, - OwnerId = userInfo.UserId, - ThumbPath = ur.ThmbnailPath, - UploadedOn = DateTime.UtcNow, - }; - - // - try - { - // - // Add Entity Model to DB ... - item = await Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - result.Add(item); - } - catch { } - } - - // - return result; - } - - /// - /// Upload File ... - /// - /// - /// - /// - /// - /// - public virtual async Task Upload( - IFormFile file, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !file.IsNull() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Save Files On Server Side Physically ... - // and Validate it ... - var uploadResult = await storageProvider - .HandleFileSave(file, cancellationToken); - isValid = !uploadResult.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Prepare Result ... - // - var fileType = storageProvider.GetFileType(uploadResult.FileName); - - // - // Create Item Model ... - var item = new XFileDto - { - Type = fileType, - OwnerId = userInfo.UserId, - FileName = uploadResult.Name, - Name = uploadResult.FileName, - Path = uploadResult.FilePath, - Thumb = uploadResult.Thmbnail, - UploadedOn = DateTime.UtcNow, - ThumbPath = uploadResult.ThmbnailPath, - }; - - // - // Add Entity Model to DB ... - var result = await Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Specified Files ... - /// - /// - /// - /// - /// - /// - public virtual async Task> Remove( - string ids, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - var isValid = !ids.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Parse ID(s) List ... - var idsList = ids.ParseListGuid(); - isValid = !idsList.IsNull() && - idsList.HasChild(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - // Loop Through Parsed Ids and Try to Remove ... - var result = new List(); - foreach (var id in idsList) - { - // - // Retrieve XFileDto and Validate it ... - var model = await Get(id); - isValid = !model.IsNull() && !model.Id.IsNull() && !model.Id.IsDefaultGuid(); - if (!isValid) - { - continue; - } - - // - // Check Physical File Exists or not ... - var fileFullPath = storageProvider.GetFileFullPath(model.Name); - var thumbFullPath = model.Thumb.IsNullOrEmpty() - ? "" - : storageProvider.GetThumbnailFileFullPath(model.Thumb); - var isFileExists = storageProvider.IsFileExists(fileFullPath); - var isThumbExists = model.Thumb.IsNullOrEmpty() - ? false - : storageProvider.IsFileExists(thumbFullPath); - - // - // Remove Physical Thumbnail File ... - if (isThumbExists) - { - // - try - { - // - // Removed Stored Thumbnail ... - storageProvider.DeleteFile( - fileFullPath: thumbFullPath, - forceFileExists: false - ); - } - catch { } - } - - // - // Remove Pgysical File ... - if (isFileExists) - { - // - try - { - // - // Remove Stored File ... - storageProvider.DeleteFile( - fileFullPath: fileFullPath, - forceFileExists: false - ); - - // - // Remove Tags ... - await DetachTags( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - // - // Remove File Entty ... - var item = await provider.RemoveAsync( - id: model.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result.Add(model.Id); - } - - // - return result; - } - - /// - /// Retrieve Specified File Streaming Info ... - /// - /// - /// - /// - public virtual async Task GetFileDescriptor( - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Check File Model Exists or not ... - var isExists = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Retrieve Item and Validate it ... - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - if (item.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Generate Physical File Path and Validate it ... - var fileFullPath = storageProvider.GetFileFullPath(item.Name); - isExists = storageProvider.IsFileExists(fileFullPath); - var filePath = storageProvider.FilePathResolver(fileFullPath); - filePath = Path.Combine("wwwroot", filePath); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Generate Physical File Info ... - IFileInfo fileInfo = storageProvider.FileProvider.GetFileInfo(filePath); - - // - // Prepare Default Streaming Requirements ... - var mimeType = "application/octetstream"; - var readStream = fileInfo.CreateReadStream(); - var fileMimeProvider = new FileExtensionContentTypeProvider(); - var fileName = item.Name; - - // - // Try to Find Physical File's Content Type ... - fileMimeProvider.TryGetContentType( - filePath, - out mimeType - ); - - // - // Prepare Result Model ... - var result = new XFileStreamDescriptorDto - { - Stream = readStream, - MIMEType = mimeType, - Name = fileName, - Path = fileFullPath - }; - - // - return result; - } - - /// - /// Retrieve Specified File Streaming Info ... - /// - /// - /// - /// - public virtual async Task GetFileDescriptor( - string fileName, - CancellationToken cancellationToken = default - ) - { - // - if (fileName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - var item = await FindOne( - includeBuilder: null, - predicate: e => - e.Name.Contains(fileName) || - e.Path.Contains(fileName) || - e.Thumb.Contains(fileName) || - e.FileName.Contains(fileName) || - e.ThumbPath.Contains(fileName), - cancellationToken: cancellationToken - ); - var isExists = !item.IsNullOrDefault(); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Extract File Name ... - fileName = Path.GetFileName(fileName); - - // - // Check File is Thumbnail or File ... - var isThumb = fileName.StartsWith(storageProvider.Configuration.ThumbPrefix); - var isFile = fileName.StartsWith(storageProvider.Configuration.FilePrefix); - - // - // Check File Type is Valid ... - isExists = isThumb || isFile; - if (!isExists) - { - XException.UnsupportedFileType.Throw(); - } - - // - // Extract File Full Path ... - var fileFullPath = ""; - if (isThumb) - { - fileFullPath = storageProvider.GetThumbnailFileFullPath(fileName); - } - else - { - fileFullPath = storageProvider.GetFileFullPath(fileName); - } - - // - // Check Physical File Exists or Not ... - isExists = storageProvider.IsFileExists(fileFullPath); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Generate Physical File Info ... - var filePath = storageProvider.FilePathResolver(fileFullPath); - filePath = Path.Combine("wwwroot", filePath); - IFileInfo fileInfo = storageProvider.FileProvider.GetFileInfo(filePath); - - // - // Prepare Default Streaming Requirements ... - var mimeType = "application/octetstream"; - var readStream = fileInfo.CreateReadStream(); - var fileMimeProvider = new FileExtensionContentTypeProvider(); - - // - // Try to Find Physical File's Content Type ... - fileMimeProvider.TryGetContentType(filePath, out mimeType); - - // - // Prepare Result Model ... - var result = new XFileStreamDescriptorDto - { - Stream = readStream, - MIMEType = mimeType, - Name = fileName, - Path = fileFullPath - }; - - // - return result; - } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Reference Identifier for Specified Provider and Specified Item ... - /// - /// - /// - /// - public string GetIdentifier( - string providedFor, - TReferenceKey forProvidedId - ) - { - // - var result = $"{providedFor}_{forProvidedId}"; - - // - return result; - } - - /// - /// Check Specified Item has Refernce to Provider ... - /// - /// - /// - /// - /// - /// - public async Task IsProvidedFor( - string providedFor, - TReferenceKey forProvidedId, - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !id.IsDefaultGuid() && - !forProvidedId.IsNull() && - !providedFor.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Exists ... - isValid = await IsExists( - id: id, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - var references = item.GetReferences(); - var result = - references.IsNull() && - references.HasChild() && - references.Any(r => - r.ProvidedFor == providedFor && - r.ReferencedTo == $"{forProvidedId}" - ); - - // - return result; - } - - /// - /// Add Specified Reference to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task AddReference( - string providedFor, - TReferenceKey forProvidedId, - Guid id, - int forIndex = 0, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedFor.IsNullOrEmpty() && - !id.IsNull() && - !id.IsDefaultGuid() && - !providedFor.IsNull() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Has Reference or not ... - isValid = await IsProvidedFor( - id: id, - providedFor: providedFor, - forProvidedId: forProvidedId, - cancellationToken: cancellationToken - ); - if (isValid) - { - // - // Prevent Moving Forward Since Reference Exists ... - return; - } - - // - // Check Permissions ... - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var reference = new XReference - { - Index = forIndex, - ProvidedFor = providedFor, - ReferencedTo = $"{forProvidedId}" - }; - var references = item.GetReferences(); - references.Add(reference); - item = item.UpdateReferences(references); - item = await Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Remove Specified Reference from Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - string providedFor, - TReferenceKey forProvidedId, - Guid id, - int forIndex = 0, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !id.IsDefaultGuid() && - !forProvidedId.IsNull() && - !userInfo.IsNullOrDefault() && - !providedFor.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Has Reference or not ... - isValid = await IsProvidedFor( - id: id, - providedFor: providedFor, - forProvidedId: forProvidedId, - cancellationToken: cancellationToken - ); - if (!isValid) - { - // - // Prevent Moving Forward Since Reference not Exists ... - return; - } - - // - // Check Permissions ... - var item = await Get( - id: id, - includeBuilder: null, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - var identifier = GetIdentifier( - providedFor: providedFor, - forProvidedId: forProvidedId - ); - var references = item.GetReferences(); - references = references - .Where(r => - r.Index != forIndex && - r.ProvidedFor != providedFor && - r.ReferencedTo != $"{forProvidedId}" - ) - .ToList(); - item = item.UpdateReferences(references); - - // - item = await Update( - item: item, - id: item.Id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Get Specified References ... - /// - /// - /// - /// - /// - public async Task>> GetReferences( - string providedFor, - Guid id, - CancellationToken cancellationToken = default - ) - { - // - IList> result = new List>(); - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - var isValid = !item.IsNullOrDefault(); - if (!isValid) - { - return result; - } - - // - result = item.GetReferences(); - - // - result = result.Where(r => - r.ProvidedFor == providedFor - ) - .ToList(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\XFileTagProvided.cs - -using System; -using xCommons.Extensions; -using xTagService.Providers; -using xIdentityModels.Models; -using xFileService.Constants; -using xFileService.Interfaces; -using xFileService.Models.Dtos; -using xFileService.Providers.Dtos; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Providers -{ - public class XFileTagProvided : XBaseTagProvided, IXFileTagProvided - { - public XFileTagProvided( - IXFileTagProvider tagProvider, - IXFileServiceProvider provider - ) : base( - provider: provider, - tagProvider: tagProvider, - permittedRoles: [XFileServiceConstants.XAdminRole] - ) - { } - - public override bool IsOwned( - XFileDto item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - item.OwnerId == userInfo.UserId; - - // - return result; - } - - public override bool IsOwned( - XFile item, - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !item.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - item.OwnerId == userInfo.UserId; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\XFileTagProvider.cs - -using System; -using xTagService.Providers; -using xFileService.Constants; -using xFileService.Interfaces; -using xTagService.Interfaces.Dtos; - -namespace xFileService.Providers -{ - public class XFileTagProvider : XBaseTagProvider, IXFileTagProvider - { - public XFileTagProvider( - IXTagServiceProvider tagProvider - ) : base( - tagProvider: tagProvider, - providedFor: XFileServiceConstants.XFileTagProvided - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Dtos\XFileDtoHub.cs - -using System; -using xPushService.Base; -using xFileService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Providers.Dtos -{ - public class XFileDtoHub : XBaseDtoHub, IXFileDtoHub - { - public XFileDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Dtos\XFileRepositoryService.cs - -using System; -using AutoMapper; -using xDataService.Providers; -using xFileService.Models.Dtos; -using System.Collections.Generic; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Dtos -{ - public class XFileRepositoryService : XBaseRepositoryService, IXFileRepositoryService - { - public XFileRepositoryService( - IXFileRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Dtos\XFileServiceProvider.cs - -using System; -using xPushService.Base; -using xFileService.Models.Dtos; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xFileService.Interfaces.Dtos; -using xFileService.Models.Entities; - -namespace xFileService.Providers.Dtos -{ - public class XFileServiceProvider : XBaseDtoProvider, IXFileServiceProvider - { - public XFileServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXFileRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileEFRepository : XBaseEFRepository, IXFileRepository - where TContext : XDbContext - { - public XFileEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXFileKeyGenerator keyGenerator = null, - IXFileRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileEntityHub.cs - -using System; -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileEntityHub : XBaseEntityHub, IXFileEntityHub - { - public XFileEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileInMemoryRepository : XBaseInMemoryRepository, IXFileRepository - { - public XFileInMemoryRepository( - XDataServiceConfiguration configuration, - IXFileKeyGenerator keyGenerator = null, - IXFileRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileKeyGenerator.cs - -using xDataService.Providers; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileKeyGenerator : XGuidKeyGenerator, IXFileKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileMongoRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileMongoRepository : XBaseMongoRepository, IXFileRepository - { - public XFileMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXFileKeyGenerator keyGenerator = null, - IXFileRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileRepositoryEvents.cs - -using xDataService.Providers; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileRepositoryEvents : XBaseRepositoryEvents, IXFileRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileRepositoryProvider.cs - -using System; -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public class XFileRepositoryProvider : XBaseEntityProvider, IXFileRepositoryProvider - { - public XFileRepositoryProvider( - IHubContext hub, - IXFileRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\Entities\XFileSeederBase.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.Entities -{ - public abstract class XFileSeederBase : XBaseDbSeeder, IXFileSeeder - { - protected XFileSeederBase( - string entity, - string database, - IXFileRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\GraphQL\XFileGraphQLTypeHelper.cs - -using System; -using xDataService.GraphQL; -using xFileService.Constants; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.GraphQL -{ - public class XFileGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXFileGraphQLTypeHelper - { - public XFileGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XFileServiceConstants.XFileCollectionName; - } - - public override string GetInQuerySingleName() - { - return XFileServiceConstants.XFileSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\GraphQL\XFileGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xFileService.Models.Entities; -using xFileService.Interfaces.Entities; - -namespace xFileService.Providers.GraphQL -{ - public class XFileGraphQuery : XBaseGraphQLQuery - { - public XFileGraphQuery( - XDataServiceConfiguration configuration, - IXFileRepository repository, - IXFileGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\GraphQL\XFileGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xFileService.Providers.GraphQL -{ - public class XFileGraphSchema : Schema - { - public XFileGraphSchema(IServiceProvider services) : base(services) - { - Query = (XFileGraphQuery)services.GetService(typeof(XFileGraphQuery)); - } - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFileService\Providers\GraphQL\XFileGraphType.cs - -using System; -using xDataService.GraphQL; -using xFileService.Models.Entities; - -namespace xFileService.Providers.GraphQL -{ - public class XFileGraphType : XBaseGraphObjectType - { - public XFileGraphType() : base() - { - Field(x => x.Type); - Field(x => x.Name); - Field(x => x.Path); - Field(x => x.Thumb); - Field(x => x.OwnerId); - Field(x => x.FileName); - Field(x => x.ThumbPath); - Field(x => x.UploadedOn); - Field(x => x.References); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261109_153906.txt b/Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261112_120934.txt similarity index 97% rename from Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261109_153906.txt rename to Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261112_120934.txt index fd8730e..6608381 100644 --- a/Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261109_153906.txt +++ b/Documents/GeneratedContext/xDashboard-xFrameworkComponentsHolder-20261112_120934.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\public-api.ts /* * Public API Surface of x-framework-components @@ -227,7 +227,7 @@ export * from './lib/x-framework-components.module'; export * from './lib/modules/x-base-component.module'; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\test.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\test.ts // This file is required by karma.conf.js and loads recursively all the .spec and framework files @@ -256,7 +256,7 @@ const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-framework-components.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-framework-components.module.ts import { NgModule } from '@angular/core'; import { IonicModule } from '@ionic/angular'; @@ -431,7 +431,7 @@ import { XDescriptionListModule } from './x-description-list/x-description-list. }) export class XFrameworkComponentsModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-base-dialog.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-base-dialog.container.ts import { XResourceIdentifier, XStandardType } from 'x-framework-core'; @@ -439,7 +439,7 @@ export interface XBaseDialogConfig { title?: XStandardType; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-base.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-base.container.ts import { Observable } from 'rxjs'; import { Component } from '@angular/core'; @@ -494,7 +494,7 @@ export abstract class XBaseComponentContainerComponent extends XBaseComponent { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-card-empty.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-card-empty.container.ts import { Input, @@ -1606,7 +1606,7 @@ export class XCardEmptyActionSearchBarContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-file.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-file.container.ts import { Input, @@ -2986,7 +2986,7 @@ export class XCardFileFileDropContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-next-prev-reset.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-next-prev-reset.container.ts import { Input, @@ -4246,7 +4246,7 @@ export class XNextPrevResetAndHostContainerComponent //#endregion //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-toolbar-footer.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\i-x-toolbar-footer.ts import { Input, @@ -4727,14 +4727,14 @@ export abstract class XToolbarFooterContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-action.model.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-action.model.ts export interface XBaseActionModel { action: T; payload?: any; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-component.ts import { Input, @@ -6375,7 +6375,7 @@ export abstract class XBaseComponent //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-dialog.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-dialog.service.ts import { XBaseService, @@ -6550,7 +6550,7 @@ export abstract class XBaseDialogService< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base-page.ts import { NgZone, @@ -6930,7 +6930,7 @@ export abstract class XBasePage //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.html
    @@ -7018,7 +7018,7 @@ export abstract class XBasePage {{ item.data | json }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.scss ::ng-deep.fullscreen-dialog { // @@ -7100,7 +7100,7 @@ h6 { margin: 0 !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.dialog.component.ts import { Inject, @@ -7608,7 +7608,7 @@ export abstract class XBaseDialogComponent< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.observable.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-base.observable.tools.ts import { toArray, @@ -8099,14 +8099,14 @@ export abstract class XBaseObservableTools implements IXBaseObservableTools { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-size.model..ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\classes\x-size.model..ts export interface XSizeModel { width?: number; height?: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\component-templates.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\component-templates.module.ts import { XCardTestComponent, @@ -8407,7 +8407,7 @@ import { XExpandablePandelTestComponent } from './x-expandable-panel.component.t }) export class XComponentTemplatesModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-action-bar.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-action-bar.component.templates.ts import { Component } from '@angular/core'; import { @@ -8450,7 +8450,7 @@ export class XActionBarTestComponent extends XActionBarContainerComponent {} }) export class XComponentActionBarTestComponent extends XComponentActionBarContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-avatar-upload.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-avatar-upload.component.templates.ts import { Component } from '@angular/core'; import { XAvatarUploadContainerComponent } from '../x-avatar-upload/x-avatar-upload.typings'; @@ -8522,7 +8522,7 @@ import { XAvatarUploadContainerComponent } from '../x-avatar-upload/x-avatar-upl }) export class XAvatarUploadTestComponent extends XAvatarUploadContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-button.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-button.component.templates.ts import { Component } from '@angular/core'; import { XButtonContainerComponent } from '../x-button/x-button.typings'; @@ -8548,7 +8548,7 @@ import { XButtonContainerComponent } from '../x-button/x-button.typings'; }) export class XButtonTestComponent extends XButtonContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-card.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-card.component.templates.ts import { Component } from '@angular/core'; import { @@ -8640,7 +8640,7 @@ export class XCardTestComponent extends XCardContainerComponent {} }) export class XComponentCardTestComponent extends XComponentCardContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-chart.component.template.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-chart.component.template.ts import { Component } from '@angular/core'; import { XChartContainerComponent } from '../x-chart/x-chart.typings'; @@ -8674,7 +8674,7 @@ import { XChartContainerComponent } from '../x-chart/x-chart.typings'; }) export class XChartTestComponent extends XChartContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-color-picker.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-color-picker.component.templates.ts import { Component } from '@angular/core'; import { XColorPickerContainerComponent } from '../x-color-picker/x-color-picker.typings'; @@ -8724,7 +8724,7 @@ import { XColorPickerContainerComponent } from '../x-color-picker/x-color-picker }) export class XColorPickerTestComponent extends XColorPickerContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-color.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-color.component.templates.ts import { Component } from "@angular/core"; import { XColorContainerComponent } from "../x-color/x-color.typings"; @@ -8749,7 +8749,7 @@ import { XColorContainerComponent } from "../x-color/x-color.typings"; }) export class XColorTestComponent extends XColorContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-counter.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-counter.component.templates.ts import { Component } from "@angular/core"; @@ -8784,7 +8784,7 @@ import { XCounterContainerComponent } from "../x-counter/x-counter.typings"; }) export class XCounterTestComponent extends XCounterContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-data-pager.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-data-pager.component.templates.ts import { Component } from '@angular/core'; import { XDataPagerContainerComponent } from '../x-data-pager/x-data-pager.typings'; @@ -8838,7 +8838,7 @@ import { XDataPagerContainerComponent } from '../x-data-pager/x-data-pager.typin }) export class XDataPagerTestComponent extends XDataPagerContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-data-scroller.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-data-scroller.component.templates.ts import { Component } from '@angular/core'; import { XDataScrollerContainerComponent } from '../x-data-scroller/x-data-scroller.typings'; @@ -8885,7 +8885,7 @@ import { XDataScrollerContainerComponent } from '../x-data-scroller/x-data-scrol }) export class XDataScrollerTestComponent extends XDataScrollerContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-description-list.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-description-list.component.templates.ts import { Component } from '@angular/core'; import { XDescriptionListContainerComponent } from '../x-description-list/x-description-list.typings'; @@ -8943,7 +8943,7 @@ export class XDescriptionListTestComponent extends XDescriptionListContainerComp }) export class XDescriptionListItemTestComponent extends XDescriptionListItemContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-empty.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-empty.component.templates.ts import { Component } from '@angular/core'; import { @@ -9001,7 +9001,7 @@ export class XEmptyTestComponent extends XEmptyContainerComponent {} }) export class XComponentEmptyTestComponent extends XComponentEmptyContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-expandable-list.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-expandable-list.component.templates.ts import { Component } from '@angular/core'; import { XExpandableListContainerComponent } from '../x-expandable-list/x-expandable-list.typings'; @@ -9045,7 +9045,7 @@ import { XExpandableListContainerComponent } from '../x-expandable-list/x-expand }) export class XExpandableListTestComponent extends XExpandableListContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-expandable-panel.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-expandable-panel.component.templates.ts import { Component } from '@angular/core'; import { XExpandablePandelContainerComponent } from '../x-expandable-panel/x-expandable-panel.typings'; @@ -9088,7 +9088,7 @@ import { XExpandablePandelContainerComponent } from '../x-expandable-panel/x-exp }) export class XExpandablePandelTestComponent extends XExpandablePandelContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-fab.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-fab.component.templates.ts import { Component } from '@angular/core'; import { XFabContainerComponent } from '../x-fab/x-fab.typings'; @@ -9108,7 +9108,7 @@ import { XFabContainerComponent } from '../x-fab/x-fab.typings'; }) export class XFabTestComponent extends XFabContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-file-drop-area.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-file-drop-area.component.templates.ts import { Component } from '@angular/core'; import { XFileDropAreaContainerComponent } from '../x-file-drop-area/x-file-drop-area.typings'; @@ -9148,7 +9148,7 @@ import { XFileDropAreaContainerComponent } from '../x-file-drop-area/x-file-drop }) export class XFileDropAreaTestComponent extends XFileDropAreaContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-file-upload.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-file-upload.component.templates.ts import { Component } from '@angular/core'; import { XFileUploadContainerComponent } from '../x-file-upload/x-file-upload.typings'; @@ -9263,7 +9263,7 @@ import { XFileUploadContainerComponent } from '../x-file-upload/x-file-upload.ty }) export class XFileUploadTestComponent extends XFileUploadContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-footer.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-footer.component.templates.ts import { Component } from '@angular/core'; import { XFooterContainerComponent } from '../x-page/x-footer/x-footer.typings'; @@ -9283,7 +9283,7 @@ import { XFooterContainerComponent } from '../x-page/x-footer/x-footer.typings'; }) export class XFooterTestComponent extends XFooterContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-form.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-form.component.templates.ts import { Component } from '@angular/core'; import { XFormContainerComponent } from '../x-form/x-form.typings'; @@ -9328,7 +9328,7 @@ import { XFormContainerComponent } from '../x-form/x-form.typings'; }) export class XFormTestComponent extends XFormContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-grid.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-grid.component.templates.ts import { Component } from '@angular/core'; import { XGridContainerComponent } from '../x-grid/x-grid.typings'; @@ -9379,7 +9379,7 @@ import { XGridContainerComponent } from '../x-grid/x-grid.typings'; }) export class XGridTestComponent extends XGridContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-icon.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-icon.component.templates.ts import { Component } from '@angular/core'; import { XIconContainerComponent } from '../x-icon/x-icon.typings'; @@ -9405,7 +9405,7 @@ import { XIconContainerComponent } from '../x-icon/x-icon.typings'; }) export class XIconTestComponent extends XIconContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-ide.component.template.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-ide.component.template.ts import { Component } from '@angular/core'; import { XIDEContainerComponent } from '../x-ide/x-ide.typings'; @@ -9461,7 +9461,7 @@ import { XIDEContainerComponent } from '../x-ide/x-ide.typings'; }) export class XIdeTestComponent extends XIDEContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-image-cropper.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-image-cropper.component.templates.ts import { Component } from '@angular/core'; import { XImageCropperContainerComponent } from '../x-image-cropper/x-image-cropper.typings'; @@ -9502,7 +9502,7 @@ import { XImageCropperContainerComponent } from '../x-image-cropper/x-image-crop }) export class XImageCropperTestComponent extends XImageCropperContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-list.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-list.component.templates.ts import { Component } from '@angular/core'; import { @@ -9702,7 +9702,7 @@ export class XListTestComponent extends XListContainerComponent {} }) export class XComponentListTestComponent extends XComponentListContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-map.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-map.component.templates.ts import { Component } from '@angular/core'; import { XMapContainerComponent } from '../x-map/x-map.typings'; @@ -9780,7 +9780,7 @@ import { XMapContainerComponent } from '../x-map/x-map.typings'; }) export class XMapTestComponent extends XMapContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-markdown.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-markdown.component.templates.ts import { Component } from '@angular/core'; import { XMarkdownContainerComponent } from '../x-markdown/x-markdown.typings'; @@ -9816,7 +9816,7 @@ import { XMarkdownContainerComponent } from '../x-markdown/x-markdown.typings'; }) export class XMarkdownTestComponent extends XMarkdownContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-model-presenter.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-model-presenter.component.templates.ts import { Component } from '@angular/core'; import { XModelPresenterContainerComponent } from '../x-model-presenter/x-model-presenter.typings'; @@ -9864,7 +9864,7 @@ import { XModelPresenterContainerComponent } from '../x-model-presenter/x-model- }) export class XModelPresenterTestComponent extends XModelPresenterContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-navigator.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-navigator.component.templates.ts import { Component } from '@angular/core'; import { XNavigatorContainerComponent } from '../x-page/x-navigator/x-navigator.typings'; @@ -9899,7 +9899,7 @@ import { XNavigatorContainerComponent } from '../x-page/x-navigator/x-navigator. }) export class XNavigatorTestComponent extends XNavigatorContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-page.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-page.component.templates.ts import { Component } from "@angular/core"; @@ -9985,7 +9985,7 @@ import { XPageContainerComponent } from "../x-page/x-page.container"; }) export class XPageTestComponent extends XPageContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-screen-capture.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-screen-capture.component.templates.ts import { Component } from '@angular/core'; import { XScreenCaptureContainerComponent } from '../x-screen-capture/x-screen-capture.container'; @@ -10006,7 +10006,7 @@ import { XScreenCaptureContainerComponent } from '../x-screen-capture/x-screen-c }) export class XScreenCaptureTestComponent extends XScreenCaptureContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-search-bar.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-search-bar.component.templates.ts import { Component } from '@angular/core'; import { @@ -10084,7 +10084,7 @@ export class XSearchBarTestComponent extends XSearchBarContainerComponent {} }) export class XComponentSearchBarTestComponent extends XComponentSearchBarContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-slider.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-slider.component.templates.ts import { Component } from '@angular/core'; import { XSliderContainerComponent } from '../x-slider/x-slider.typings'; @@ -10123,7 +10123,7 @@ export class XSliderTestComponent extends XSliderContainerComponent {} }) export class XSlideTestComponent extends XSlideContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-slotter.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-slotter.component.templates.ts import { Component } from '@angular/core'; import { XSlotterContainerComponent } from '../x-slotter/x-slotter.typings'; @@ -10163,7 +10163,7 @@ export class XSlotterTestComponent extends XSlotterContainerComponent {} }) export class XSlotTestComponent extends XSlotContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-spinner.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-spinner.component.templates.ts import { Component } from '@angular/core'; import { XSpinnerContainerComponent } from '../x-spinner/x-spinner.typings'; @@ -10185,7 +10185,7 @@ import { XSpinnerContainerComponent } from '../x-spinner/x-spinner.typings'; }) export class XSpinnerTestComponent extends XSpinnerContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-stepper.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-stepper.component.templates.ts import { Component } from '@angular/core'; import { XStepperContainerComponent } from '../x-stepper/x-stepper.typings'; @@ -10274,7 +10274,7 @@ export class XStepperTestComponent extends XStepperContainerComponent {} }) export class XStepTestComponent extends XStepContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-tab-navigator.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-tab-navigator.component.templates.ts import { Component } from '@angular/core'; import { XTabNavigatorContainerComponent } from '../x-tab-navigator/x-tab-navigator.typings'; @@ -10301,7 +10301,7 @@ import { XTabNavigatorContainerComponent } from '../x-tab-navigator/x-tab-naviga }) export class XTabNavigatorTestComponent extends XTabNavigatorContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-table.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-table.component.templates.ts import { Component } from '@angular/core'; import { XTableContainerComponent } from '../x-table/x-table.typings'; @@ -10376,7 +10376,7 @@ import { XTableContainerComponent } from '../x-table/x-table.typings'; }) export class XTableTestComponent extends XTableContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-tabs.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-tabs.component.templates.ts import { Component } from '@angular/core'; import { XTabsContainerComponent } from '../x-tabs/x-tabs.typings'; @@ -10423,7 +10423,7 @@ export class XTabsTestComponent extends XTabsContainerComponent {} }) export class XTabTestComponent extends XTabContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-theme-manager.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-theme-manager.component.templates.ts import { Component } from '@angular/core'; import { XThemeManagerContainerComponent } from '../x-theme/x-theme-manager/x-theme-manager.typings'; @@ -10552,7 +10552,7 @@ import { XThemeManagerContainerComponent } from '../x-theme/x-theme-manager/x-th }) export class XThemeManagerTestComponent extends XThemeManagerContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-thumbnail.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-thumbnail.component.templates.ts import { Component } from '@angular/core'; import { XThumbnailContainerComponent } from '../x-thumbnail/x-thumbnail.typings'; @@ -10576,7 +10576,7 @@ import { XThumbnailContainerComponent } from '../x-thumbnail/x-thumbnail.typings }) export class XThumbnailTestComponent extends XThumbnailContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-toolbar.component.templates.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\component-templates\x-toolbar.component.templates.ts import { Component } from '@angular/core'; import { XToolbarContainerComponent } from '../x-page/x-toolbar/x-toolbar.typings'; @@ -10617,7 +10617,7 @@ import { XToolbarContainerComponent } from '../x-page/x-toolbar/x-toolbar.typing }) export class XToolbarTestComponent extends XToolbarContainerComponent {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\config\x-framework-components.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\config\x-framework-components.config.ts import { XFrameworkCoreConfig } from 'x-framework-core'; import { XFrameworkServicesConfig } from 'x-framework-services'; @@ -10637,7 +10637,7 @@ export interface XFrameworkComponentsConfig extends XSharedConfig { defaultSearchDebounceTime: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -10674,7 +10674,7 @@ import { XSelectorDialogComponent } from './x-selector-dialog/x-selector-dialog. }) export class XDialogsModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.scss x-icon { --size: 24px; @@ -10800,7 +10800,7 @@ h6 { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.component.ts import { XDialogConfig, @@ -11041,7 +11041,7 @@ export abstract class XDialogComponent extends XBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-dialog\x-dialog.typings.ts import { XColorIdentifier, XColorWithBrightness } from 'x-framework-core'; @@ -11074,7 +11074,7 @@ export const defaultBaseDialogConfig: Partial = { progressBarColor: XColorWithBrightness.Warning, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.html @@ -11219,7 +11219,7 @@ export const defaultBaseDialogConfig: Partial = { }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.scss :host { --max-popover-height: 260px; @@ -11266,7 +11266,7 @@ h6 { overflow-y: scroll; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.component.ts import { Inject, @@ -11565,7 +11565,7 @@ export class XPopoverComponent extends XBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.service.ts import { toArray, @@ -11749,7 +11749,7 @@ export class XPopoverService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.tools.ts import { XListItem } from '../../x-list/x-list.typings'; import { @@ -11828,7 +11828,7 @@ export const defaultPopoverOption: XPopoverOption = { handler: () => {}, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-popover\x-popover.typings.ts import { XStandardType, @@ -11918,7 +11918,7 @@ export type XPopoverPresenterOptions = Partial< > >; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.html
    @@ -12079,7 +12079,7 @@ export type XPopoverPresenterOptions = Partial< {{ item.data | json }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.scss ::ng-deep.fullscreen-dialog { // @@ -12161,7 +12161,7 @@ h6 { margin: 0 !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.component.ts import { Inject, @@ -12596,7 +12596,7 @@ export class XSelectorDialogComponent extends XBaseDialogComponent< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.service.ts import { MatDialog, @@ -12645,7 +12645,7 @@ export class XSelectorDialogService extends XBaseDialogService< } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\dialogs\x-selector-dialog\x-selector-dialog.typings.ts import { XStandardType, @@ -12685,7 +12685,7 @@ export interface XSelectorDialogConfig taskName?: XStandardType; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\modules\x-base-component.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\modules\x-base-component.module.ts import { NgModule } from '@angular/core'; import { IonicModule } from '@ionic/angular'; @@ -12720,7 +12720,7 @@ import { XDirectivesModule as XFrameworkServicesDirectivesModule } from 'x-frame }) export class XBaseComponentModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\modules\x-material.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\modules\x-material.module.ts // import { NgModule } from '@angular/core'; @@ -12910,7 +12910,7 @@ import { CommonModule } from '@angular/common'; }) export class XMaterialModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\_tools.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\_tools.scss @import "./animate.scss"; @@ -13222,7 +13222,7 @@ $d-100p: 100%; //#endregion //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\animate.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\animate.scss @charset "UTF-8"; @@ -16848,7 +16848,7 @@ $d-100p: 100%; } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\base-theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\base-theme.scss // Import all the theming functionality. // We can use relative imports for imports from the cdk because we bundle everything @@ -21920,7 +21920,7 @@ $mat-form-field-dedupe: 0; @include mat-snack-bar-theme($theme); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\custom-effects.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\custom-effects.scss // button:hover:not([disabled]), @@ -21968,7 +21968,7 @@ ion-button:hover:not([disabled]) { flex: 0 auto !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\fab-theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\fab-theme.scss // //#region Fab ... @@ -22005,7 +22005,7 @@ x-fab[pageFab] { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\markdown-theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\markdown-theme.scss /** * MIT License @@ -22127,7 +22127,7 @@ x-fab[pageFab] { color: #d6e7ff; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\material-fonts.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\material-fonts.scss // //#region Material Fonts ... @@ -22470,7 +22470,7 @@ body { @extend .mat-typography; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\material-icons.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\material-icons.scss @font-face { font-family: 'Material Icons'; @@ -22508,7 +22508,7 @@ body { font-feature-settings: 'liga'; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\theme\theme.scss @import "./base-theme.scss"; @import "./material-icons.scss"; @@ -23400,7 +23400,7 @@ body { // Implement to ionic them ... @include x-to-ion-color(); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\tokens\x-injectable-tokens.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\tokens\x-injectable-tokens.ts import { InjectionToken } from '@angular/core'; import { XFrameworkComponentsConfig } from '../config/x-framework-components.config'; @@ -23409,7 +23409,7 @@ export const X_FRAMEWORK_COMPONENTS_CONFIG = new InjectionToken< XFrameworkComponentsConfig >('x_config'); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.scss $action-item-margin: var(--action-items-offset, 2px); $action-item-gutter: var(--action-items-gutter, 8px); @@ -23559,7 +23559,7 @@ $action-item-gutter: var(--action-items-gutter, 8px); } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.component.ts import { sort, @@ -24058,7 +24058,7 @@ export class XActionBarComponent extends XActionBarContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -24080,7 +24080,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XActionBarModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-action-bar\x-action-bar.typings.ts import { XColor, @@ -24627,7 +24627,7 @@ export abstract class XComponentActionBarContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.html @@ -24819,7 +24819,7 @@ export abstract class XComponentActionBarContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.scss // :host { @@ -24879,7 +24879,7 @@ x-file-drop-area { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.component.ts import { Component, @@ -25399,7 +25399,7 @@ export class XAvatarUploadComponent extends XAvatarUploadContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -25437,7 +25437,7 @@ import { XFileDropAreaModule } from '../x-file-drop-area/x-file-drop-area.module }) export class XAvatarUploadModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-avatar-upload\x-avatar-upload.typings.ts import { Input, @@ -25719,7 +25719,7 @@ export abstract class XAvatarUploadContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-button\x-button.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-button\x-button.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.component.scss // @import "../theme/theme.scss"; @@ -26536,7 +26536,7 @@ export abstract class XButtonContainerComponent visibility: hidden; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.component.ts import { XCardAction, @@ -27010,7 +27010,7 @@ export class XCardComponent extends XCardContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -27026,7 +27026,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XCardModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-card\x-card.typings.ts import { Input, @@ -27499,7 +27499,7 @@ export abstract class XComponentCardContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.html @@ -27565,7 +27565,7 @@ export abstract class XComponentCardContainerComponent
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.scss :host { display: block; @@ -27584,7 +27584,7 @@ export abstract class XComponentCardContainerComponent height: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.component.ts import { Component, @@ -30644,7 +30644,7 @@ export class XChartComponent extends XChartContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -30679,7 +30679,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XChartModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-chart\x-chart.typings.ts import { Input, @@ -34956,7 +34956,7 @@ export abstract class XChartContainerComponent //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.scss :host { --size: 32px; @@ -35028,7 +35028,7 @@ export abstract class XChartContainerComponent border-width: var(--border-width); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.component.ts import { nameof, @@ -35249,7 +35249,7 @@ export class XColorComponent extends XColorContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -35263,7 +35263,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XColorModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color\x-color.typings.ts import { Input, @@ -35493,7 +35493,7 @@ export abstract class XColorContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.html @@ -35782,7 +35782,7 @@ export abstract class XColorContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.scss :host { display: block; @@ -35982,7 +35982,7 @@ export abstract class XColorContainerComponent border: #a9a9a9 solid 1px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.component.ts import { Component, @@ -36642,7 +36642,7 @@ export class XColorPickerComponent extends XColorPickerContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -36683,7 +36683,7 @@ import { XColorPickerDialogComponent } from './x-color-picker-dialog/x-color-pic }) export class XColorPickerModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker.typings.ts import { Input, @@ -37207,7 +37207,7 @@ export abstract class XColorPickerContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\directives\x-color-text.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\directives\x-color-text.directive.ts import { Input, @@ -37250,7 +37250,7 @@ export class XColorTextDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.html @@ -37347,7 +37347,7 @@ export class XColorTextDirective { > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.scss ::ng-deep.fullscreen-dialog { // @@ -37405,7 +37405,7 @@ h6 { margin: 0 !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.component.ts import { Inject, @@ -37895,7 +37895,7 @@ export class XColorPickerDialogComponent extends XBasePage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.service.ts import { XResourceIDs, @@ -38050,7 +38050,7 @@ export class XColorPickerDialogService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-color-picker\x-color-picker-dialog\x-color-picker-dialog.typings.ts import { XDialogResult } from 'x-framework-core'; import { IXColorPickerContainer } from '../x-color-picker.typings'; @@ -38065,7 +38065,7 @@ export interface XColorPickerDialogConfig extends XBaseDialogConfig, Partial {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.html @@ -38115,13 +38115,13 @@ export interface XColorPickerDialogConfig -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.scss .display-message-container { margin: 2px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.component.ts import { XCounterTick, @@ -38523,7 +38523,7 @@ export class XCounterComponent extends XCounterContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -38538,7 +38538,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XCounterModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-counter\x-counter.typings.ts import { Input, @@ -38820,7 +38820,7 @@ export abstract class XCounterContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.html @@ -39161,10 +39161,10 @@ export abstract class XCounterContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.component.ts import { nameof, @@ -39882,7 +39882,7 @@ export class XDataPagerComponent extends XDataPagerContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -39912,7 +39912,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XDataPagerModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-pager\x-data-pager.typings.ts import { Input, @@ -40229,7 +40229,7 @@ export abstract class XDataPagerContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.html @@ -40315,10 +40315,10 @@ export abstract class XDataPagerContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.component.ts import { XDataScrollerAction, @@ -40584,7 +40584,7 @@ export class XDataScrollerComponent extends XDataScrollerContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -40606,7 +40606,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XDataScrollerModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-data-scroller\x-data-scroller.typings.ts import { Input, @@ -40822,7 +40822,7 @@ export abstract class XDataScrollerContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.html @@ -41105,7 +41105,7 @@ export abstract class XDataScrollerContainerComponent {{ value }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.scss :host ::ng-deep .x-description-list { &.isLegacy { @@ -41218,7 +41218,7 @@ export abstract class XDataScrollerContainerComponent } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.component.ts import { Component, @@ -41874,7 +41874,7 @@ export class XDescriptionListComponent< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -41898,7 +41898,7 @@ import { XDescriptionListItemComponent } from './x-description-list-item/x-descr }) export class XDescriptionListModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list.typings.ts import { Input, @@ -42239,16 +42239,16 @@ export abstract class XDescriptionListContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.component.ts import { nameof } from 'x-framework-core'; import { @@ -42354,7 +42354,7 @@ export class XDescriptionListItemComponent extends XDescriptionListItemContainer //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-description-list\x-description-list-item\x-description-list-item.typings.ts import { Input, @@ -42506,7 +42506,7 @@ export abstract class XDescriptionListItemContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.scss :host { --padding: 6px; @@ -42552,7 +42552,7 @@ export abstract class XDescriptionListItemContainerComponent padding-bottom: 6px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.component.ts import { XEmptyAction, @@ -42660,7 +42660,7 @@ export class XEmptyComponent extends XEmptyContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -42676,7 +42676,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XEmptyModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-empty\x-empty.typings.ts import { Input, @@ -43179,7 +43179,7 @@ export abstract class XComponentEmptyContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.html @@ -43326,7 +43326,7 @@ export abstract class XComponentEmptyContainerComponent
    {{ getResourceValue(item.title) | async }}
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.scss :host ::ng-deep { // @@ -43496,7 +43496,7 @@ x-card { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.component.ts import { nameof, @@ -44400,7 +44400,7 @@ export class XExpandableListComponent extends XExpandableListContainerComponent //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -44421,7 +44421,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XExpandableListModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.tools.ts import { toArray, @@ -44728,7 +44728,7 @@ export async function parentItemsById( } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-list\x-expandable-list.typings.ts import { Input, @@ -45124,7 +45124,7 @@ export abstract class XExpandableListContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.html @@ -45337,7 +45337,7 @@ export abstract class XExpandableListContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.scss :host { --panel-header-size: 48px; @@ -45412,7 +45412,7 @@ export abstract class XExpandableListContainerComponent width: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.component.ts import { Component, @@ -46349,7 +46349,7 @@ export class XExpandablePanelComponent extends XExpandablePandelContainerCompone //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -46384,7 +46384,7 @@ import { XExpandablePanelComponent } from './x-expandable-panel.component'; }) export class XExpandablePanelModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-expandable-panel.typings.ts import { Input, @@ -46710,7 +46710,7 @@ export abstract class XExpandablePandelContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.html @@ -46732,10 +46732,10 @@ export abstract class XExpandablePandelContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.component.ts import { Component, @@ -46850,7 +46850,7 @@ export class XPanelComponent extends XPanelContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-expandable-panel\x-panel\x-panel.typings.ts import { Input, @@ -47071,7 +47071,7 @@ export abstract class XPanelContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.scss :host ::ng-deep .x-icon { background-color: transparent !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.component.ts import { XFabItem, @@ -47492,7 +47492,7 @@ export class XFabComponent extends XFabContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -47507,7 +47507,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XFabModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-fab\x-fab.typings.ts import { Input, @@ -47758,7 +47758,7 @@ export abstract class XFabContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.html @@ -47841,7 +47841,7 @@ export abstract class XFabContainerComponent
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.scss :host { width: inherit; @@ -47898,7 +47898,7 @@ export abstract class XFabContainerComponent font-size: 8px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.component.ts import { nameof, @@ -48055,7 +48055,7 @@ export class XFileDropAreaComponent extends XFileDropAreaContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -48084,7 +48084,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XFileDropAreaModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-drop-area\x-file-drop-area.typings.ts import { Input, @@ -48823,7 +48823,7 @@ export abstract class XComponentFileDropAreaContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.html @@ -48986,7 +48986,7 @@ export abstract class XComponentFileDropAreaContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.scss :host { --top-radius: 5px; @@ -49051,7 +49051,7 @@ export abstract class XComponentFileDropAreaContainerComponent border-top-right-radius: var(--top-radius); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.component.ts import { ViewChild, @@ -50103,7 +50103,7 @@ export class XFileUploadComponent extends XFileUploadContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -50135,7 +50135,7 @@ import { XFileDropAreaModule } from '../x-file-drop-area/x-file-drop-area.module }) export class XFileUploadModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-file-upload\x-file-upload.typings.ts import { Input, @@ -51416,7 +51416,7 @@ export abstract class XFileUploadContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.html @@ -54139,7 +54139,7 @@ export abstract class XFileUploadContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.scss // :host { @@ -55216,7 +55216,7 @@ export abstract class XFileUploadContainerComponent } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.component.ts import { FormGroup, @@ -62403,7 +62403,7 @@ export class XFormComponent extends XFormContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.module.ts import { LocaleFactory, @@ -62497,7 +62497,7 @@ import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapte }) export class XFormModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.tools.ts import { XIconNames } from '../x-icon/x-icon.typings'; import { XColorWithBrightness } from 'x-framework-core'; @@ -62517,7 +62517,7 @@ export const defaultFormControlSelectIcon: XControlIconDescriptor = { position: XControlIconPosition.Suffix, } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\x-form.typings.ts import { Input, @@ -63511,7 +63511,7 @@ export abstract class XFormContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\validators\x-form-validators.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-form\validators\x-form-validators.ts import { isValidURL, @@ -63680,7 +63680,7 @@ export class XFormValidators { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.html @@ -63747,7 +63747,7 @@ export class XFormValidators { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.scss :host { --x-frame-height: auto; @@ -63764,7 +63764,7 @@ export class XFormValidators { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.component.ts import { Component, @@ -64398,7 +64398,7 @@ export class XFrameComponent extends XFrameContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -64413,7 +64413,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XFrameModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-frame\x-frame.typings.ts import { Input, @@ -64692,7 +64692,7 @@ export abstract class XFrameContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.html @@ -64889,7 +64889,7 @@ export abstract class XFrameContainerComponent
    {{ item | json }}
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.scss ion-item-option > ion-item { --background: transparent !important; @@ -64991,7 +64991,7 @@ x-card { height: inherit; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.component.ts import { XGridItem, @@ -65285,7 +65285,7 @@ export class XGridComponent extends XGridContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -65308,7 +65308,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XGridModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-grid\x-grid.typings.ts import { Input, @@ -65572,7 +65572,7 @@ export abstract class XGridContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.scss :host { // @@ -65684,7 +65684,7 @@ ion-ripple-effect { cursor: pointer; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.component.ts import { XIconAction, @@ -65847,7 +65847,7 @@ export class XIconComponent extends XIconContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -65861,7 +65861,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XIconModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-icon\x-icon.typings.ts import { Input, @@ -67057,7 +67057,7 @@ export abstract class XIconContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.html @@ -67139,10 +67139,10 @@ export abstract class XIconContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.component.ts import { Component, @@ -69422,7 +69422,7 @@ export class XIDEComponent extends XIDEContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -69455,7 +69455,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XIDEModule { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-ide\x-ide.typings.ts import { Input, @@ -70357,7 +70357,7 @@ export class XIDEContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.scss :host::ng-deep .mat-dialog-container { padding: 0 !important; @@ -70662,7 +70662,7 @@ mat-icon { border-radius: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.component.ts import { NgZone, @@ -71732,7 +71732,7 @@ export class XImageCropperComponent extends XImageCropperContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -71750,7 +71750,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XImageCropperModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.service.ts import { toFileBlob, @@ -72013,7 +72013,7 @@ export class XImageCropperService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-image-cropper\x-image-cropper.typings.ts import { Input, @@ -72421,7 +72421,7 @@ export abstract class XImageCropperContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.html @@ -72840,7 +72840,7 @@ export abstract class XImageCropperContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.scss ion-item-option > ion-item { --background: transparent !important; @@ -72903,7 +72903,7 @@ x-card { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.component.ts import { nameof, @@ -73875,7 +73875,7 @@ export class XListComponent extends XListContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -73911,7 +73911,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XListModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-list\x-list.typings.ts import { Input, @@ -75400,7 +75400,7 @@ export abstract class XComponentListContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.html @@ -75707,7 +75707,7 @@ export abstract class XComponentListContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.scss :host { --map-height: 200px; @@ -76155,7 +76155,7 @@ $transform-hide: scaleY(0); } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.component.ts import { of, @@ -77684,7 +77684,7 @@ export class XMapComponent extends XMapContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -77723,7 +77723,7 @@ import { XMapDialogComponent } from './x-map-dialog/x-map-dialog.component'; }) export class XMapModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.tools.ts import { XMapLocation } from './x-map.typings'; import { isNullOrEmptyString, hasChild, isString, isArray, countChild } from 'x-framework-core'; @@ -77797,7 +77797,7 @@ export function toLongLat(point: XMapLocation) { return `${point.longitude},${point.latitude}`; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map.typings.ts import { Input, @@ -78605,7 +78605,7 @@ export class XMapContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.html
    @@ -78730,7 +78730,7 @@ export class XMapContainerComponent
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.scss :host { --x-map-height: 200px; @@ -78801,7 +78801,7 @@ h6 { margin: 0 !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.component.ts import { Inject, @@ -79530,7 +79530,7 @@ export class XMapDialogComponent extends XBasePage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.service.ts import { XColor, @@ -79724,7 +79724,7 @@ export class XMapDialogService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-map\x-map-dialog\x-map-dialog.typings.ts import { XDialogResult } from 'x-framework-core'; import { XMapLocation, IXMapContainer } from '../x-map.typings'; @@ -79796,7 +79796,7 @@ export enum XMapdialogCssVar { export type XMapdialogCssVarIdentifier = XMapdialogCssVar | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.html @@ -79956,7 +79956,7 @@ export type XMapdialogCssVarIdentifier = XMapdialogCssVar | string; > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.scss :host ::ng-deep a { pointer-events: none; @@ -80007,7 +80007,7 @@ textarea { min-height: unset; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.component.ts import { ViewChild, @@ -80457,7 +80457,7 @@ export class XMarkdownComponent extends XMarkdownContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.module.ts import { NgModule } from '@angular/core'; import { MarkdownModule } from 'ngx-markdown'; @@ -80489,7 +80489,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XMarkdownModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-markdown\x-markdown.typings.ts import { Input, @@ -80874,7 +80874,7 @@ export abstract class XMarkdownContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.html @@ -81111,7 +81111,7 @@ export abstract class XMarkdownContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.scss :host { // @@ -81242,7 +81242,7 @@ export abstract class XMarkdownContainerComponent } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.component.ts import { Component, @@ -82162,7 +82162,7 @@ export class XModelPresenterComponent< //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -82191,7 +82191,7 @@ import { XModelPresenterItemComponent } from './x-model-presenter-item/x-model-p }) export class XModelPresenterModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter.typings.ts import { Input, @@ -82624,16 +82624,16 @@ export abstract class XModelPresenterContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.component.ts import { Input, @@ -82787,7 +82787,7 @@ export class XModelPresenterItemComponent extends XBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-model-presenter\x-model-presenter-item\x-model-presenter-item.typings.ts import { XBaseActionModel } from '../../classes/x-base-action.model'; @@ -82799,7 +82799,7 @@ export type XModelPresenterItemActionIdentifier = XModelPresenterItemAction | st export interface XModelPresenterItemModel extends XBaseActionModel {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.scss :host { height: 100%; @@ -83045,7 +83045,7 @@ export interface XModelPresenterItemModel touch-action: pan-y; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.component.ts import { XMenuState, @@ -83636,7 +83636,7 @@ export class XPageComponent extends XPageContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.container.ts import { Input, @@ -84439,7 +84439,7 @@ export abstract class XPageContainerComponent //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -84489,7 +84489,7 @@ import { XExpandablePanelModule } from '../x-expandable-panel/x-expandable-panel }) export class XPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-page.typings.ts export enum XMenuState { @@ -84586,7 +84586,7 @@ export enum XPageCSSVars { export type XPageCSSVarsIdentifier = XPageCSSVars | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.scss :host { position: absolute; @@ -84609,7 +84609,7 @@ export type XPageCSSVarsIdentifier = XPageCSSVars | string; right: 0; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.component.ts import { XFooterAction, @@ -84713,7 +84713,7 @@ export class XFooterComponent extends XFooterContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-footer\x-footer.typings.ts import { Input, @@ -85029,7 +85029,7 @@ export abstract class XComponentFooterContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.scss .nav-item > * { display: inline-block; @@ -85148,7 +85148,7 @@ export abstract class XComponentFooterContainerComponent } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.component.ts import { XNavigatorAction, @@ -85336,7 +85336,7 @@ export class XNavigatorComponent extends XNavigatorContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.tools.ts import { XPage, @@ -85450,7 +85450,7 @@ export function toNavigatiorListItem(page: XPage) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-navigator\x-navigator.typings.ts import { Input, @@ -85798,7 +85798,7 @@ export abstract class XNavigatorContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.html @@ -85975,7 +85975,7 @@ export abstract class XNavigatorContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.scss .x-toolbar-slot, .x-toolbar-start-slot, @@ -86072,7 +86072,7 @@ ion-menu-button { max-width: 150px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.component.ts import { XParam, @@ -86344,7 +86344,7 @@ export class XToolbarComponent extends XToolbarContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-page\x-toolbar\x-toolbar.typings.ts import { Input, @@ -87128,7 +87128,7 @@ export abstract class XComponentToolbarContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.component.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; import { XProgressBarAction, XProgressBarActionModel, XProgressBarContainerComponent, XProgressBarType } from './x-progress-bar.typings'; @@ -87256,7 +87256,7 @@ export class XProgressBarComponent extends XProgressBarContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -87270,7 +87270,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XProgressBarModule { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-progress-bar\x-progress-bar.typings.ts import { Subject, @@ -87528,7 +87528,7 @@ export class XComponentProgressBarContainer } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.html
    @@ -87552,7 +87552,7 @@ export class XComponentProgressBarContainer
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.scss .x-overlay { top: 0px; @@ -87574,7 +87574,7 @@ export class XComponentProgressBarContainer } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.component.ts import { ViewChild, @@ -87894,7 +87894,7 @@ export class XScreenCaptureComponent extends XScreenCaptureContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.container.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.container.ts import { Input, @@ -88044,7 +88044,7 @@ export abstract class XScreenCaptureContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -88058,7 +88058,7 @@ import { XScreenCaptureComponent } from './x-screen-capture.component'; }) export class XScreenCaptureModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.service.ts import { XMimeType, @@ -88333,7 +88333,7 @@ export class XScreenCaptureService extends XBaseService { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-screen-capture\x-screen-capture.typings.ts import { Options } from 'dom-to-image'; @@ -88356,7 +88356,7 @@ export interface XScreenCaptureDimensions { height: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.scss :host { --clear-icon-color: var(--x-color-danger); @@ -88421,7 +88421,7 @@ export interface XScreenCaptureDimensions { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.component.ts import { nameof, @@ -88710,7 +88710,7 @@ export class XSearchBarComponent extends XSearchBarContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -88731,7 +88731,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XSearchBarModule { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-search-bar\x-search-bar.typings.ts import { XResourceIDs, @@ -89569,7 +89569,7 @@ export abstract class XComponentSearchBarContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide.animation.providers.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide.animation.providers.ts import { XSlideAnimationProvider } from './x-slider.typings'; @@ -90095,7 +90095,7 @@ export const Flip: XSlideAnimationProvider = { }; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.html @@ -90152,7 +90152,7 @@ export const Flip: XSlideAnimationProvider = {
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.scss :host { --paginator: var(--x-color-dark-tint); @@ -90172,7 +90172,7 @@ ion-slides { padding-bottom: 30px !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.component.ts import { Component, @@ -90545,7 +90545,7 @@ export class XSliderComponent extends XSliderContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -90568,7 +90568,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XSliderModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slider.typings.ts import { Input, @@ -90818,7 +90818,7 @@ export abstract class XSliderContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.html @@ -90828,13 +90828,13 @@ export abstract class XSliderContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.scss .full-width { width: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.component.ts import { Component, @@ -90940,7 +90940,7 @@ export class XSlideComponent extends XSlideContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slider\x-slide\x-slide.typings.ts import { Input, @@ -91058,7 +91058,7 @@ export abstract class XSlideContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.component.ts import { Component, @@ -91345,7 +91345,7 @@ export class XSlotterComponent extends XSlotterContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -91360,7 +91360,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XSlotterModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slotter.typings.ts import { Input, @@ -91586,16 +91586,16 @@ export abstract class XSlotterContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.component.ts import { XSlotAction, @@ -91697,7 +91697,7 @@ export class XSlotComponent extends XSlotContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-slotter\x-slot\x-slot.typings.ts import { Input, @@ -91838,7 +91838,7 @@ export abstract class XSlotContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.scss :host { display: inline-block; @@ -91871,7 +91871,7 @@ ion-spinner { direction: ltr !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.component.ts import { XSpinnerAction, @@ -91968,7 +91968,7 @@ export class XSpinnerComponent extends XSpinnerContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -91982,7 +91982,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XSpinnerModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-spinner\x-spinner.typings.ts import { Input, @@ -92148,7 +92148,7 @@ export abstract class XSpinnerContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.html @@ -92327,7 +92327,7 @@ export abstract class XSpinnerContainerComponent > -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.scss :host { // @@ -92401,7 +92401,7 @@ button { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.component.ts import { ViewChild, @@ -93497,7 +93497,7 @@ export class XStepperComponent extends XStepperContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -93538,7 +93538,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XStepperModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-stepper.typings.ts import { Input, @@ -93835,7 +93835,7 @@ export abstract class XStepperContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.html @@ -93852,10 +93852,10 @@ export abstract class XStepperContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.component.ts import { XStepAction, @@ -93982,7 +93982,7 @@ export class XStepComponent extends XStepContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-stepper\x-step\x-step.typings.ts import { Input, @@ -94137,7 +94137,7 @@ export abstract class XStepContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.html
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.scss :host { // @@ -94259,7 +94259,7 @@ ion-badge { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.component.ts import { nameof, @@ -94728,7 +94728,7 @@ export class XTabNavigatorComponent extends XTabNavigatorContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -94743,7 +94743,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XTabNavigatorModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.tools.ts import { XTabNavigatorItem, @@ -94773,7 +94773,7 @@ export function toTabNavigatiorItem(page: XPage) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tab-navigator\x-tab-navigator.typings.ts import { Input, @@ -95057,7 +95057,7 @@ export abstract class XTabNavigatorContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.html @@ -95596,7 +95596,7 @@ export abstract class XTabNavigatorContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.scss ::ng-deep :root, :host { @@ -95699,7 +95699,7 @@ td.mat-footer-cell { visibility: hidden !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.component.ts import { nameof, @@ -97023,7 +97023,7 @@ export class XTableComponent extends XTableContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -97052,7 +97052,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XTableModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-table\x-table.typings.ts import { Inject, @@ -97657,7 +97657,7 @@ export abstract class XTableContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.html @@ -97733,7 +97733,7 @@ export abstract class XTableContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.scss :host { // @@ -97824,7 +97824,7 @@ x-card { background-color: var(--tab-header-color) !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.component.ts import { QueryList, @@ -98395,7 +98395,7 @@ export class XTabsComponent extends XTabsContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -98419,7 +98419,7 @@ import { XTabsContainerComponent } from './x-tabs.typings'; }) export class XTabsModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tabs.typings.ts import { Input, @@ -98809,7 +98809,7 @@ export class XTabsContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.html @@ -98819,13 +98819,13 @@ export class XTabsContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.scss .full-width { width: 100%; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.component.ts import { Component, @@ -98938,7 +98938,7 @@ export class XTabComponent extends XTabContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tabs\x-tab\x-tab.typings.ts import { Input, @@ -99054,7 +99054,7 @@ export abstract class XTabContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-typings.ts // //#region Form Interfaces ... @@ -99188,7 +99188,7 @@ export interface XThemeBaseFormModel { XThemeLightFormModel {} //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -99234,7 +99234,7 @@ import { XModelPresenterModule } from '../x-model-presenter/x-model-presenter.mo }) export class XThemeModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme.tools.ts import { XThemePack, XThemeType } from 'x-framework-core'; import { XThemeBaseFormModel, XThemeDarkFormModel, XThemeFormModel, XThemeLightFormModel } from './x-theme-typings'; @@ -99827,7 +99827,7 @@ export function getEmptyThemeFormModel() { } as XThemeFormModel; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.html @@ -100202,7 +100202,7 @@ export function getEmptyThemeFormModel() { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.scss :host ::ng-deep x-color { --size: 24px !important; @@ -100216,7 +100216,7 @@ export function getEmptyThemeFormModel() { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.component.ts import { nameof, @@ -101529,7 +101529,7 @@ export class XThemeManagerComponent extends XThemeManagerContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-theme\x-theme-manager\x-theme-manager.typings.ts import { Input, @@ -102737,7 +102737,7 @@ function XStandardType() { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.html
    () { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.scss :host { --thumbnail-size: 32px; @@ -102844,7 +102844,7 @@ ion-thumbnail.circular { position: relative; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.component.ts import { nameof, @@ -103078,7 +103078,7 @@ export class XThumbnailComponent extends XThumbnailContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -103093,7 +103093,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XThumbnailModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-thumbnail\x-thumbnail.typings.ts import { Input, @@ -103292,7 +103292,7 @@ export abstract class XThumbnailContainerComponent } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.html @@ -103398,7 +103398,7 @@ export abstract class XThumbnailContainerComponent -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.scss :host(::ng-deep.mat-tree) { background-color: unset !important; @@ -103408,7 +103408,7 @@ export abstract class XThumbnailContainerComponent align-items: baseline !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.component.ts import { XTreeNode, @@ -103705,7 +103705,7 @@ export class XTreeComponent extends XTreeContainerComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -103721,7 +103721,7 @@ import { XBaseComponentModule } from '../modules/x-base-component.module'; }) export class XTreeModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkComponentsHolder\projects\x-framework-components\src\lib\x-tree\x-tree.typings.ts import { Input, diff --git a/Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261109_153855.txt b/Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261112_120917.txt similarity index 95% rename from Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261109_153855.txt rename to Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261112_120917.txt index cc41d35..96dcb2b 100644 --- a/Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261109_153855.txt +++ b/Documents/GeneratedContext/xDashboard-xFrameworkCoreHolder-20261112_120917.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\jalali-moment.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\jalali-moment.d.ts declare function moment(inp?: moment.MomentInput, format?: moment.MomentFormatSpecification, strict?: boolean): moment.Moment; declare function moment(inp?: moment.MomentInput, format?: moment.MomentFormatSpecification, language?: string, strict?: boolean): moment.Moment; @@ -760,7 +760,7 @@ declare namespace moment { export = moment; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\public-api.ts /* * Public API Surface of x-framework-core @@ -894,7 +894,7 @@ export * from './lib/modules/x-directives.module'; export * from './lib/x-framework-core.module'; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\test.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\test.ts // This file is required by karma.conf.js and loads recursively all the .spec and framework files @@ -923,7 +923,7 @@ const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\x-framework-core.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\x-framework-core.module.ts import { NgModule } from '@angular/core'; import { IonicModule } from '@ionic/angular' @@ -947,14 +947,14 @@ import { XHammerGestureConfig } from './classes/x-hammer-gesture-config'; }) export class XFrameworkCoreModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-base.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-base.service.ts import { XLoggable } from './x-loggable'; export abstract class XBaseService extends XLoggable { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-hammer-gesture-config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-hammer-gesture-config.ts import { Injectable } from '@angular/core'; import { HammerGestureConfig } from '@angular/platform-browser'; @@ -974,7 +974,7 @@ export class XHammerGestureConfig extends HammerGestureConfig { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-loggable.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-loggable.ts import { isNullOrUndefined, @@ -1097,7 +1097,7 @@ export abstract class XLoggable implements GetLogTag { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-persian-date-adapter.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-persian-date-adapter.ts import * as moment_ from 'jalali-moment'; const moment = moment_; @@ -1347,7 +1347,7 @@ export const LocaleFactory = () => { return window[XParam.Language]; }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-renderer.class.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\classes\x-renderer.class.ts import { NgZone, @@ -1779,7 +1779,7 @@ export class XRenderer extends XLoggable { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\config\x-framework-core.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\config\x-framework-core.config.ts import { XCountryCode } from '../typings/x.typings'; import { XNotificationSound } from '../typings/x-notification.typings'; @@ -1848,7 +1848,7 @@ export interface XFrameworkCoreConfig { defaultActionDelay: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-border.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-border.enum.ts export enum XBorderStyle { Dotted = 'dotted', @@ -1865,7 +1865,7 @@ export enum XBorderStyle { export type XBorderStyleIdentifier = XBorderStyle | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-crud.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-crud.enum.ts export enum XCrudAction { Add = 'add', @@ -1875,7 +1875,7 @@ export enum XCrudAction { export type XCrudActionIdentifier = XCrudAction | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-exception.resources.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-exception.resources.ts import { XExceptionIndex } from '../typings/x-exception.typings'; @@ -2237,7 +2237,7 @@ export const Exceptions: XExceptionIndex = { //#endregion }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-file.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-file.enum.ts // //#region XFile Types ... @@ -2828,7 +2828,7 @@ export const XFileInfos = [ ]; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-header.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-header.enum.ts export enum XHeader { File = 'file', @@ -2855,7 +2855,7 @@ export function getAuthorizationHeaderValue(token: string) { return `${XHeader.AuthorizationPrefix}${token}`; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-param.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-param.enum.ts export enum XParam { // @@ -2900,13 +2900,13 @@ export enum XParam { export type XParamIdentifier = XParam | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-setting.resources.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-setting.resources.ts export enum XSettingsStorageKey { Locale = '[SETTINGS] Locale' } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-translation.resources.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x-translation.resources.ts export enum XResourceIDs { // @@ -3143,11 +3143,11 @@ export enum XResourceIDs { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x.constants.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\constants\x.constants.ts export const DEFAULT_JAVASCRIPT_VOID_HREF = 'javascript:void(0)'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-clipboard.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-clipboard.directive.ts import { Input, @@ -3197,7 +3197,7 @@ export class XClipboardDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-color.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-color.directive.ts import { Input, @@ -3298,7 +3298,7 @@ export class XColorDirective implements OnChanges { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-droppable.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-droppable.directive.ts import { Input, @@ -3536,7 +3536,7 @@ export class XDroppableDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-file-reader.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-file-reader.directive.ts import { Input, @@ -3674,7 +3674,7 @@ export class XFileReaderDirective implements OnInit, OnChanges, OnDestroy { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-focus-handler.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-focus-handler.directive.ts import { Input, @@ -3784,7 +3784,7 @@ export class XFocusedHandlerDirective { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-focus.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-focus.directive.ts import { Input, @@ -3878,7 +3878,7 @@ export class XFocusDirective } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-formatter.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-formatter.directive.ts import { Input, @@ -3942,7 +3942,7 @@ export class XFormatterDirective implements OnInit { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-mouse-handler.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-mouse-handler.directive.ts import { Input, @@ -4132,7 +4132,7 @@ export class XMouseHandlerDirective //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-enter.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-enter.directive.ts import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @@ -4153,7 +4153,7 @@ export class XOnEnterDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-escape.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-escape.directive.ts import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @@ -4174,7 +4174,7 @@ export class XOnEscapeDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-outside-click.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-on-outside-click.directive.ts import { Output, @@ -4206,7 +4206,7 @@ export class XOutsideClickDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-render.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-render.directive.ts import { Directive, @@ -4272,7 +4272,7 @@ export class XRenderDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-scroll-behavior.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-scroll-behavior.directive.ts import { Input, @@ -4604,7 +4604,7 @@ export class XScrollBehaviourDirective } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-slider.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-slider.directive.ts import { Input, @@ -4725,7 +4725,7 @@ export class XSliderDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-stop-click-propagation.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-stop-click-propagation.directive.ts import { Directive, HostListener } from '@angular/core'; @@ -4740,7 +4740,7 @@ export class XStopClickPropagationDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-var.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\directives\x-var.directive.ts import { isNullOrUndefined, @@ -4797,7 +4797,7 @@ export class XVarDirective { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\guards\x-can-deactivate.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\guards\x-can-deactivate.guard.ts import { CanDeactivate, @@ -4830,7 +4830,7 @@ export class XCanDeactivateGuard implements CanDeactivate { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-base-dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-base-dto.ts import { isSameObject } from '../tools/x-object.tools'; @@ -4894,7 +4894,7 @@ export interface XBaseStorableDto extends XBaseDto { id?: T } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-base.indexed.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-base.indexed.dto.ts import { XBaseDto } from './x-base-dto'; @@ -4907,7 +4907,7 @@ export interface XBaseIndexedDto extends XBaseDto { export interface XBaseIntIndexedDto extends XBaseIndexedDto {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-grouped-data.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\models\x-grouped-data.dto.ts import { XBaseDto } from "./x-base-dto"; @@ -4917,7 +4917,7 @@ export interface XGroupedDataDto extends XBaseDto { timeStamp: Date; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\modules\x-directives.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\modules\x-directives.module.ts import { NgModule } from '@angular/core'; import { IonicModule } from '@ionic/angular'; @@ -5026,7 +5026,7 @@ import { XStopClickPropagationDirective } from '../directives/x-stop-click-propa }) export class XDirectivesModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-as.pipe.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-as.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @@ -5047,7 +5047,7 @@ export class XAsPipe implements PipeTransform { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-formatter.pipe.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-formatter.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { applyFormat, clearFormat } from '../tools/x-formatter.tools'; @@ -5089,7 +5089,7 @@ export class XFormatterPipe implements PipeTransform { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-log.pipe.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-log.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @@ -5111,7 +5111,7 @@ export class XLogPipe implements PipeTransform { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-safe-html.pipe.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\pipes\x-safe-html.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @@ -5130,7 +5130,7 @@ export class XSafeHtmlPipe implements PipeTransform { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tokens\x-injectable-tokens.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tokens\x-injectable-tokens.ts import { InjectionToken } from '@angular/core'; import { XFrameworkCoreConfig } from '../config/x-framework-core.config'; @@ -5139,7 +5139,7 @@ export const X_FRAMEWORK_CORE_CONFIG = new InjectionToken( 'x_config' ); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-array.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-array.tools.ts // //#region Array Tools ... @@ -5451,7 +5451,7 @@ export function isXEqual(a: T[], b: T[]): boolean { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-color.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-color.tools.ts import { isNumber, @@ -6669,7 +6669,7 @@ export function getXColorValue(color: XColorIdentifier) { return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-date-time.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-date-time.tools.ts import { isDate, @@ -7246,7 +7246,7 @@ export function isValueDate(source: any) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-exception.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-exception.tools.ts import { keys, @@ -7394,7 +7394,7 @@ export type XExceptionIdentifier = | XException | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-file.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-file.tools.ts import { XMimeType, @@ -8629,7 +8629,7 @@ export function downloadFile( //#endregion //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-formatter.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-formatter.tools.ts import { hasChild } from './x-array.tools'; import { removeAll } from './x-string.tools'; @@ -8919,7 +8919,7 @@ function getCurrencyFormattedValue(options: XFormatterOption, value: any) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-number.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-number.tools.ts // //#region Number Tools ... @@ -8946,7 +8946,7 @@ export function random(min?: number, max?: number) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-object.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-object.tools.ts import { isDate, @@ -10113,7 +10113,7 @@ export function waitForXElements(selector: string): Promise { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-observable.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-observable.tools.ts import { of, @@ -10302,7 +10302,7 @@ export function nextSubjectWhenElementExists( } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-page.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-page.tools.ts import { toPromise } from './x-observable.tools'; import { XPage } from '../typings/x-page.typings'; @@ -10451,7 +10451,7 @@ export async function parentPagesByRoute( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-string.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-string.tools.ts import { Md5 } from 'md5-typescript'; import { hasChild, toArray } from './x-array.tools'; @@ -10970,7 +10970,7 @@ export function parseListString(listString: string, seperator: string = ',') { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-task.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-task.tools.ts export const taskIdStartKey = '_['; export const taskIdEndKey = ']'; @@ -11062,7 +11062,7 @@ export function setTaskId(key: string | any, id: string | any) { return `${key.toString()}${taskIdStartKey}${id.toString()}${taskIdEndKey}`; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-to-form-data.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-to-form-data.ts import { isDate, @@ -11213,7 +11213,7 @@ export async function logFormData(source: FormData) { console.log(result); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-convert.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-convert.tools.ts // //#region Type Converter ... @@ -11275,7 +11275,7 @@ export function toBoolean(object: any) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-defaults.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-defaults.tools.ts import { isArray, @@ -11343,7 +11343,7 @@ export function getDefaultValue(t: XStandardType): Observable { ); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-detect.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-type-detect.tools.ts /** * Custom Data Types ... @@ -11561,7 +11561,7 @@ export function isPromise(variable: any) { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-uuid-tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\tools\x-uuid-tools.ts import { v4 as uuidv4 } from 'uuid'; import { v5 as uuidv5 } from 'uuid'; @@ -11580,11 +11580,11 @@ export function generateUuid( return result; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-base-component.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-base-component.typings.ts export const DEFAULT_EXPORT_TYPING_BASE = 'default'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-color.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-color.typings.ts // import { XBaseKeyValue } from './x.typings'; @@ -11692,7 +11692,7 @@ export type XColorFormatIdentifier = XColorFormat | string; export interface XColorKeyValue extends XBaseKeyValue {} //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-date-time.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-date-time.typings.ts export enum XUnitOfTime { Year, @@ -11700,7 +11700,7 @@ export enum XUnitOfTime { Day } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-exception.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-exception.typings.ts import { XExceptionIDs, Exceptions } from '../constants/x-exception.resources'; @@ -11716,7 +11716,7 @@ export type XExceptionIndex = { export type XExceptions = keyof typeof Exceptions; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-manager.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-manager.typings.ts export enum XUiEvent { // @@ -11739,7 +11739,7 @@ export enum XUiEvent { Ready } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-notification.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-notification.typings.ts import { AlertInput, @@ -12004,7 +12004,7 @@ export interface XPickerOptions extends XXPickerOptions { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-page.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-page.typings.ts import { XOneOrManyType } from './x.typings'; import { XResourceIdentifier } from './x-translation.typings'; @@ -12020,7 +12020,7 @@ export interface XPage { description?: XResourceIdentifier; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-query.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-query.typings.ts export interface XBaseDataPagerQuery { filter?: string; @@ -12033,7 +12033,7 @@ export interface XBaseDataPagerQueryResult { items: T[]; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-setting.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-setting.typings.ts export type XOrientation = 'landscape' | 'portrait'; @@ -12062,7 +12062,7 @@ export type XCssProperties = | 'toolbar-height' | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-storage.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-storage.typings.ts /** * represent a single item which can be stored ... @@ -12072,7 +12072,7 @@ export interface XStorageItem { value: string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-task-manager.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-task-manager.typings.ts import { Observable } from 'rxjs'; import { XException } from './x-exception.typings'; @@ -12093,7 +12093,7 @@ export interface XTask { error?: XException; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-theme-manager.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-theme-manager.typings.ts export enum XThemeType { Light = 'light', @@ -12231,7 +12231,7 @@ export interface XThemePack { dark: XThemeDescriptor; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-translation.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x-translation.typings.ts import { XResourceIDs } from '../constants/x-translation.resources'; import { toEnNumbers, toPersianNumbers } from '../tools/x-string.tools'; @@ -12285,7 +12285,7 @@ export function applyLocale(content: string, locale: XLocale = 'en-US') { export type XResourceIdentifier = XResourceIDs | XTranslationId | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\typings\x.typings.ts import { Observable } from 'rxjs'; import { XFileBlob } from '../tools/x-file.tools'; @@ -12517,7 +12517,7 @@ export type XGConstructor = new (...args: any[]) => T; export type XConstructor = new (...args: any[]) => {}; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-general-validators.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-general-validators.ts import { XPhoneNumber, @@ -12836,7 +12836,7 @@ export class XValidators { } //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-email.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-email.directive.ts import { Directive } from '@angular/core'; import { isValidEmail } from './x-general-validators'; @@ -12868,7 +12868,7 @@ export class XValidEmailDirective implements Validator { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-phone-number.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-phone-number.directive.ts import { XCountryCode } from '../typings/x.typings'; import { Directive, Input, Inject } from '@angular/core'; @@ -12907,7 +12907,7 @@ export class XValidPhoneNumberDirective implements Validator { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-url.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-valid-url.directive.ts import { Directive, Input } from '@angular/core'; import { isValidURL } from './x-general-validators'; @@ -12946,7 +12946,7 @@ export class XValidUrlDirective implements Validator { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-value-match.directive.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkCoreHolder\projects\x-framework-core\src\lib\validators\x-value-match.directive.ts import { NgModel, diff --git a/Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261109_153901.txt b/Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261112_120926.txt similarity index 96% rename from Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261109_153901.txt rename to Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261112_120926.txt index 5697b28..0d601fe 100644 --- a/Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261109_153901.txt +++ b/Documents/GeneratedContext/xDashboard-xFrameworkIdentitySDKHolder-20261112_120926.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\public-api.ts /* * Public API Surface of x-framework-identity-sdk @@ -72,7 +72,7 @@ export * from './lib/tokens/x-injectable-tokens'; // Module ... export * from './lib/x-framework-identity-sdk.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\test.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\test.ts // This file is required by karma.conf.js and loads recursively all the .spec and framework files @@ -101,7 +101,7 @@ const context = require.context('./', true, /\.spec\.ts$/); // And load the modules. context.keys().map(context); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\x-account.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\x-account.service.ts import { X_API_CONFIG, @@ -134,7 +134,7 @@ export class XAccountService extends XAccountFinalService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\x-framework-identity-sdk.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\x-framework-identity-sdk.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -162,7 +162,7 @@ import { XFrameworkServicesModule } from 'x-framework-services'; }) export class XFrameworkIdentitySdkModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\base\x-base-api.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\base\x-base-api.service.ts import { XParam, @@ -791,7 +791,7 @@ export abstract class XBaseApiService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\config\x-api-service.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\config\x-api-service.config.ts import { XApiHeader, @@ -945,7 +945,7 @@ export const COLLECTION_FORMATS = { pipes: '|' }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\config\x-framework-identity-sdk.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\config\x-framework-identity-sdk.config.ts import { XFrameworkCoreConfig } from 'x-framework-core'; import { XFrameworkServicesConfig } from 'x-framework-services'; @@ -1012,7 +1012,7 @@ export interface XFrameworkIdentitySDKConfig extends XSharedConfig { Pages: any; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-account.keys.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-account.keys.ts export enum XAccountStorageKeys { UserSelectBy = '[ACCOUNT] USER', @@ -1020,7 +1020,7 @@ export enum XAccountStorageKeys { UserInfos = '[ACCOUNT] USER INFO' } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-api-scope.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-api-scope.enum.ts export enum XApiScope { Read, @@ -1029,7 +1029,7 @@ export enum XApiScope { Manage, } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-header.enum.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\constants\x-header.enum.ts export enum XApiHeader { ExpiresAt = 'expires_at', @@ -1042,7 +1042,7 @@ export function getAuthorizationHeaderValue(token: string): string { return `${XApiHeader.AuthorizationPrefix}${token}`; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\guards\auth.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\guards\auth.guard.ts import { Route, @@ -1144,7 +1144,7 @@ export class AuthGuard //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\guards\not-auth.guard.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\guards\not-auth.guard.ts import { Route, @@ -1251,7 +1251,7 @@ export class NotAuthGuard //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\helpers\x-account.helper.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\helpers\x-account.helper.ts import { XValidators } from 'x-framework-core'; import { XUserAccountInfo } from '../typings/x-account.typings'; @@ -1267,7 +1267,7 @@ export function validateUserAccountInfo(model: XUserAccountInfo): void { XValidators.validateBiggerThan(0, model.expiresAt); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-device-info.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-device-info.dto.ts export interface XDeviceInfo { os: string; @@ -1288,7 +1288,7 @@ export enum XDeviceTypes { Desktop } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-discovery.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-discovery.dto.ts import { XBaseDto } from 'x-framework-core'; @@ -1351,7 +1351,7 @@ export interface XDiscoveryDto extends XBaseDto { tokenEndpointAuthenticationMethodsSupported?: Array; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-friend-dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-friend-dto.ts import { XBaseDto, @@ -1436,7 +1436,7 @@ export function isDefaultFriendDto(model: XFriendDto) { return isSameObject(prepareFriendDtoFields(model), defaultFriendDto); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-friendship.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-friendship.dto.ts import { XBaseDto } from 'x-framework-core'; @@ -1472,7 +1472,7 @@ export interface XFriendshipInfoDto { followings: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-login.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-login.dto.ts import { XLocale } from 'x-framework-core'; import { XUserProfileDto } from './x-user.dto'; @@ -1496,7 +1496,7 @@ export interface XLoginResponseDto extends XTokenResponseDto { profile: XUserProfileDto; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-page.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-page.dto.ts export interface XPageRequestDto { first?: number; @@ -1514,7 +1514,7 @@ export interface XPageResponseDto { hasPreviousPage: boolean; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-query.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-query.dto.ts export interface XQueryDto { page?: number; @@ -1536,7 +1536,7 @@ export interface XQueryResultDto { totalFilteredPages?: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-registration-dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-registration-dto.ts import { XDeviceInfo } from './x-device-info.dto'; import { XBaseRequestDto, XBaseResponseDto } from 'x-framework-core'; @@ -1568,7 +1568,7 @@ export interface XActionResponseDto extends XBaseResponseDto { expiration?: Date; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-string.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-string.dto.ts import { XLocale, @@ -1631,7 +1631,7 @@ export function isDefaultStringDto(model: XStringDto) { return isSameObject(prepareStringDtoFields(model), defaultStringDto); } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-user.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\models\x-user.dto.ts import { fromUtcDate, @@ -1823,7 +1823,7 @@ export interface XBusinessOwner extends XBaseNumberIDDto { userId: string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.admin.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.admin.service.ts import { Observable } from 'rxjs'; import { @@ -2001,7 +2001,7 @@ export class XAccountAdminService extends XAccountRegistrationService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.authentication.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.authentication.service.ts import { XHeader, @@ -2546,7 +2546,7 @@ export abstract class XAccountAuthenticationService extends XAccountBaseService //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.base.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.base.service.ts import { keys, @@ -3790,7 +3790,7 @@ export abstract class XAccountBaseService extends XBaseApiService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.final.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.final.service.ts import { Observable, of } from 'rxjs'; import { filter, map } from 'rxjs/operators'; @@ -3833,7 +3833,7 @@ export abstract class XAccountFinalService extends XAccountSearchService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.friendship.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.friendship.service.ts import { Observable } from 'rxjs'; import { @@ -5186,7 +5186,7 @@ export abstract class XAccountFriendshipService extends XAccountProfileService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.profile.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.profile.service.ts import { XavatarDto, @@ -5885,7 +5885,7 @@ export abstract class XAccountProfileService extends XAccountAuthenticationServi //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.registration.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.registration.service.ts import { of } from 'rxjs'; import { Observable } from 'rxjs'; @@ -7009,7 +7009,7 @@ export abstract class XAccountRegistrationService extends XAccountFriendshipServ //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.search.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\partial\x-account.search.service.ts import { Observable } from 'rxjs'; import { @@ -7081,7 +7081,7 @@ export abstract class XAccountSearchService extends XAccountAdminService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\providers\x-url.encoder.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\providers\x-url.encoder.ts import { HttpUrlEncodingCodec } from '@angular/common/http'; @@ -7096,7 +7096,7 @@ export class XHttpUrlEncodingCodec extends HttpUrlEncodingCodec { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\services\api-http-interceptor.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\services\api-http-interceptor.service.ts import { XHeader, @@ -7442,7 +7442,7 @@ export class ApiHttpInterceptorService //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\tokens\x-injectable-tokens.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\tokens\x-injectable-tokens.ts import { InjectionToken } from '@angular/core'; import { XApiConfiguration } from '../config/x-api-service.config'; @@ -7456,7 +7456,7 @@ export const X_API_CONFIG = new InjectionToken( 'apiConfiguration' ); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\tools\x-endpoint.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\tools\x-endpoint.tools.ts import { values, @@ -7529,7 +7529,7 @@ export function setParams( return route; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-account.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-account.typings.ts import { XLoginResponseDto } from '../models/x-login.dto'; @@ -7545,7 +7545,7 @@ export interface XAccountState extends XUserAccountInfo { isLoggedIn: boolean; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-endpoint.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-endpoint.typings.ts export enum XEndPoint { Account, @@ -7678,7 +7678,7 @@ export enum XAccountEndPoint { export type XAccountEndPoints = keyof typeof XAccountEndPoint; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-registration.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\typings\x-registration.typings.ts export enum RegistrationStep { Terms = 'terms', @@ -7691,7 +7691,7 @@ export enum RegistrationStep { export type RegistrationStepIdentifier = RegistrationStep | string; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\validators\api-validators.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkIdentitySDKHolder\projects\x-framework-identity-sdk\src\lib\validators\api-validators.ts import { tap, diff --git a/Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261109_153904.txt b/Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261112_120931.txt similarity index 91% rename from Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261109_153904.txt rename to Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261112_120931.txt index 72bc0b1..26fd5f0 100644 --- a/Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261109_153904.txt +++ b/Documents/GeneratedContext/xDashboard-xFrameworkPushServiceHolder-20261112_120931.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\public-api.ts /* * Public API Surface of x-framework-push-service @@ -33,7 +33,7 @@ export * from './lib/base/x-base-entity.push.service'; // Module ... export * from './lib/x-framework-push-service.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\x-framework-push-service.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\x-framework-push-service.module.ts import { NgModule } from '@angular/core'; @@ -47,7 +47,7 @@ import { NgModule } from '@angular/core'; }) export class XFrameworkPushServiceModule { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-entity.push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-entity.push.service.ts import { Subject } from 'rxjs'; import { Injectable } from '@angular/core'; @@ -435,7 +435,7 @@ export abstract class XBaseEntityPushService extends XBasePushService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-push.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-push.service.ts import { isFunction, @@ -768,7 +768,7 @@ export abstract class XBasePushService extends XBaseService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-web-rtc.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-base-web-rtc.service.ts import { Subject } from 'rxjs'; import { @@ -905,7 +905,7 @@ export abstract class XBaseWebRTCService extends XBasePushService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-rtc-peer.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\base\x-rtc-peer.service.ts import { Inject, Injectable } from '@angular/core'; @@ -938,7 +938,7 @@ export class XRTCPeerService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\config\x-framework-push-service.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\config\x-framework-push-service.config.ts import { LogLevel } from '@microsoft/signalr'; import { XFrameworkCoreConfig } from 'x-framework-core'; @@ -960,7 +960,7 @@ export interface XFrameworkPushServiceConfig extends XSharedConfig { iceServers: Array; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\models\x-hub-connection.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\models\x-hub-connection.dto.ts import { XBaseDto } from 'x-framework-core'; @@ -970,7 +970,7 @@ export interface XHubConnectionDto extends XBaseDto { connectionId: string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\policies\x-push-service-connection-retry-policy.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\policies\x-push-service-connection-retry-policy.ts import { Inject } from '@angular/core'; import { IRetryPolicy, RetryContext } from '@microsoft/signalr'; @@ -1009,7 +1009,7 @@ export class XPushServiceConnectionRetryPolicy implements IRetryPolicy { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\policies\x-push-service-token-fetcher.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\policies\x-push-service-token-fetcher.ts import { Observable } from 'rxjs'; @@ -1021,7 +1021,7 @@ export interface IXPushServiceTokenFetcher { getToken(): string; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\tokens\x-injectable-tokens.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkPushServiceHolder\projects\x-framework-push-service\src\lib\tokens\x-injectable-tokens.ts import { InjectionToken } from '@angular/core'; import { IXPushServiceTokenFetcher } from '../policies/x-push-service-token-fetcher'; @@ -1035,7 +1035,7 @@ export const X_FRAMEWORK_PUSH_SERVICE_TOKEN_FETCHER = new InjectionToken('x_config'); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-base.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-base.service.ts import { Location } from '@angular/common'; import { XBaseService } from 'x-framework-core'; @@ -7659,13 +7659,13 @@ export abstract class XManagerBaseService extends XBaseService { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-final.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-final.service.ts import { XManagerRouteService } from './x-manager-route.service'; export abstract class XManagerFinalService extends XManagerRouteService {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-route.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-route.service.ts import { keys, @@ -8067,7 +8067,7 @@ export abstract class XManagerRouteService extends XManagerUIStateService { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-ui-state.service.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xFrameworkServicesHolder\projects\x-framework-services\src\lib\x-manager-service-partial\x-manager-ui-state.service.ts import { XLocale, diff --git a/Documents/GeneratedContext/xDashboard-xFrameworkTest-20261109_153847.txt b/Documents/GeneratedContext/xDashboard-xFrameworkTest-20261112_120905.txt similarity index 96% rename from Documents/GeneratedContext/xDashboard-xFrameworkTest-20261109_153847.txt rename to Documents/GeneratedContext/xDashboard-xFrameworkTest-20261112_120905.txt index 202da00..e0f8a72 100644 --- a/Documents/GeneratedContext/xDashboard-xFrameworkTest-20261109_153847.txt +++ b/Documents/GeneratedContext/xDashboard-xFrameworkTest-20261112_120905.txt @@ -1,5 +1,5 @@ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-device\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-device\types\index.d.ts // Type definitions for Apache Cordova Device plugin // Project: https://github.com/apache/cordova-plugin-device @@ -38,7 +38,7 @@ interface Device { declare var device: Device; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\src\wp\ResolutionHelper.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\src\wp\ResolutionHelper.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -80,7 +80,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\src\wp\SplashScreen.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\src\wp\SplashScreen.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -338,7 +338,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-splashscreen\types\index.d.ts // Type definitions for Apache Cordova Splashscreen plugin // Project: https://github.com/apache/cordova-plugin-splashscreen @@ -358,7 +358,7 @@ interface Navigator { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-statusbar\src\wp\StatusBar.cs +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-statusbar\src\wp\StatusBar.cs /* Licensed under the Apache License, Version 2.0 (the "License"); @@ -502,7 +502,7 @@ namespace WPCordovaClassLib.Cordova.Commands } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-statusbar\types\index.d.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\plugins\cordova-plugin-statusbar\types\index.d.ts // Type definitions for Apache Cordova StatusBar plugin // Project: https://github.com/apache/cordova-plugin-statusbar @@ -582,7 +582,7 @@ interface StatusBar { declare var StatusBar: StatusBar; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\index.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\index.html @@ -615,7 +615,7 @@ declare var StatusBar: StatusBar; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\main.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\main.ts import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @@ -630,7 +630,7 @@ if (environment.production) { platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\polyfills.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\polyfills.ts /** * This file includes polyfills needed by Angular and is loaded before the app. @@ -698,7 +698,7 @@ import 'zone.js'; // Included with Angular CLI. * APPLICATION IMPORTS */ -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\app-routing.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\app-routing.module.ts import { NgModule } from '@angular/core'; import { Pages, BaseRoutes } from './config/page.config'; @@ -771,16 +771,16 @@ const routes: Routes = [ }) export class AppRoutingModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\app.component.ts import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; @@ -800,7 +800,7 @@ export class AppComponent { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\app.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\app.module.ts import { XCanDeactivateGuard, @@ -879,7 +879,7 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; }) export class AppModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\app-config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\app-config.ts import { DefaultLocale, @@ -990,7 +990,7 @@ export const xSharedConfig: XSharedConfig = { ...xAppSharedConfig, }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\app.localization.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\app.localization.config.ts import { XTranslationItem } from 'x-framework-core'; @@ -2921,7 +2921,7 @@ export const EnCustomLocales: XTranslationItem[] = [ //#endregion ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\audio.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\audio.config.ts import { XNotificationSound, XActionType } from 'x-framework-core'; @@ -2940,7 +2940,7 @@ export const NotificationAudioSources: XNotificationSound[] = [ }, ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\exceptions.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\exceptions.config.ts import { XTranslationItem } from 'x-framework-core'; @@ -3482,7 +3482,7 @@ export const XEnUSExceptions: XTranslationItem[] = [ //#endregion ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\localization.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\localization.config.ts import { XLocale, XLanguageDescriptor } from 'x-framework-core'; import { EnCustomLocales, FaCustomLocales } from './app.localization.config'; @@ -5121,7 +5121,7 @@ export const AvailableTranslationResources: XLanguageDescriptor[] = [ }, ]; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\page.config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\page.config.ts import { XIconNames, @@ -5885,7 +5885,7 @@ export const TabNavsItems: XTabNavigatorItem[] = [ ]; //#endregion -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\config\x-config.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\config\x-config.ts import { XConfig } from './app-config'; import { environment } from '../../environments/environment'; @@ -5897,7 +5897,7 @@ export const XCONFIG: XConfig = JSON.parse( export const X_CONFIG = new InjectionToken('x_config'); -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\components.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\components.module.ts import { NgModule } from '@angular/core'; import { FabPage } from './fab/fab.page'; @@ -6083,7 +6083,7 @@ import { ChartPage } from './chart/chart.page'; }) export class ComponentsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.scss .content-container { margin: 24px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\card\card.page.ts import { Component } from '@angular/core'; import { VPageComponent } from '../../../views/v-page/v-page.component'; @@ -6319,7 +6319,7 @@ this component use to present a part of a page. } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\chart\chart.page.ts import { XChartOptions, @@ -6967,7 +6967,7 @@ export class ChartPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\color-picker\color-picker.page.ts import { XColorPickerOutputFormat, @@ -7132,7 +7132,7 @@ export class ColorPickerPage extends VPageComponent { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.scss .content-container { margin: 24px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\counter\counter.page.ts import { XColor, @@ -7445,7 +7445,7 @@ export class CounterPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.scss .content-container { margin: 24px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\description-list\description-list.page.ts import { Component } from '@angular/core'; import { XResourceIDs, isNullOrEmptyString } from 'x-framework-core'; @@ -7602,7 +7602,7 @@ this component used to show a data model in an structural template } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-list\expandable-list.page.ts import { XColor, @@ -7848,7 +7848,7 @@ async handleItemSelected(item: XExpandableListItem) { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.html ) { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\expandable-panel\expandable-panel.page.ts import { Component } from '@angular/core'; import { XIconNames } from 'x-framework-components'; @@ -8080,7 +8080,7 @@ export class ExpandablePanelPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\fab\fab.page.ts import { XFabItem, @@ -8505,7 +8505,7 @@ fabHandler = async (id?: string) => { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.html { -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.scss // $size: 32px !important; @@ -8857,7 +8857,7 @@ x-thumbnail { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\file-components\file-components.page.ts import { Inject, @@ -9514,7 +9514,7 @@ export class FileComponentsPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.html {{ item.data }} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\form\form.page.ts import { keys, @@ -11375,7 +11375,7 @@ export class FormPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\grid\grid.page.ts import { XGridItem, @@ -11621,7 +11621,7 @@ templGridItems: XGridItem[] = this.tempList.map((i) => { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.html [] = this.tempList.map((i) => {
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\icon\icon.page.ts import { XSpinner, @@ -11967,7 +11967,7 @@ export class IconPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\ide\ide.page.ts import { Component } from '@angular/core'; import { isNullOrEmptyString } from 'x-framework-core'; @@ -12166,7 +12166,7 @@ export function applyToDataPagerQueryResult( //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.html ( -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\introduction\introduction.page.ts import { XResourceIDs, @@ -12285,7 +12285,7 @@ getting deep dive into all components of this module is very usefull to make eas } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.html {{item.data}} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\list\list.page.ts import { XColor, @@ -12710,7 +12710,7 @@ private prepareListItems() { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.scss x-map { --map-height: 500px; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\map\map.page.ts import { Inject, @@ -13096,7 +13096,7 @@ export class MapPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\markdown\markdown.page.ts import { Component } from '@angular/core'; import { XIconNames } from 'x-framework-components'; @@ -13287,7 +13287,7 @@ export class MarkdownPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\model-presenter\model-presenter.page.ts import { nameof, @@ -14242,7 +14242,7 @@ async handleModelChanged(event: any) { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\page\page.page.ts import { Component } from '@angular/core'; import { XIconNames } from 'x-framework-components'; @@ -14408,7 +14408,7 @@ this page and all pages you explored until now created useing this Component. //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.scss .slide-content { direction: ltr; @@ -14509,7 +14509,7 @@ this page and all pages you explored until now created useing this Component. } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\slider\slider.page.ts import { Component } from '@angular/core'; import { XIconNames } from 'x-framework-components'; @@ -14651,7 +14651,7 @@ this Component used to provide Slideable Content's. //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\small-components.page.ts import { XColor, @@ -16403,7 +16403,7 @@ this component used when user requet item(s) from resources and the result is em //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.html

    Sample Modal Component

    @@ -16414,10 +16414,10 @@ this component used when user requet item(s) from resources and the result is em CLOSE
    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\small-components\sample-modal\sample-modal.component.ts import { Component, Input } from '@angular/core'; import { ModalController, PopoverController } from '@ionic/angular'; @@ -16462,7 +16462,7 @@ export class SampleModalComponent { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\stepper\stepper.page.ts import { XIconNames, @@ -16863,7 +16863,7 @@ export class StepperPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tab-navigator\tab-navigator.page.ts import { Component } from '@angular/core'; import { Pages } from 'src/app/config/page.config'; @@ -17005,7 +17005,7 @@ export class TabNavigatorPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\table\table.page.ts import { XResourceIDs, @@ -17886,7 +17886,7 @@ this Component used to show a collection of related Data in a Table. //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.scss .tab-wrapper { padding: { @@ -18004,7 +18004,7 @@ this Component used to show a collection of related Data in a Table. }; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tabs\tabs.page.ts import { XTabAlign, @@ -18183,7 +18183,7 @@ export class TabsPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.scss :host(::ng-deep.mat-tree-node) { align-items: baseline !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\components\tree\tree.page.ts import { Subject } from 'rxjs'; import { @@ -18565,7 +18565,7 @@ export class TreePage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\core.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\core.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -18594,7 +18594,7 @@ import { BaseRoutes, ServicesRoutes } from 'src/app/config/page.config'; }) export class CorePageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\core\introduction\introduction.page.ts import { XResourceIDs, @@ -18709,7 +18709,7 @@ for complete descriptions please read this module documentaions. } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\home.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\home.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -18738,7 +18738,7 @@ import { IntroductionPage } from './introduction/introduction.page'; }) export class HomePageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\home\introduction\introduction.page.ts import { Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -18872,7 +18872,7 @@ export class IntroductionPage extends VPageComponent { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\services.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\services.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -18906,7 +18906,7 @@ import { UserDevicePage } from './user-device/user-device.page'; }) export class ServicesPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\introduction\introduction.page.ts import { XResourceIDs, @@ -19089,7 +19089,7 @@ for more information, please read documentation. } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\services\user-device\user-device.page.ts import { Component } from '@angular/core'; import { XResourceIDs, XColorWithBrightness } from 'x-framework-core'; @@ -19148,7 +19148,7 @@ export class UserDevicePage extends VPageComponent { device = this.managerService.settingsService.device; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tabs.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tabs.module.ts import { TabsPage } from './tabs.page'; import { NgModule } from '@angular/core'; @@ -19194,7 +19194,7 @@ import { Pages, BaseRoutes } from 'src/app/config/page.config'; }) export class TabsPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tabs.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tabs.page.ts import { Component } from '@angular/core'; import { XColorWithBrightness } from 'x-framework-core'; @@ -19224,14 +19224,14 @@ export class TabsPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.html

    Tab Page 1

    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-1\tab-page-1.page.ts import { Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -19265,14 +19265,14 @@ export class TabPage1Page extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.html

    Tab Page 2

    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-2\tab-page-2.page.ts import { Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -19306,14 +19306,14 @@ export class TabPage2Page extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.html

    Tab Page 3

    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\tabs\tab-page-3\tab-page-3.page.ts import { Component } from '@angular/core'; import { VPageComponent } from 'src/app/views/v-page/v-page.component'; @@ -19347,7 +19347,7 @@ export class TabPage3Page extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\themes.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\themes.module.ts import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; @@ -19378,7 +19378,7 @@ import { ThemeManagerPage } from './theme-manager/theme-manager.page'; }) export class ThemesPageModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.scss -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\pages\themes\theme-manager\theme-manager.page.ts import { XThemePack, @@ -19591,7 +19591,7 @@ export class ThemeManagerPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\public-api.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\public-api.ts // // Tools ... @@ -19623,7 +19623,7 @@ export * from './v-page/v-page.component'; // Module ... export * from './views.module'; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\views.module.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\views.module.ts import { XFrameworkCoreModule, @@ -19818,7 +19818,7 @@ import { VMaintainerComponent } from './v-maintainer/v-maintainer.component'; }) export class ViewsModule {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-data-pager.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-data-pager.page.ts import { isSameObject, @@ -20264,7 +20264,7 @@ export abstract class VBaseDataPagerPage extends VBaseTabsPage { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-data-scroller.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-data-scroller.page.ts import { XTask, @@ -20596,7 +20596,7 @@ export abstract class VBaseDataScrollerPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-form-view.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-form-view.ts import { nameof, @@ -21359,7 +21359,7 @@ export abstract class VBaseFormViewComponent extends VBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-tabs.page.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base-tabs.page.ts import { Subject } from 'rxjs'; import { @@ -21553,7 +21553,7 @@ export abstract class VBaseTabsPage extends VPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\classes\v-base.component.ts import { Inject, @@ -21612,7 +21612,7 @@ export abstract class VBaseComponent extends XBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\models\x-query.dto.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\models\x-query.dto.ts export interface XQueryDto { filter?: string; @@ -21633,7 +21633,7 @@ export interface XQueryResultDto { totalItems?: number; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\task.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\task.tools.ts export const taskIdStartKey = '_['; export const taskIdEndKey = ']'; @@ -21725,7 +21725,7 @@ export function setTaskId(key: string | any, id: string | any) { return `${key.toString()}${taskIdStartKey}${id.toString()}${taskIdEndKey}`; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\v-base.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\v-base.tools.ts import { isValidEmail, @@ -21764,7 +21764,7 @@ import { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\v-data-pager.tools.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\tools\v-data-pager.tools.ts import { XBaseDataPagerQuery, @@ -21806,7 +21806,7 @@ import { } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\typings\v-base-form.typings.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\typings\v-base-form.typings.ts import { XBaseActionModel } from 'x-framework-components'; @@ -21833,7 +21833,7 @@ export type VBaseFormViewActionIdentifier = VBaseFormViewAction | string; export interface VBaseFormViewActionModel extends XBaseActionModel {} -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.html

    @@ -21906,7 +21906,7 @@ export interface VBaseFormViewActionModel

    -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.scss h1, h2, @@ -21932,7 +21932,7 @@ h6 { } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-maintainer\v-maintainer.component.ts import { Inject, @@ -21993,7 +21993,7 @@ export class VMaintainerComponent extends XBaseComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.html +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.html -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.scss .x-footer-content { margin: 0; @@ -22142,7 +22142,7 @@ x-page { // --side-menu-content-offset-bottom: -44px !important; } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\app\views\v-page\v-page.component.ts import { Input, @@ -22662,7 +22662,7 @@ export class VPageComponent extends XPageComponent { //#endregion } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\environments\environment.prod.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\environments\environment.prod.ts import { XConfig, xSharedConfig } from '../app/config/app-config'; @@ -22676,7 +22676,7 @@ export const environment = { } as XConfig }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\environments\environment.ts +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\environments\environment.ts import { XConfig, xSharedConfig } from '../app/config/app-config'; @@ -22690,7 +22690,7 @@ export const environment = { } as XConfig }; -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xFrameworkTest\src\theme\theme.scss +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xFrameworkTest\src\theme\theme.scss // // XFramework Color Mechanism ... diff --git a/Documents/GeneratedContext/xDashboard-xHttpService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xHttpService-20261109_152620.txt deleted file mode 100644 index 6199e1e..0000000 --- a/Documents/GeneratedContext/xDashboard-xHttpService-20261109_152620.txt +++ /dev/null @@ -1,767 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Configurations\XHttpServiceConfiguration.cs - -namespace xHttpService.Configurations { - public partial class XHttpServiceConfiguration { - /// - /// Determines Http Handler Check SSL or not ... - /// - /// - public bool DisableSSLCheck { get; set; } - public int DefaultClientTimeout { get; set; } = 360; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Constants\ConfigurationNodeNames.cs - -namespace xHttpService.Constants { - public partial struct ConfigurationNodeNames { - public const string HTTP_SERVICE_NODE_NAME = "HttpServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Constants\XHttpMethod.cs - -using xExceptions.Attributes; - -namespace xHttpService.Constants { - public enum XHttpMethod { - [StringValue ("GET")] - GET, - - [StringValue ("POST")] - POST, - - [StringValue ("PUT")] - PUT, - - [StringValue ("DELETE")] - DELETE - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Constants\XSSEConstants.cs - -namespace xHttpService.Constants -{ - public struct XSSEConstants - { - public const string DataIdentifier = "data:"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\DI\XDIHelperExtension.cs - -using System; -using xCommons.Extensions; -using xHttpService.Constants; -using xHttpService.Providers; -using xHttpService.Interfaces; -using xHttpService.Configurations; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xHttpService.DI { - public static partial class XDIHelperExtension { - /// - /// Retrieve XHttpService Configuration from AppSettings - /// - /// - /// - public static XHttpServiceConfiguration GetXHttpServiceConfiguration (this IConfiguration configuration) { - // - var xHttpSection = configuration.GetSection (ConfigurationNodeNames.HTTP_SERVICE_NODE_NAME); - return xHttpSection.Get (); - } - - /// - /// Register XHttpService Configuration - /// - /// - /// - public static void AddXHttpServiceConfiguration ( - this IServiceCollection services, - IConfiguration configuration - ) { - // - var httpServiceConfiguration = configuration.GetXHttpServiceConfiguration (); - services.AddXHttpServiceConfiguration(httpServiceConfiguration); - } - - /// - /// Register XHttpService Configuration - /// - /// - /// - public static void AddXHttpServiceConfiguration ( - this IServiceCollection services, - XHttpServiceConfiguration configuration - ) { - // - if (configuration.IsNull ()) { - Console.WriteLine($"xHttpService: there is no provided configurations, using default ..."); - configuration = new XHttpServiceConfiguration (); - } - - // - services.AddSingleton (configuration); - } - - /// - /// Register XHttpService on DI ... - /// - /// - /// - public static void AddXHttpService ( - this IServiceCollection services, - IConfiguration configuration - ) { - // - // Register Service Configuration ... - if (services.GetRegisteredService ().IsNull ()) { - services.AddXHttpServiceConfiguration (configuration); - } - - // - // Register Service ... - services.AddSingleton (); - } - - /// - /// Register XHttpService on DI ... - /// - /// - /// - public static void AddXHttpService ( - this IServiceCollection services, - XHttpServiceConfiguration configuration - ) { - // - // Register Service Configuration ... - if (services.GetRegisteredService ().IsNull ()) { - services.AddXHttpServiceConfiguration (configuration); - } - - // - // Register Service ... - services.AddSingleton (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Extensions\RestSharpExtensions.cs - -using RestSharp; -using xModels.Dtos; -using xCommons.Constants; -using xCommons.Extensions; - -namespace xHttpService.Extensions -{ - public static partial class RestSharpExtensions - { - /// - /// Attach an instance of XQuery to a RestRequest object - /// - /// - /// - /// - public static RestRequest AttachXQuery( - this RestRequest source, - XQuery query - ) - { - // - if (query.IsNull()) - { - return source; - } - - // - // ContainsDetail ... - // - var containsDetailKey = System.Uri.EscapeDataString(nameof(query.ContainsDetail)); - var containsDetailValue = query.ContainsDetail.AsHttpParamString(); - source.AddQueryParameter(containsDetailKey, containsDetailValue); - - // - // IsAscending ... - var isAscendingKey = System.Uri.EscapeDataString(nameof(query.IsAscending)); - var isAscendingValue = query.IsAscending.AsHttpParamString(); - source.AddQueryParameter(isAscendingKey, isAscendingValue); - - // - // Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - var key = System.Uri.EscapeDataString(nameof(query.Filter)); - var value = query.Filter.AsHttpParamString(); - source.AddQueryParameter(key, value); - } - - // - // SortBy ... - if (!query.SortBy.IsNullOrEmpty()) - { - // - var key = System.Uri.EscapeDataString(nameof(query.SortBy)); - var value = query.SortBy.AsHttpParamString(); - source.AddQueryParameter(key, value); - } - - // - // Page ... - if (query.Page > 0) - { - // - var key = System.Uri.EscapeDataString(nameof(query.Page)); - var value = query.Page.AsHttpParamString(); - source.AddQueryParameter(key, value); - } - - // - // PageSize ... - if (query.PageSize > 0) - { - // - var key = System.Uri.EscapeDataString(nameof(query.PageSize)); - var value = query.PageSize.AsHttpParamString(); - source.AddQueryParameter(key, value); - } - - // - return source; - } - - /// - /// Add Dest User to Query Strings ... - /// - /// - /// - /// - public static RestRequest AttachDestUser( - this RestRequest source, - string destUser - ) - { - // - if (destUser.IsNullOrEmpty()) - { - return source; - } - - // - var destUserKey = System.Uri.EscapeDataString(nameof(destUser)); - var destUserValue = destUser.AsHttpParamString(); - source.AddQueryParameter(destUserKey, destUserValue); - - // - return source; - } - - /// - /// Add XPoweredBy Header to specific RestRequest Headers ... - /// - /// - /// - /// - public static RestRequest AddXPoweredBy( - this RestRequest source, - string poweredByValue - ) - { - // - source.AddHeader( - XAuthorization.XPoweredBy, - poweredByValue - ); - - // - return source; - } - - /// - /// Add XAccessToken Header to specific RestRequest Headers ... - /// - /// - /// - /// - public static RestRequest AddXAccessToken( - this RestRequest source, - string token - ) - { - // - token = $"{XAuthentication.BEARER} {token}"; - - // - source.AddHeader( - XAuthorization.Header, - token - ); - - // - return source; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Extensions\XSseExtensions.cs - -using System; -using System.Text; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; - -namespace xHttpService.Extensions -{ - /// - /// Server-Sent Events (SSE) Helpers ... - /// Format (per Spec): [event: name\n] data: line\n ... \n - /// - public static class XSseExtensions - { - // - // Event Names ... - public const string SseDoneEvent = "done"; - public const string SseErrorEvent = "error"; - public const string SseContentType = "text/event-stream; charset=utf-8"; - - /// - /// Configure Response for SSE (Headers + Disable Buffering) ... - /// Must be Called before any Write ... - /// - /// - public static void PrepareSseResponse( - this HttpResponse source - ) - { - // - if (source.IsNull() || source.HasStarted) - { - return; - } - - // - source.StatusCode = StatusCodes.Status200OK; - source.ContentType = SseContentType; - source.Headers["Cache-Control"] = "no-cache, no-store"; - source.Headers["X-Accel-Buffering"] = "no"; - - // - // Disable Response Buffering ... - source.HttpContext.Features - .Get()? - .DisableResponseBuffering(); - } - - /// - /// Write an Object as JSON (camelCase) SSE Event ... - /// - public static Task WriteSseEventAsync( - this HttpResponse source, - T data, - string eventName = null, - CancellationToken cancellationToken = default - ) - { - // - var payload = data.IsNull() - ? "null" - : data.ToJSON(camelCase: true); - - // - return source.WriteSseRawAsync(payload, eventName, cancellationToken); - } - - /// - /// Write Raw Text as SSE Event (Multi Line Text is Split into Multiple data: Lines) ... - /// - public static async Task WriteSseRawAsync( - this HttpResponse source, - string payload, - string eventName = null, - CancellationToken cancellationToken = default - ) - { - // - var builder = new StringBuilder(); - if (!eventName.IsNullOrEmpty()) - { - builder.Append("event: ").Append(eventName).Append('\n'); - } - - // - var normalized = (payload ?? string.Empty) - .Replace("\r\n", "\n") - .Replace('\r', '\n'); - foreach (var line in normalized.Split('\n')) - { - builder.Append("data: ").Append(line).Append('\n'); - } - builder.Append('\n'); - - // - await source.WriteAsync(builder.ToString(), Encoding.UTF8, cancellationToken); - await source.Body.FlushAsync(cancellationToken); - } - - /// - /// Write Terminating "done" Event ... - /// - public static Task WriteSseDoneAsync( - this HttpResponse source, - CancellationToken cancellationToken = default - ) - { - return source.WriteSseRawAsync("[DONE]", SseDoneEvent, cancellationToken); - } - - /// - /// Write "error" Event (Never Throws; Used when Stream has Already Started) ... - /// - public static async Task WriteSseErrorAsync( - this HttpResponse source, - string message - ) - { - // - try - { - await source.WriteSseEventAsync( - data: new { error = message ?? "Stream Failed" }, - eventName: SseErrorEvent, - cancellationToken: CancellationToken.None - ); - } - catch - { - // Client Gone ... - } - } - - /// - /// Is Exception Caused by Client Disconnect / Cancellation ... - /// - public static bool IsClientCancellation( - this Exception source, - CancellationToken cancellationToken - ) - { - return source is OperationCanceledException && cancellationToken.IsCancellationRequested; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Interfaces\IXHttpProvider.cs - -using RestSharp; -using System.Net.Http; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xHttpService.Interfaces { - public partial interface IXHttpProvider { - HttpClient GetHttpClient (); - RestClient GetRestClient ( - string baseUrl = null, - string poweredByValue = null, - XTokenResponse tokens = null - ); - RestRequest GetRestRequet ( - string endpoint, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null - ); - Task RunRestRequest ( - RestClient client, - RestRequest request, - XHttpMethod method - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xHttpService\Providers\XHttpProvider.cs - -using System; -using RestSharp; -using xModels.Base; -using System.Net.Http; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xHttpService.Interfaces; -using RestSharp.Authenticators; -using System.Collections.Generic; -using xHttpService.Configurations; -using Microsoft.Extensions.Logging; - -namespace xHttpService.Providers { - public partial class XHttpProvider : XBaseClass, IXHttpProvider { - - private readonly XHttpServiceConfiguration configuration; - - public XHttpProvider ( - ILoggerFactory loggerFactory, - XHttpServiceConfiguration configuration - ) : base (loggerFactory) { - this.configuration = configuration; - } - - // - #region Actions ... - /// - /// Get an Instance of Http Client - /// - /// - public HttpClient GetHttpClient () { - // - HttpClient httpClient = null; - httpClient = new HttpClient (); - - // - if (configuration.DisableSSLCheck) { - // - var httpHandler = new HttpClientHandler (); - httpHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; - - // - httpClient = new HttpClient (httpHandler); - } - - // - // Set Timeout ... - httpClient.Timeout = TimeSpan - .FromSeconds (configuration.DefaultClientTimeout); - - // - return httpClient; - } - - /// - /// Get an Instance of RestClient - /// - /// - /// - /// - /// - public RestClient GetRestClient ( - string baseUrl = null, - string poweredByValue = null, - XTokenResponse tokens = null - ) { - // - var client = new RestClient (baseUrl); - - // - // Add XPowered By to Default Headers ... - if (!poweredByValue.IsNullOrEmpty ()) { - client.AddDefaultHeader (XAuthorization.XPoweredBy, poweredByValue); - } - - // - // Set Authenticator ... - if (!tokens.IsNull () && - !tokens.AccessToken.IsNullOrEmpty ()) { - client.Authenticator = new JwtAuthenticator (tokens.AccessToken); - } - - // - // Refresh Token ... - if (!tokens.IsNull () && - !tokens.RefreshToken.IsNullOrEmpty ()) { - client.AddDefaultHeader (XAuthorization.RefreshToken, tokens.RefreshToken); - } - - // - // ExpiresAt ... - if (!tokens.IsNull () && - tokens.ExpiresAt > 0) { - client.AddDefaultHeader (XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString ()); - } - - // - // Set Default Timeout ... - client.Timeout = configuration.DefaultClientTimeout; - - // - // SSL Validation Handler ... - if (configuration.DisableSSLCheck) { - client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; - } - - // - return client; - } - - /// - /// Get an Instance of RestRequest - /// - /// - /// - /// - /// - /// - public RestRequest GetRestRequet ( - string endpoint, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null - ) { - // - var url = endpoint.ToString (); - - // - // Add Route Payloads ... - if (!@params.IsNull () && @params.Count > 0) { - // - var enumerator = @params.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - - // - url = url.Replace (item.Key, item.Value.ToUrlEncoded ()); - } - } - - // - // Add Query Strings ... - if (!queryStrings.IsNull () && queryStrings.Count > 0) { - // - url = $"{url}?"; - var enumerator = queryStrings.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - - // - url += $"{item.Key}={item.Value.ToUrlEncoded ()}&"; - } - - // - // remove lates & ... - if (url.EndsWith ("&")) { - url = url.Substring (0, url.Length - 1); - } - } - - // - // Create request ... - var request = new RestRequest (url, DataFormat.Json); - - // - // Add Headers to request ... - if (!headers.IsNull () && headers.Count > 0) { - // - var enumerator = headers.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - request.AddHeader (item.Key, item.Value); - } - } - - // - return request; - } - - /// - /// Handle Call Specific Request and retrieve Response - /// - /// - /// - /// - /// - /// - public async Task RunRestRequest ( - RestClient client, - RestRequest request, - XHttpMethod method - ) { - // - var response = await Task.Run (() => { - // - IRestResponse resp = null; - - // - // Call Endpoint Service using Specified Method ... - switch (method) { - // - // Get ... - case XHttpMethod.GET: - resp = client.Get (request); - break; - - // - // Put ... - case XHttpMethod.PUT: - resp = client.Put (request); - break; - - // - // Post ... - case XHttpMethod.POST: - resp = client.Post (request); - break; - - // - // Delete ... - case XHttpMethod.DELETE: - resp = client.Delete (request); - break; - } - - // - if (!resp.IsSuccessful) { - // - // UnAuthorized ... - if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { - XException.NotAuthorized.Throw (); - } - - // - // NotFound ... - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) { - XException.NotFound.Throw (); - } - - // - // Timeout ... - if (!resp.ErrorMessage.IsNullOrEmpty () && - resp.ErrorMessage.Contains ("timed out")) { - XException.Timeout.Throw (); - } - - // - // ErrorMessage ... - if (!resp.ErrorMessage.IsNullOrEmpty ()) { - throw new Exception (resp.ErrorMessage); - } - - // - // Default Exception ... - XException.BadRequest.Throw (); - } - - // - var result = resp.Content.FromJSON (); - return result; - }); - - // - return response; - } - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xIdentityHelper-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xIdentityHelper-20261109_152621.txt deleted file mode 100644 index a197143..0000000 --- a/Documents/GeneratedContext/xDashboard-xIdentityHelper-20261109_152621.txt +++ /dev/null @@ -1,4316 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\XApiScopeHelper.cs - -using xExceptions.Attributes; - -namespace xIdentityHelper { - public static class XApiScopeHelper { - public partial struct XApiScopes { - public const string Read = "XAPI.read"; - public const string Write = "XAPI.write"; - public const string Admin = "XAPI.admin"; - public const string Manage = "manage"; - } - - public enum XApiScope { - [StringValue ("XAPI.read")] - Read, - - [StringValue ("XAPI.write")] - Write, - - [StringValue ("XAPI.admin")] - Admin, - - [StringValue ("manage")] - Manage, - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\XAuthorizationHelper.cs - -using IdentityModel; -using xCommons.Constants; -using xCommons.Extensions; -using xCommons.Authorization; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using static xIdentityHelper.XApiScopeHelper; - -namespace xIdentityHelper -{ - public class XAuthorizationHelper - { - public static IDictionary GetXAuthorizationPolicies() - { - // - var result = new Dictionary(); - - // - RequiredRolesRequirement roleRequirements = null; - - // - #region Build Policies ... - // - // Scope Policies ... - #region Scope Policies ... - // - // Read Scope ... - result.Add(XPolicies.ReadAccess, - new AuthorizationPolicyBuilder() - .RequireClaim(JwtClaimTypes.Scope, XApiScopes.Read) - .Build() - ); - - // - // Write Scope ... - result.Add(XPolicies.WriteAccess, - new AuthorizationPolicyBuilder() - .RequireClaim( - JwtClaimTypes.Scope, - XApiScopes.Read, - XApiScopes.Write - ) - .Build() - ); - - // - // Admin Scope ... - result.Add(XPolicies.AdminAccess, - new AuthorizationPolicyBuilder() - .RequireClaim( - JwtClaimTypes.Scope, - XApiScopes.Read, - XApiScopes.Write, - XApiScopes.Admin - ) - .Build() - ); - - // - // Manage Scope ... - result.Add(XPolicies.ManageAccess, - new AuthorizationPolicyBuilder() - .RequireClaim( - JwtClaimTypes.Scope, - XApiScopes.Read, - XApiScopes.Write, - XApiScopes.Admin, - XApiScopes.Manage - ) - .Build() - ); - #endregion - - // - // Roles Policies ... - #region Roles Policies ... - // - // User ... - #region User Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.USER, - XUserRoles.AGENT, - XUserRoles.REPORTER_ASSISTANT, - XUserRoles.REPORTER, - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // User Policy ... - result.Add(XPolicies.User, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled User Policy ... - result.Add(XPolicies.EnabledUser, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // Agent ... - #region Agent Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.AGENT, - XUserRoles.REPORTER_ASSISTANT, - XUserRoles.REPORTER, - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // Agent Policy ... - result.Add(XPolicies.Agent, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled Agent Policy ... - result.Add(XPolicies.EnabledAgent, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // ReporterAssistant ... - #region Reporter Assistant Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.REPORTER_ASSISTANT, - XUserRoles.REPORTER, - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // ReporterAssistant ... - result.Add(XPolicies.ReporterAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled ReporterAssistant ... - result.Add(XPolicies.EnabledReporterAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // Reporter ... - #region Reporter Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.REPORTER, - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // Reporter ... - result.Add(XPolicies.Reporter, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled Reporter ... - result.Add(XPolicies.EnabledReporter, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // ActuaryAssistant ... - #region Actuary Assistant Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // ActuaryAssistant ... - result.Add(XPolicies.ActuaryAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled ActuaryAssistant ... - result.Add(XPolicies.EnabledActuaryAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // Actuary ... - #region Actuary Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.ACTUARY, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // Actuary ... - result.Add(XPolicies.Actuary, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled Actuary ... - result.Add(XPolicies.EnabledActuary, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // ChiefClerkAssistant ... - #region Chief Clerk Assistant Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // ChiefClerkAssistant ... - result.Add(XPolicies.ChiefClerkAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled ChiefClerkAssistant ... - result.Add(XPolicies.EnabledChiefClerkAssistant, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // ChiefClerk ... - #region Chief Clerk Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.CHIEF_CLERK, - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // ChiefClerk ... - result.Add(XPolicies.ChiefClerk, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled ChiefClerk ... - result.Add(XPolicies.EnabledChiefClerk, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // Journalist ... - #region Journalist Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.JOURNALIST, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // Journalist ... - result.Add(XPolicies.Journalist, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled Journalist ... - result.Add(XPolicies.EnabledJournalist, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // ResponsibleManager ... - #region Responsible Manager Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.ADMIN - ); - - // - // ResponsibleManager ... - result.Add(XPolicies.ResponsibleManager, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled ResponsibleManager ... - result.Add(XPolicies.EnabledResponsibleManager, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - - // - // Admin ... - #region Admin Related Policies ... - // - roleRequirements = new RequiredRolesRequirement( - XUserRoles.ADMIN - ); - - // - // Admin Policy ... - result.Add(XPolicies.Admin, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .Build() - ); - - // - // Enabled Admin Policy ... - result.Add(XPolicies.EnabledAdmin, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(roleRequirements) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - #endregion - - // - // Complex Policies ... - #region AdminOrAgent Related Policies ... - // - // Admin Or Agent Policy ... - result.Add(XPolicies.AdminOrAgent, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(new RequiredRolesRequirement( - XUserRoles.ADMIN, - XUserRoles.AGENT - )) - .Build() - ); - - // - // Enabled Admin Or Agent Policy ... - result.Add(XPolicies.EnabledAdminOrAgent, - new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .AddRequirements(new RequiredRolesRequirement( - XUserRoles.ADMIN, - XUserRoles.AGENT - )) - .RequireClaim( - XCustomClaims.IsBanned, - false.ToString(), - false.ToString() - .ToNormalString() - ) - .RequireClaim( - XCustomClaims.IsEnabled, - true.ToString(), - true.ToString() - .ToNormalString() - ) - .Build() - ); - #endregion - #endregion - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\XPolicies.cs - -namespace xIdentityHelper -{ - public partial struct XPolicies - { - // - // Scopes ... - public const string ReadAccess = "readScopePolicy"; - public const string WriteAccess = "writeScopePolicy"; - public const string AdminAccess = "adminScopePolicy"; - public const string ManageAccess = "manageScopePolicy"; - // - // Api Keys ... - public const string ApiKeyAccess = "apiKeyAccessPolicy"; - public const string ApiKeyReadAccess = "apiKeyReadAccessPolicy"; - public const string ApiKeyWriteAccess = "apiKeyWriteAccessPolicy"; - public const string ApiKeyAdminAccess = "apiKeyAdminAccessPolicy"; - public const string ApiKeyManageAccess = "apiKeyManageAccessPolicy"; - // - // Admin ... - public const string Admin = "adminPolicy"; - public const string EnabledAdmin = "enabledAdminPolicy"; - // - // Responsible Manager ... - public const string ResponsibleManager = "responsibleManagerPolicy"; - public const string EnabledResponsibleManager = "enabledResponsibleManagerPolicy"; - // - // Journalist ... - public const string Journalist = "journalistPolicy"; - public const string EnabledJournalist = "enabledJournalistPolicy"; - // - // Chief Clerk ... - public const string ChiefClerk = "chiefClerkPolicy"; - public const string EnabledChiefClerk = "enabledChiefClerkPolicy"; - // - // Chief Clerk Assistant ... - public const string ChiefClerkAssistant = "chiefClerkAssistantPolicy"; - public const string EnabledChiefClerkAssistant = "enabledChiefClerkAssistantPolicy"; - // - // Actuary ... - public const string Actuary = "actuaryPolicy"; - public const string EnabledActuary = "enabledActuaryPolicy"; - // - // Actuary Assistant ... - public const string ActuaryAssistant = "actuaryAssistantPolicy"; - public const string EnabledActuaryAssistant = "enabledActuaryAssistantPolicy"; - // - // Reporter ... - public const string Reporter = "reporterPolicy"; - public const string EnabledReporter = "enabledReporterPolicy"; - // - // Reporter Assistant ... - public const string ReporterAssistant = "reporterAssistantPolicy"; - public const string EnabledReporterAssistant = "enabledReporterAssistantPolicy"; - // - // Agent ... - public const string Agent = "agentPolicy"; - public const string EnabledAgent = "enabledAgentPolicy"; - // - // User ... - public const string User = "userPolicy"; - public const string EnabledUser = "enabledUserPolicy"; - // - // Complex Policies ... - public const string AdminOrAgent = "adminOrAgentPolicy"; - public const string EnabledAdminOrAgent = "enabledAdminOrAgentPolicy"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\XUserRoles.cs - -using xExceptions.Attributes; -using System.Collections.Generic; - -namespace xIdentityHelper -{ - public partial struct XUserRoles - { - /// - /// Must Top Role of System ... - /// - public const string ADMIN = "admin"; - - /// - /// مدیر مسئول - /// - public const string RESPONSIBLE_MANAGER = "responsible_manager"; - - /// - /// روزنامه نگار - /// - public const string JOURNALIST = "journalist"; - - /// - /// سر دبیر - /// - public const string CHIEF_CLERK = "chief_clerk"; - - /// - /// دستیار سرد بیر - /// - public const string CHIEF_CLERK_ASSISTANT = "chief_clerk_assistant"; - - /// - /// دبیر - /// - public const string ACTUARY = "actuary"; - - /// - /// دستیار دبیر - /// - public const string ACTUARY_ASSISTANT = "actuary_assistant"; - - /// - /// خبرنگار - /// - public const string REPORTER = "reporter"; - - /// - /// دستیار خبرنگار - /// - public const string REPORTER_ASSISTANT = "reporter_assistant"; - - /// - /// دستیار - /// - public const string AGENT = "agent"; - - /// - /// کاربر - /// - public const string USER = "user"; - } - - public enum XUserRole - { - /// - /// Must Top Role of System ... - /// - [StringValue("admin")] - Admin = 10, - - /// - /// مدیر مسئول - /// - [StringValue("responsible_manager")] - ResponsibleManager = 9, - - /// - /// روزنامه نگار - /// - [StringValue("journalist")] - Journalist = 8, - - /// - /// سر دبیر - /// - [StringValue("chief_clerk")] - ChiefClerk = 7, - - /// - /// دستیار سرد بیر - /// - [StringValue("chief_clerk_assistant")] - ChiefClerkAssistant = 6, - - /// - /// دبیر - /// - [StringValue("actuary")] - Actuary = 5, - - /// - /// دستیار دبیر - /// - [StringValue("actuary_assistant")] - ActuaryAssistant = 4, - - /// - /// خبرنگار - /// - [StringValue("reporter")] - Reporter = 3, - - /// - /// دستیار خبرنگار - /// - [StringValue("reporter_assistant")] - ReporterAssistant = 2, - - /// - /// دستیار - /// - [StringValue("agent")] - Agent = 1, - - /// - /// کاربر - /// - [StringValue("user")] - User = 0 - } - - public static class XUserRoleHelper - { - public static List GetAllRoles() - { - // - var result = new List - { - XUserRoles.ADMIN, - XUserRoles.RESPONSIBLE_MANAGER, - XUserRoles.JOURNALIST, - XUserRoles.CHIEF_CLERK, - XUserRoles.CHIEF_CLERK_ASSISTANT, - XUserRoles.ACTUARY, - XUserRoles.ACTUARY_ASSISTANT, - XUserRoles.REPORTER, - XUserRoles.REPORTER_ASSISTANT, - XUserRoles.AGENT, - XUserRoles.USER - }; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\Controllers\XAccountControllerBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Attributes; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityModels.Navigations; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using static xIdentityHelper.XApiScopeHelper; - -namespace xIdentityHelper.Controllers -{ - public abstract class XAccountControllerBase : XBaseAccountController - { - protected XAccountControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider IdentityProvider, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, IdentityProvider, validationProvider) - { } - - // - #region Authentication Actions ... - /// - /// Logout User - /// - [RequireXPowered] - [HttpPost("Logout")] - [Authorize(Policy = XPolicies.User)] - public virtual async Task Logout() - { - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - await IdentityProvider - .Logout(tokens); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Validate a Revision Checksum - /// - /// - /// - [HttpPost("Validate")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> Validate( - [FromBody] XValidateRevisionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.Revision) - .ValidateGroupAsync(); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = tokens.ValidateRevisionChecksum( - model.Revision, - IdentityProvider.RevisionSecretKey - ); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Request AccessToken for Specific XApiScope - /// - /// a member of XApiScope - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestScopeAccessToken")] - public virtual async Task> RequestScopeAccessToken ( - [FromHeader] XApiScope scope - ) { - // - // Do Action ... - try { - // - // Validate Args ... - var scopeName = string.Empty; - try { - scopeName = scope.GetStringValue (); - } catch { } - ValidationProvider.NotEmpty (scopeName); - - // - var result = await IdentityProvider - .RequestScopeAccessToken (scopeName); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - return result; - } - } - #endregion - - // - #region Password Actions ... - /// - /// Change a User's Password ... - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - NewPassword: user's new password to change. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "" - /// "newPassword": "", - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [RequireXPowered] - [HttpPost("ChangePassword")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task ChangePassword( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull( - model, - model.Device - ) - .AddNotEmpty( - model.Lang, - model.Password, - model.NewPassword, - model.ReturnUrl - ) - .ValidateGroupAsync(); - - // - // Get User Select By ... - var userSelectByParam = GetUserSelectByParam( - model, - forceNotNull: false - ); - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - await IdentityProvider - .ChangePassword(tokens, model); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Admin Actions ... - /// - /// Ban Specific Users - /// - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of banned users identifiers - [RequireXPowered] - [HttpPost("Ban")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public virtual async Task>> Ban( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotZeroChilds(model.Ids) - .ValidateGroupAsync(); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .Ban( - tokens, - model - ); - - // - return Ok(result) - .ToDynamicObject(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// UnBann Specific Users - /// - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of unbanned users identifiers - [RequireXPowered] - [HttpPost("UnBan")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public virtual async Task>> UnBan( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotZeroChilds(model.Ids) - .ValidateGroupAsync(); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .UnBan( - tokens, - model - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Check Specific User is Banned or not - /// - /// specified user's identifier - /// a boolean value which represent user banned or not - [RequireXPowered] - [HttpGet("IsBanned/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [Authorize(Policy = XPolicies.EnabledAgent)] - public virtual async Task> IsBanned( - [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .IsBanned( - tokens, - userSelectByParam - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Friendship Actions ... - /// - /// Follow a User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [RequireXPowered] - [HttpPost("Friendship/{destUser}/Follow")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> Follow( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .Follow( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Cancel Following Request - /// - /// a user identifier which represent destination user - /// a boolean value - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/Cancel")] - public virtual async Task> Cancel( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .Cancel( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Unfollow a Follower - /// - /// a user identifier which represent destination user - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/UnFollowFollower")] - public virtual async Task UnFollowFollower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - await IdentityProvider - .UnFollowFollower( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Unfollow Following - /// - /// a user identifier which represent destination user - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/UnFollowFollowing")] - public virtual async Task UnFollowFollowing( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - await IdentityProvider - .UnFollowFollowing( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Block a Follower - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [RequireXPowered] - [HttpPost("Friendship/{destUser}/Block")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> Block( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .Block( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - - /// - /// Unblock a Blocked User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [RequireXPowered] - [HttpPost("Friendship/{destUser}/UnBlock")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> UnBlock( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .UnBlock( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Accept a Following Request - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/AcceptRequest")] - public virtual async Task> AcceptRequest( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .AcceptRequest( - tokens, - destUser - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Reject a Following Request - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/RejectRequest")] - public virtual async Task> RejectRequest( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .RejectRequest( - tokens, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Friendship Getters ... - /// - /// Get Friendship Info Model between Specific User and Current User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipInfoDto - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/FriendshipInfo")] - public virtual async Task> FriendshipInfo( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFriendshipInfo( - tokens, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Check a User IsFollower of Requested User - /// - /// a user identifier which represent destination user - /// a boolean value - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/IsFollower")] - public virtual async Task> IsFollower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .IsFollower( - tokens, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Follower State of a User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipState - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/FollowerState")] - public virtual async Task> FollowerState( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowerState( - tokens, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Specific Follower - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/Follower")] - public virtual async Task> Follower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollower( - tokens, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Followers List Of Current User - /// - /// a collection of XFriendshipFollower - [RequireXPowered] - [HttpGet("Friendship/Followers")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> Followers() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowers(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - - /// - /// Get All Followers List Includes Blocked, Requested and etc - /// of Current User - /// - /// a collection of XFriendshipFollower - [RequireXPowered] - [HttpGet("Friendship/AllFollowers")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> AllFollowers() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetAllFollowers(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Followers List Includes Blocked, Requested and etc - /// of Current User based On Query Model ... - /// - /// a Query Result of XFriendDto - [RequireXPowered] - [HttpGet("Friendship/QueryFollowers")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryFollowers( - [FromQuery] XQuery query, - [FromQuery] string destUser - ) - { - // - // Do Action ... - try - { - // - // Normalizing Dest User ... - var userInfo = await GetUserInfo(); - bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN); - if (destUser.IsNullOrEmpty()) - { - destUser = userInfo.UserName; - } - bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName; - if (!isDestUserValid) - { - XException.NotAllowed.Throw(); - } - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .QueryFollowers( - query: query, - tokens: tokens, - destUser: destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Check a User is in Followings of Current User - /// - /// a user identifier which represent destination user - /// a boolean value - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/IsFollowing")] - public virtual async Task> IsFollowing( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .IsFollowing( - tokens, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Following State Relation between Specific User - /// and Current User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipState - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/FollowingState")] - public virtual async Task> FollowingState( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowingState( - tokens, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Specific Following Model - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/Following")] - public virtual async Task> Following( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowing( - tokens, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Followings of Current User - /// - /// a collection of XFriendshipFollowing - [RequireXPowered] - [HttpGet("Friendship/Followings")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> Followings() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowings(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Following List Includes Blocked, Requested and etc - /// of Current User - /// - /// a collection of XFriendshipFollowing - [RequireXPowered] - [HttpGet("Friendship/AllFollowings")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> AllFollowings() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetAllFollowings(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Return Following UserName's List of Current User - /// - /// a collection of UserNames - [RequireXPowered] - [HttpGet("Friendship/FollowingsList")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> FollowingsList() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowingList(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Return Followers UserName's List of Current User - /// - /// a collection of UserNames - [RequireXPowered] - [HttpGet("Friendship/FollowersList")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> FollowersList() - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetFollowersList(tokens); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Followings List Includes Blocked, Requested and etc - /// of Current User based On Query Model ... - /// - /// a Query Result of XFriendDto - [RequireXPowered] - [HttpGet("Friendship/QueryFollowings")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryFollowings( - [FromQuery] XQuery query, - [FromQuery] string destUser - ) - { - // - // Do Action ... - try - { - // - // Normalizing Dest User ... - var userInfo = await GetUserInfo(); - bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN); - if (destUser.IsNullOrEmpty()) - { - destUser = userInfo.UserName; - } - bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName; - if (!isDestUserValid) - { - XException.NotAllowed.Throw(); - } - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .QueryFollowings( - query: query, - tokens: tokens, - destUser: destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Profile Actions ... - // - #region Retrieve Actions ... - /// - /// Retrieve User Names based on UserIds - /// - /// a comma seperated list of UserIds - /// a collection of UserNames - [RequireXPowered] - [HttpGet("Profile/{ids}/GetNames")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetNames( - [FromRoute] string ids - ) - { - // - // Do Action ... - try - { - // - ValidationProvider.NotEmpty(ids); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetUserNames( - tokens, - ids - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// get user ids and retrieve corresponding user names - /// - /// an instance of XUserNameIdRequest which represent required UserIds collection - /// a collection of XUserNameIdResponse instance - [RequireXPowered] - [HttpPost("Profile/GetNameIds")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetNameIds( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - ValidationProvider.NotNull(model); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetUserNameIds( - tokens, - model - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Profile Object of Specific User - /// - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [HttpGet("Profile/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> GetProfile( - [FromRoute] string userSelectByParam = "" - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .GetUserProfile( - tokens, - userSelectByParam - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Users - /// for specifiy users role for query user 'role: string' and 'forceRole: boolean' in header - /// - /// how to filter results based on XQuery structure - /// an string which represent user role - /// if it's true the user must has exact role, otherwise top level users also listed - /// an instance of XQueryResult of XUserProfileDto - [RequireXPowered] - [HttpGet("Profile/Query")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [Authorize(Policy = XPolicies.EnabledAgent)] - public virtual async Task>> QueryProfiles( - [FromQuery] XQuery query, [FromHeader] string role, [FromHeader] bool forceRole = false - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = new XQueryResult(); - if (role.IsNullOrEmpty()) - { - // - result = await IdentityProvider.QueryUsers( - tokens, - query - ); - } - else - { - // - result = await IdentityProvider.QueryInRoleUsers( - tokens, - role, - query, - forceRole - ); - } - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Query Specified User's Profile Images - /// - /// determine's which user profile must be retrieved - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XProfileImage - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [HttpGet("Profile/Avatars/Query/{userSelectByParam?}")] - public virtual async Task>> QueryAvatars( - [FromQuery] XQuery query, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.QueryAvatars( - tokens, - userSelectByParam, - query - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region Update Actions ... - /// - /// Update User Profile based on XProfileUpdateRequest (FirstName/LastName/DateOfBirth) - /// - /// user update info, an instance of XProfileUpdateRequest - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Profile/Update/{userSelectByParam?}")] - public virtual async Task> UpdateProfile( - [FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.ProfileUpdateAsync( - tokens, - userSelectByParam, - model - ); - - // - // Prepare Push Message ... - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a User Profile based on XProfileUpdateRequest Full - /// - /// user update info, an instance of XProfileUpdateRequest - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledAdminOrAgent)] - public virtual async Task> FullUpdateProfile( - [FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.FullProfileUpdateAsync( - tokens, - userSelectByParam, - model - ); - - // - // Prepare Push Message ... - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Avatar Actions ... - /// - /// Add a New Profile Image - /// - /// an specific File to upload, IFormFile - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatar")] - [RequestSizeLimit(966_367_641)] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AddAvatar( - [FromForm] IFormFile file - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotNull(file); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .AddAvatar( - tokens, - file - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Add a New Collection of Profile Images - /// - /// a collection of Files to upload, IFormFileCollection - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatars")] - [RequestSizeLimit(966_367_641)] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AddAvatars( - [FromForm] IFormFileCollection files - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotZeroChilds(files); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.AddAvatars( - tokens, - files - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// set Specified Profile Image as Avatar - /// - /// an integer which reperesent AvatarId to set as current Avatar - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatars/{id:int}/Set")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> SetAvatar( - [FromRoute] int id - ) - { - // - // Do Action ... - try - { - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .SetAvatar( - tokens, - id - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Remove Profile Images - /// - /// a comma seperated list of avatarIds to remove - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [HttpDelete("Profile/Avatars/{ids}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> RemoveAvatars( - [FromRoute] string ids - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(ids); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider - .RemoveAvatars( - tokens, - ids - ); - - // - // Prepare Push Message ... - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - - // - #region Registration ... - /// - /// Invite a User to Register on Dashboard - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Email: which email address is going to invite. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Registration URL. - /// notice in this step you had to provide all this informations as FormData - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "email": "", - /// "returnUrl": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [RequireXPowered] - [HttpPost ("InviteUser")] - [Authorize (Policy = XPolicies.EnabledAdmin)] - [Authorize (Policy = XPolicies.EnabledAgent)] - public virtual async Task> InviteUser ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - - // - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Email, - model.ReturnUrl) - .AddEmailAddress (model.Email) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - var tokens = await RetrieveTokensAsXTokenResponse (); - var result = await IdentityProvider - .InviteUser ( - tokens, - model - ); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - return result; - } - } - - /// - /// Check User is Confirmed Email or not - /// - /// a boolean value - [RequireXPowered] - [HttpGet ("IsConfirmedEmail")] - [Authorize (Policy = XPolicies.User)] - public virtual async Task> IsConfirmedEmail () { - // - // Do Action ... - try { - // - // Get Result ... - var tokens = await RetrieveTokensAsXTokenResponse (); - var result = await IdentityProvider - .IsConfirmedEmail ( - tokens, - User.Identity.Name - ); - - // - // Return Result - return Ok (result); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - - // - return result; - } - } - - /// - /// Check User is Confirmed Mobile or not - /// - /// a boolean value - [RequireXPowered] - [HttpGet ("IsConfirmedMobile")] - [Authorize (Policy = XPolicies.User)] - public virtual async Task> IsConfirmedMobile () { - // - // Do Action ... - try { - // - // Get Result ... - var tokens = await RetrieveTokensAsXTokenResponse (); - var result = await IdentityProvider - .IsConfirmedMobile ( - tokens, - User.Identity.Name - ); - - // - // Return Result - return Ok (result); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - - // - return result; - } - } - #endregion - - // - #region Search ... - /// - /// Query Open To Search Users Profiles ... - /// Query all Users Which their Profiles is Open To Search ... - /// - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - [RequireXPowered] - [HttpGet("OpenToSearch/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryOpenToSearchProfiles( - [FromQuery] XQuery query - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.QueryOpenToSearchUsers( - tokens, - query - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region Applications ... - // - #region Application ... - /// - /// Create Application ... - /// - /// - /// Sample request: - /// - /// { - /// "type": 0, - /// "name": "string", - /// "description": "string", - /// } - /// - /// - /// - /// - /// - [RequireXPowered] - [HttpPost("Applications")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> CreateApplication( - [FromBody] XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.CreateApplication( - item: item, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Update Specified Application ... - /// - /// - /// Sample request: - /// - /// { - /// "id": 0, - /// "type": 0, - /// "name": "string", - /// "description": "string", - /// } - /// - /// - /// - /// - /// - /// - [RequireXPowered] - [HttpPut("Applications/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> UpdateApplication( - [FromRoute] int id, - [FromBody] XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.UpdateApplication( - id: id, - item: item, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Remove Specified Application ... - /// - /// - /// - /// - [RequireXPowered] - [HttpDelete("Applications/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> RemoveApplication( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RemoveApplication( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Get Specified Application ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> GetApplication( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetApplication( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Get All Application ... - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetAllApplications( - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetAllApplications( - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Query Applications ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryApplications( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.QueryApplications( - query: query, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region ApiKey ... - /// - /// Get Specified ApiKey ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/ApiKeys/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> GetApiKey( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetApiKey( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Remove Specified ApiKey ... - /// - /// - /// - /// - [RequireXPowered] - [HttpDelete("Applications/ApiKeys/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> RemoveApiKey( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RemoveApiKey( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Update Specified ApiKey ... - /// - /// - /// - /// - /// - [RequireXPowered] - [HttpPut("Applications/ApiKeys/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> UpdateApiKey( - [FromRoute] Guid id, - [FromBody] XApiKeyDto item, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.UpdateApiKey( - id: id, - item: item, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Get All Specified ApiKeys ... - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/ApiKeys")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetAllApiKeys( - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetAllApiKeys( - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Query ApiKeys ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/ApiKeys/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> QueryApiKeys( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.QueryApiKeys( - query: query, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region ApiKeyUsage ... - /// - /// Add Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [HttpPost("Applications/ApiKeys/Usages")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task> AddApiKeyUsage( - [FromBody] XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.AddApiKeyUsage( - item: item, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Get Specified Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Applications/ApiKeys/Usages/{id}")] - public virtual async Task> GetApiKeyUsage( - [FromRoute] long id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetApiKeyUsage( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Remove Specified Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpDelete("Applications/ApiKeys/Usages/{id}")] - public virtual async Task> RemoveApiKeyUsage( - [FromRoute] long id, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RemoveApiKeyUsage( - id: id, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Update Specified Api Key Usage ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPut("Applications/ApiKeys/Usages/{id}")] - public virtual async Task> UpdateApiKeyUsage( - [FromRoute] long id, - [FromBody] XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.UpdateApiKeyUsage( - id: id, - item: item, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Get All Api Key Usages ... - /// - /// - /// - [RequireXPowered] - [HttpGet("Applications/ApiKeys/Usages")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual async Task>> GetAllApiKeyUsages( - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetAllApiKeyUsages( - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Query Api Key Usages ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Applications/ApiKeys/Usages/Query")] - public virtual async Task>> QueryApiKeyUsages( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.QueryApiKeyUsages( - query: query, - tokens: tokens, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region Custom ... - /// - /// Show Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Applications/{applicationId}/ApiKeys/{apiKeyId}/Show")] - public virtual async Task> ShowApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.ShowApiKey( - tokens: tokens, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Create Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Applications/{applicationId}/ApiKeys/Create")] - public virtual async Task> CreateApiKey( - [FromRoute] int applicationId, - [FromBody] XCreateApiKeyRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.CreateApiKey( - tokens: tokens, - request: request, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Remove Specified Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpDelete("Applications/{applicationId}/ApiKeys/{apiKeyId}")] - public virtual async Task> RemoveApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RemoveApiKey( - tokens: tokens, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Rotate Specified Api Key ... - /// - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}")] - public virtual async Task> RotateApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - [FromBody] XRotateApiKeyRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RotateApiKey( - tokens: tokens, - request: request, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}/Revoke")] - public virtual async Task> RevokeApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.RevokeApiKey( - tokens: tokens, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Retrieve Specified Application's Api Keys ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Applications/{applicationId}/ApiKeys")] - public virtual async Task>> GetApiKeys( - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetApiKeys( - tokens: tokens, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Retrieve Specified Api Keys Usages ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Applications/{applicationId}/ApiKeys/{apiKeyId}/Usages")] - public virtual async Task>> GetApiKeyUsages( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var tokens = await RetrieveTokensAsXTokenResponse(); - var result = await IdentityProvider.GetApiKeyUsages( - tokens: tokens, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Validate Specifed Api Key ... - /// - /// - /// - /// - [RequireXPowered] - [HttpPost("Applications/ApiKeys/Validate")] - public virtual async Task> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default - ) - { - // - // Do Action ... - try - { - // - var result = await IdentityProvider.ValidateApiKey( - request: request, - cancellationToken: cancellationToken - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\Controllers\XTestIdentityControllerBase.cs - -using System.Linq; -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; - -namespace xIdentityHelper.Controllers -{ - public abstract class XTestIdentityControllerBase : XBaseTestIdentityController - { - protected XTestIdentityControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { } - - // - #region Identity Actions ... - /// - /// API Read Scope ... - /// - /// string message - [RequireXPowered] - [HttpGet("PassReadAccess")] - [Authorize(Policy = XPolicies.ReadAccess)] - public virtual ActionResult PassReadAccess() - { - return Ok("Read Access Passed ..."); - } - - /// - /// API Write Scope ... - /// - /// string message - [RequireXPowered] - [HttpGet("PassWriteAccess")] - [Authorize(Policy = XPolicies.WriteAccess)] - public virtual ActionResult PassWriteAccess() - { - return Ok("Write Access Passed ..."); - } - - /// - /// API Admin Scope ... - /// - /// string message - [RequireXPowered] - [HttpGet("PassAdminAccess")] - [Authorize(Policy = XPolicies.AdminAccess)] - public virtual ActionResult PassAdminAccess() - { - return Ok("Admin Access Passed ..."); - } - - /// - /// API Manage Scope ... - /// - /// string message - [RequireXPowered] - [HttpGet("PassManageAccess")] - [Authorize(Policy = XPolicies.ManageAccess)] - public virtual ActionResult PassManageAccess() - { - return Ok("Manage Access Passed ..."); - } - - /// - /// a simple Action which returns a List of Authenticated User Claims ... - /// - /// string message which represent current user's claims - [RequireXPowered] - [HttpGet("HiClaims")] - [Authorize(Policy = XPolicies.User)] - public virtual ActionResult HiClaims() - { - // - var result = new - { - name = User.Identity.Name, - claims = User.Claims.Select(c => new - { - c.Type, - c.Value - }) - }; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiUser")] - [Authorize(Policy = XPolicies.User)] - public virtual ActionResult HiUser() - { - // - var result = $"Hi User: {User.Identity.Name} ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiEnabledUser")] - [Authorize(Policy = XPolicies.EnabledUser)] - public virtual ActionResult HiEnabledUser() - { - // - var result = $"Hi User: {User.Identity.Name} is Enabled ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiAgent")] - [Authorize(Policy = XPolicies.Agent)] - public virtual ActionResult HiAgent() - { - // - var result = $"Hi Agent: {User.Identity.Name} ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiEnabledAgent")] - [Authorize(Policy = XPolicies.EnabledAgent)] - public virtual ActionResult HiEnabledAgent() - { - // - var result = $"Hi Agent: {User.Identity.Name} is Enabled ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiAdmin")] - [Authorize(Policy = XPolicies.Admin)] - public virtual ActionResult HiAdmin() - { - // - var result = $"Hi Admin: {User.Identity.Name} ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("HiEnabledAdmin")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public virtual ActionResult HiEnabledAdmin() - { - // - var result = $"Hi Admin: {User.Identity.Name} is Enabled ..."; - - // - return Ok(result); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\Extensions\XIdentityHelperExtensions.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xIdentityModels.Models; - -namespace xIdentityHelper.Extensions -{ - public static class XIdentityHelperExtensions - { - /// - /// Check User Claims ia Admin Role or not ... - /// - /// - /// - public static bool IsAdmin(this XUserClaimsInfoDto source) - { - // - var result = false; - - // - if (source.IsNull() || - source.Roles.IsNull() || - !source.Roles.HasChild()) - { - return result; - } - - // - result = source.Roles.Contains(XUserRoles.ADMIN); - - // - return result; - } - - /// - /// Check Actor is Valid for UserSelectByParam or not ... - /// - /// - /// - /// - public static bool IsValidActor(this XUserClaimsInfoDto source, string userSelectByParam) - { - // - var result = false; - - // - if (source.IsNull() || - userSelectByParam.IsNullOrEmpty()) - { - return result; - } - - // - bool isAdmin = source.IsAdmin(); - result = isAdmin || - userSelectByParam == source.Email || - userSelectByParam == source.UserId || - userSelectByParam == source.UserName || - userSelectByParam == source.PhoneNumber; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityHelper\Extensions\XUserRoleExtensions.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Collections.Generic; - -namespace xIdentityHelper.Extensions -{ - public static class XUserRoleExtensions - { - /// - /// Converts an String to XUserRole ... - /// - /// - /// - public static XUserRole ToXUserRole(this string role) - { - // - var result = XUserRole.User; - - // - // Validate ... - if (role.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var roles = new List - { - role - }; - result = roles.GetTopRole(); - - // - return result; - } - - /// - /// Retrieve User Top Role based on Role Lists ... - /// - /// - /// - public static XUserRole GetTopRole(this IEnumerable roles) - { - // - // Validate ... - if (roles.IsNull() || !roles.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize Roles ... - roles = roles.Select(r => r.ToNormalString()); - - // - var result = XUserRole.User; - - // - // Admin ... - if (roles.Contains(XUserRole.Admin.GetStringValue().ToNormalString())) - { - result = XUserRole.Admin; - } - // - // ResponsibleManager ... - else if (roles.Contains(XUserRole.ResponsibleManager.GetStringValue().ToNormalString())) - { - result = XUserRole.ResponsibleManager; - } - // - // Journalist ... - else if (roles.Contains(XUserRole.Journalist.GetStringValue().ToNormalString())) - { - result = XUserRole.Journalist; - } - // - // ChiefClerk ... - else if (roles.Contains(XUserRole.ChiefClerk.GetStringValue().ToNormalString())) - { - result = XUserRole.ChiefClerk; - } - // - // ChiefClerkAssistant ... - else if (roles.Contains(XUserRole.ChiefClerkAssistant.GetStringValue().ToNormalString())) - { - result = XUserRole.ChiefClerkAssistant; - } - // - // Actuary ... - else if (roles.Contains(XUserRole.Actuary.GetStringValue().ToNormalString())) - { - result = XUserRole.Actuary; - } - // - // ActuaryAssistant ... - else if (roles.Contains(XUserRole.ActuaryAssistant.GetStringValue().ToNormalString())) - { - result = XUserRole.ActuaryAssistant; - } - // - // Reporter ... - else if (roles.Contains(XUserRole.Reporter.GetStringValue().ToNormalString())) - { - result = XUserRole.Reporter; - } - // - // ReporterAssistant ... - else if (roles.Contains(XUserRole.ReporterAssistant.GetStringValue().ToNormalString())) - { - result = XUserRole.ReporterAssistant; - } - // - // Agent ... - else if (roles.Contains(XUserRole.Agent.GetStringValue().ToNormalString())) - { - result = XUserRole.Agent; - } - // - // User ... - else if (roles.Contains(XUserRole.User.GetStringValue().ToNormalString())) - { - result = XUserRole.User; - } - else - { - XException.InvalidData.Throw(); - } - - // - return result; - } - - /// - /// Check User Roles has Specified Permissions or not ... - /// - /// - /// - /// - public static bool HasRolePermissions(this IEnumerable roles, XUserRole role) - { - // - // Validate ... - var result = - !roles.IsNull() && - roles.HasChild(); - if (!result) - { - return result; - } - - // - try - { - // - var topRole = roles.GetTopRole(); - - // - result = (int)topRole >= (int)role; - } - catch - { - result = false; - } - - // - return result; - } - public static bool HasRolePermissions(this IEnumerable roles, string role) - { - // - // Validate ... - var result = - !roles.IsNull() && - roles.HasChild() && - !role.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - var roleEnum = role.ToXUserRole(); - result = roles.HasRolePermissions(roleEnum); - - // - return result; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xIdentityModels-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xIdentityModels-20261109_152621.txt deleted file mode 100644 index 99f6a88..0000000 --- a/Documents/GeneratedContext/xDashboard-xIdentityModels-20261109_152621.txt +++ /dev/null @@ -1,4294 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\XApiToken.cs - -using xModels.Base; -using xCommons.Extensions; -using xIdentityModels.Models; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels { - public class XApiToken : XBaseIntIDEntity { - public string Content { get; set; } - - [NotMapped] - public XTokenResponse Tokens { - get { return Content.IsNullOrEmpty () ? null : Content.FromJSON (); } - set { Content = value.ToJSON (); } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\XUser.cs - -using System; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Navigations; -using Microsoft.AspNetCore.Identity; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels -{ - /// - /// represnt a User of System - /// - public partial class XUser : IdentityUser - { - // - #region Properties ... - /// - /// FirstName - /// - /// user's FirstName - [Required] - [StringLength(50)] - public string FirstName { get; set; } - /// - /// LastName - /// - /// user's LastName - [Required] - [StringLength(100)] - public string LastName { get; set; } - /// - /// User is Enabled or not - /// - /// - /// system was restrict Disabled Users access to Many Resources - /// - /// boolean value represent User is Enable or not - public bool IsEnable { get; set; } - /// - /// User is Banned or not - /// - /// - /// system was reject Banned Users access to Almost all Resources - /// - /// boolean value represent User is Banned or not - public bool IsBanned { get; set; } - /// - /// DateOfBirth - /// - /// user's DateOfBirth - [Required] - public DateTime DateOfBirth { get; set; } - /// - /// CreationDate - /// - /// user's Creation/Registration Date - [Required] - public DateTime CreationDate { get; set; } - /// - /// LastLogin - /// - /// user's Last Successfull Login Date - public DateTime? LastLogin { get; set; } - /// - /// ProfileImage/Avatar - /// - /// user's current Avatar - public string Avatar { get; set; } - /// - /// Gender - /// - /// user's Gender - [Required] - public XGender Gender { get; set; } - /// - /// User Biography ... - /// - /// - public string Bio { get; set; } - /// - /// User Bio Cover Image ... - /// - /// - public string CoverImage { get; set; } - /// - /// Can Discover User ... - /// - /// - public bool OpenToSearch { get; set; } - #endregion - - // - #region Navigation Properties ... - /// - /// User's Devices - /// - /// XDevice - /// a Collection of all assigned Devices to User - [InverseProperty("User")] - public virtual ICollection Devices { get; set; } = new HashSet(); - /// - /// User's Avatars - /// - /// XProfileImage - /// a Collection of all assigned Avatars to User - [InverseProperty("User")] - public virtual ICollection Avatars { get; set; } = new HashSet(); - /// - /// User's Followers - /// - /// XFriendshipFollower - /// a Collection of all User's Followers - [InverseProperty("User")] - public virtual ICollection Followers { get; set; } = new HashSet(); - /// - /// User's Followings - /// - /// XFriendshipFollowing - /// a Collection of all User's Followings - [InverseProperty("User")] - public virtual ICollection Followings { get; set; } = new HashSet(); - /// - /// User's Roles - /// - /// a Collection of all User's Roles in System - public virtual ICollection> Roles { get; set; } = new HashSet>(); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityConfiguration.cs - -using xIdentityModels.Dtos; -using System.Collections.Generic; - -namespace xIdentityModels.Configurations { - public class XIdentityConfiguration { - // - // Define All Policies which can Apply to Identity Framework - // and also create a Default instance if it's not Exists - // in AppSetting JSON file ... - public XIdentityPolicy Policy { get; set; } - - /// - /// the Security Key which used to Signing JWT Tokens - /// in Authentication Provider - /// - /// - public string IdentitySecretKey { get; set; } - - /// - /// the Issuer and Creator of Token - /// - /// - public string IdentityIssuer { get; set; } - - /// - /// the Audience and Consumer of Token - /// - /// - public string IdentityAudience { get; set; } - - /// - /// the List of Users Roles which must Provides in Identity - /// - /// - public HashSet IdentityRoles { get; set; } - - /// - /// determines All new users must Assign to which role in Registration - /// - /// - public string NewUsersRole { get; set; } - - /// - /// determines New Registered Users Confirm Email or not - /// - /// - public bool AutoConfirmNewUsersEmail { get; set; } - - /// - /// determines New Registered Users Confirm PhoneNumber or not - /// - /// - public bool AutoConfirmNewUsersPhoneNumber { get; set; } - - /// - /// determines the Registration only Can be done with Invitation or not - /// - /// - public bool RegistrationJustWithInvite { get; set; } - - /// - /// determines the Registration required confirmation with email or not - /// - /// - public bool RequireRegistrationConfirm { get; set; } - - // - public int MaxNumberOfVerificationCodeSend { get; set; } - - // - public int DeleyBetweenTwoVerificationCode { get; set; } - - public int BannedDeviceTimeout { get; set; } - - /// - /// an string Which Provide how long a action token can be valid - /// - /// - public string ActionTokenExpirationDateProvider { get; set; } - - public HashSet IdentityMessages { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityPolicy.cs - -namespace xIdentityModels.Configurations { - /// - /// Provide the Available Policies with their Default Values - /// - public class XIdentityPolicy { - /// - /// User Account Lock Policies - /// - /// - public XIdentityPolicyLockout Lockout { get; set; } - - /// - /// User Password Policies - /// - /// - public XIdentityPolicyPassword Password { get; set; } - - /// - /// the Policies for User for Allowing to SignIn - /// - /// - public XIdentityPolicySignIn SignIn { get; set; } - - /// - /// the Policies for User - /// - /// - public XIdentityPolicyUser User { get; set; } - - /// - /// the policies which determines how to - /// populate user profile - /// - /// - public XIdentityProfile Profile { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityPolicyLockout.cs - -namespace xIdentityModels.Configurations { - /// - /// User Account Lock Policies - /// - public class XIdentityPolicyLockout { - /// - /// The String which Provide Time Span Delais - /// between Lockout and UnLock a User Account - /// this Provided String the Parsed before Use - /// - /// - public string LockoutTimeSpanProvider { get; set; } - - /// - /// the Number of InvalidLoginAttemps which can - /// Happens to Lockout User Account - /// - /// - public byte MaxFailedAccessAttempts { get; set; } - - /// - /// determines Lockout mechanism allowed for new Users or not - /// - /// - public bool AllowedForNewUsers { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityPolicyPassword.cs - -namespace xIdentityModels.Configurations { - /// - /// User Password Policies - /// - public class XIdentityPolicyPassword { - /// - /// determines Password must contains digits or not - /// - /// - public bool RequireDigit { get; set; } - - /// - /// determines the minimum allowed length for a password - /// - /// - public byte RequiredLength { get; set; } - - /// - /// determines the number of Unique Chars must be included in a Password - /// - /// - public byte RequiredUniqueChars { get; set; } - - /// - /// determines Password must contains LowerCase chars or not - /// - /// - public bool RequireLowercase { get; set; } - - /// - /// determines Password must contains Non-Alphabetical chars or not - /// - /// - public bool RequireNonAlphanumeric { get; set; } - - /// - /// determines Password must contains UpperCase chars or not - /// - /// - public bool RequireUppercase { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityPolicySignIn.cs - -namespace xIdentityModels.Configurations { - /// - /// the Policies for User for Allowing to SignIn - /// - public class XIdentityPolicySignIn { - /// - /// determines only enabled users can SignIn - /// - /// - public bool RequiredEnabled { get; set; } - - /// - /// determines User must Confirm the given Email Address - /// before Login or not - /// - /// - public bool RequireConfirmedEmail { get; set; } - - /// - /// determines User must Confirm the given Phone Number - /// before Login or not - /// - /// - public bool RequireConfirmedPhoneNumber { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityPolicyUser.cs - -using System.Collections.Generic; - -namespace xIdentityModels.Configurations { - /// - /// the Policies for User - /// - public class XIdentityPolicyUser { - /// - /// determines Allowed characters which can used in UserName - /// - /// - public string AllowedUserNameCharacters { get; set; } - - /// - /// determines the Email Address of each User must be Unique or not - /// - /// - public bool RequireUniqueEmail { get; set; } - - /// - /// minimum length of User Name - /// - /// - public byte MinLength { get; set; } - - /// - /// maximum length of user name - /// - /// - public byte MaxLength { get; set; } - - /// - /// Minimum Age for Registration - /// - /// - public int MinAgeForRegistration { get; set; } - - /// - /// Maximum age for Registration - /// - /// - public int MaxAgeForRegistration { get; set; } - - /// - /// a collection of invalid usernames - /// - /// - public ICollection InvalidUserNames { get; set; } = new HashSet (); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Configurations\XIdentityProfile.cs - -namespace xIdentityModels.Configurations { - /// - /// contains user profile configuration - /// - public class XIdentityProfile { - /// - /// determines user profile contain email or not - /// - /// - public bool ContainsEmail { get; set; } - - /// - /// determines user profile contains phone number or not - /// - /// - public bool ContainsPhoneNumber { get; set; } - - /// - /// determines user profile contains Roles collection or not - /// - /// - public bool ContainsRoles { get; set; } - - public bool ContainsDateOfBirth { get; set; } - - public bool ContainsLastLogin { get; set; } - - public bool ContainsCreationDate { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XAction.cs - -namespace xIdentityModels.Constants { - public enum XAction { - Authentication, - Invite, - Registration, - RequestMobileVerificationCode, - ConfirmMobileNumber, - RequestEmailVerificationCode, - ConfirmEmailAddress, - AddAccountInfo, - AttachProfileImage, - RequestResetPassword, - ProfileAction, - Finish, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XApiKeyScope.cs - -using xExceptions.Attributes; - -namespace xIdentityModels.Constants -{ - public enum XApiKeyScope - { - [StringValue("read")] - Read, - - [StringValue("write")] - Write, - - [StringValue("admin")] - Admin, - - [StringValue("manage")] - Manage - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XApplicationType.cs - -namespace xIdentityModels.Constants -{ - public enum XApplicationType - { - Web, Mobile, Desktop, IoT, ThirdParty, Service - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XFriendshipState.cs - -namespace xIdentityModels.Constants { - /// - /// Represent State of Friendship between to Users - /// - public enum XFriendshipState { - None, - Pending, - Accepted, - Rejected, - Blocked, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XGender.cs - -namespace xIdentityModels.Constants { - /// - /// Determines Available Genders - /// - public enum XGender { - Male, - Female - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\xIdentityModelsConstants.cs - -namespace xIdentityModels.Constants { - public class xIdentityModelsConstants { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Constants\XUserSelectBy.cs - -namespace xIdentityModels.Constants { - public enum XUserSelectBy { - NotSpecified, - ID, - Username, - Email, - MobileNumber - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Descriptors\XIdentityUserDescriptor.cs - -namespace xIdentityModels.Descriptors { - /// - /// contains default users information - /// - public class XIdentityUserDescriptor { - public string Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string UserName { get; set; } - public string Email { get; set; } - public bool EmailConfirmed { get; set; } - public string PhoneNumber { get; set; } - public bool PhoneNumberConfirmed { get; set; } - public string Password { get; set; } - public string Role { get; set; } - public bool IsEnable { get; set; } - public bool IsBanned { get; set; } - public string DateOfBirth { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\DI\XDIHelperExtension.cs - -namespace xIdentityModels.DI { - public static partial class XDIHelperExtension { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XApiKeyDto.cs - -using System; -using xModels.Base; - -namespace xIdentityModels.Dtos -{ - /// - /// an Specified Api Key ... - /// - public class XApiKeyDto : XBaseGuidIDEntityDto - { - /// - /// Related Application Id ... - /// - public int ApplicationId { get; set; } - - /// - /// Hash ... - /// SHA256 of ApiKey ... - /// - public string KeyHash { get; set; } - - /// - /// a Prefix ... - /// - public string KeyPrefix { get; set; } - - /// - /// Expiration Type ... - /// - public DateTime ExpiresAt { get; set; } - - /// - /// Cration Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Last Usage Date ... - /// - public DateTime? LastUsedAt { get; set; } - - /// - /// Revoked Time ... - /// - public DateTime? RevokedAt { get; set; } - - /// - /// Revoker User Id ... - /// - public string RevokedBy { get; set; } - - /// - /// a Json Array String ... - /// XApiKeyScope ... - /// - public string AllowedScopes { get; set; } - - /// - /// a Comma-separated List which Specified White List IP ... - /// - public string AllowedIPs { get; set; } - - /// - /// Rate Limit Per Minute ... - /// - public int RateLimitPerMinute { get; set; } = 60; - - // - /// - /// Related Application ... - /// - public virtual XApplicationDto Application { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XApiKeyUsageDto.cs - -using System; -using xModels.Base; - -namespace xIdentityModels.Dtos -{ - public class XApiKeyUsageDto : XBaseLongIDEntityDto - { - /// - /// Api Key Id ... - /// - public Guid ApiKeyId { get; set; } - - /// - /// Called Endpoint ... - /// - public string Endpoint { get; set; } - - /// - /// Called Http Method ... - /// - public string HttpMethod { get; set; } - - /// - /// Client IP Address ... - /// - public string ClientIP { get; set; } - - /// - /// Status Code ... - /// - public int StatusCode { get; set; } - - /// - /// Request Time ... - /// - public DateTime RequestedOn { get; set; } - - /// - /// Response Time in Milliseconds ... - /// - public long ResponseTimeMs { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XApplicationDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xIdentityModels.Constants; - -namespace xIdentityModels.Dtos -{ - /// - /// an Application in xDashboard ... - /// - public class XApplicationDto : XBaseIntIDEntityDto - { - /// - /// Name ... - /// - public string Name { get; set; } - - /// - /// Descriptor ... - /// - public string Description { get; set; } - - /// - /// Owner Id ... - /// - public string OwnerId { get; set; } - public virtual XPersonDto Owner { get; set; } - - /// - /// Application Type ... - /// - public XApplicationType Type { get; set; } - - /// - /// Specified Application is Active or not ... - /// - public bool IsActive { get; set; } = true; - - /// - /// Application Create Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Application Update Type ... - /// - public DateTime UpdatedAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XDiscoveryDocumentDto.cs - -using Newtonsoft.Json; -using System.Collections.Generic; - -namespace xIdentityModels.Dtos -{ - public class XDiscoveryDocumentDto - { - [JsonProperty ("issuer")] - public string Issuer { get; set; } - - [JsonProperty ("jwks_uri")] - public string JwksUri { get; set; } - - [JsonProperty ("authorization_endpoint")] - public string AuthorizationEndpoint { get; set; } - - [JsonProperty ("token_endpoint")] - public string TokenEndpoint { get; set; } - - [JsonProperty ("userinfo_endpoint")] - public string UserinfoEndpoint { get; set; } - - [JsonProperty ("end_session_endpoint")] - public string EndSessionEndpoint { get; set; } - - [JsonProperty ("check_session_iframe")] - public string CheckSessionIframe { get; set; } - - [JsonProperty ("revocation_endpoint")] - public string RevocationEndpoint { get; set; } - - [JsonProperty ("introspection_endpoint")] - public string IntrospectionEndpoint { get; set; } - - [JsonProperty ("device_authorization_endpoint")] - public string DeviceAuthorizationEndpoint { get; set; } - - [JsonProperty ("frontchannel_logout_supported")] - public bool FrontchannelLogoutSupported { get; set; } - - [JsonProperty ("frontchannel_logout_session_supported")] - public bool FrontchannelLogoutSessionSupported { get; set; } - - [JsonProperty ("backchannel_logout_supported")] - public bool BackchannelLogoutSupported { get; set; } - - [JsonProperty ("backchannel_logout_session_supported")] - public bool BackchannelLogoutSessionSupported { get; set; } - - [JsonProperty ("scopes_supported")] - public List ScopesSupported { get; set; } - - [JsonProperty ("claims_supported")] - public List ClaimsSupported { get; set; } - - [JsonProperty ("grant_types_supported")] - public List GrantTypesSupported { get; set; } - - [JsonProperty ("response_types_supported")] - public List ResponseTypesSupported { get; set; } - - [JsonProperty ("response_modes_supported")] - public List ResponseModesSupported { get; set; } - - [JsonProperty ("token_endpoint_auth_methods_supported")] - public List TokenEndpointAuthMethodsSupported { get; set; } - - [JsonProperty ("id_token_signing_alg_values_supported")] - public List IdTokenSigningAlgValuesSupported { get; set; } - - [JsonProperty ("subject_types_supported")] - public List SubjectTypesSupported { get; set; } - - [JsonProperty ("code_challenge_methods_supported")] - public List CodeChallengeMethodsSupported { get; set; } - - [JsonProperty ("request_parameter_supported")] - public bool RequestParameterSupported { get; set; } - - [JsonProperty ("account_api")] - public string AccountApi { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XFriendDto.cs - -using xModels.Base; -using xIdentityModels.Constants; - -namespace xIdentityModels.Dtos -{ - /// - /// All Available Friendship Types ... - /// - public enum XFriendshipType - { - Follower = 0, - Following = 1, - } - - /// - /// a DTO Class Which Represent a User Friends ... - /// - public class XFriendDto : XBaseDto - { - public string Avatar { get; set; } - public string UserId { get; set; } - public string Username { get; set; } - public string Lastname { get; set; } - public string Firstname { get; set; } - public XFriendshipType Type { get; set; } - public XFriendshipState State { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XFriendshipInfoDto.cs - -using xModels.Base; -using xIdentityModels.Constants; - -namespace xIdentityModels.Dtos { - public class XFriendshipInfoDto : XBaseDto { - public string UserId { get; set; } - public bool IsFollower { get; set; } - public bool IsFollowing { get; set; } - public XFriendshipState FollowerState { get; set; } - public XFriendshipState FollowingState { get; set; } - public long Followers { get; set; } - public long Followings { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XIdentityMessageDto.cs - -using xModels.Base; - -namespace xIdentityModels.Dtos { - public class XIdentityMessageDto : XBaseDto { - public string Language { get; set; } - public string ResourceTitle { get; set; } - public string TranslatedValue { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XOpenActionDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xCommons.Extensions; - -namespace xIdentityModels.Dtos -{ - /// - /// a List of Available Open Actions ... - /// - public struct XOpenActions - { - public const string HandShake = "HandShake"; - public const string GetApiKey = "GetApiKey"; - public const string UseApiKey = "UseApiKey"; - public const string GetUserInfo = "GetUserInfo"; - public const string GetUserInfos = "GetUserInfos"; - } - - /// - /// Open Actions Request Model ... - /// - public class XOpenActionRequestDto : XBaseDto - { - // - public string Action { get; set; } - public string Payload { get; set; } - public string Checksum { get; set; } - public XDeviceDto Device { get; set; } - public string Timestamp { get; set; } - - /// - /// Validate Model ... - /// - /// - public bool Validate() - { - // - var result = - !Device.IsNull() && - !Timestamp.IsNull() && - !Action.IsNullOrEmpty() && - ( - // - Action == XOpenActions.HandShake || - Action == XOpenActions.GetApiKey || - Action == XOpenActions.UseApiKey || - Action == XOpenActions.GetUserInfo || - Action == XOpenActions.GetUserInfos - ) && - !Int64.Parse(Timestamp) - .FromTimestamp() - .IsExPired(); - - // - return result; - } - - /// - /// Checksum Digest Model ... - /// - /// - public string ToOpenActionToken() - { - // - var result = string.Empty; - if (!Validate()) - { - return result; - } - - // - var tmp = this; - tmp.Checksum = string.Empty; - - // - result = $"{tmp.ToJSON()}" - .ToMd5String(); - return result; - } - - /// - /// Validate a Token is Correspond to Model or not ... - /// - /// - /// - public bool ValidateToken(string token) - { - // - var result = - Validate() && - !token.IsNullOrEmpty() && - token == ToOpenActionToken(); - - // - return result; - } - } - - /// - /// aa Dto which used between Api's ... - /// - public class XOpenActionInnerDto : XBaseDto - { - public string Token { get; set; } - public string Payload { get; set; } - } - - /// - /// User Info Providing in Open Actions ... - /// - public class XOpenActionUserInfoDto : XBaseDto - { - public string UserId { get; set; } - public string Avatar { get; set; } - public string Username { get; set; } - public string Lastname { get; set; } - public string Firstname { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XProfileImageDto.cs - -using System; -using xModels.Base; -using Newtonsoft.Json; - -namespace xIdentityModels.Dtos { - public class XProfileImageDto : XBaseDto { - public int Id { get; set; } - - [JsonProperty ( - "name", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Name { get; set; } - - [JsonProperty ( - "thumb", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Thumb { get; set; } - - [JsonProperty ( - "path", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Path { get; set; } - - [JsonProperty ( - "thumbPath", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string ThumbPath { get; set; } - - [JsonProperty ( - "creationDate", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public DateTime CreationDate { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XUserNameIdRequest.cs - -using xModels.Base; -using System.Collections.Generic; - -namespace xIdentityModels.Dtos { - public class XUserNameIdRequest : XBaseDto { - public IEnumerable Ids { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XUserNameIdResponse.cs - -using xModels.Base; - -namespace xIdentityModels.Dtos { - public class XUserNameIdResponse : XBaseDto { - public string Id { get; set; } - public string UserName { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Dtos\XUserProfileDto.cs - -using System; -using xModels.Base; -using Newtonsoft.Json; -using xIdentityModels.Constants; -using System.Collections.Generic; - -namespace xIdentityModels.Dtos { - public class XUserProfileDto : XBaseDto { - [JsonProperty ( - "userId", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string UserId { get; set; } - - [JsonProperty ( - "userName", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string UserName { get; set; } - - [JsonProperty ( - "email", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Email { get; set; } - - [JsonProperty ( - "emailConfirmed", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public bool EmailConfirmed { get; set; } - - [JsonProperty ( - "phoneNumber", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string PhoneNumber { get; set; } - - [JsonProperty ( - "phoneNumberConfirmed", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public bool PhoneNumberConfirmed { get; set; } - - [JsonProperty ( - "firstName", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string FirstName { get; set; } - - [JsonProperty ( - "lastName", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string LastName { get; set; } - - [JsonProperty ( - "dateOfBirth", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public DateTime? DateOfBirth { get; set; } - - [JsonProperty ( - "creationDate", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public DateTime? CreationDate { get; set; } - - [JsonProperty ( - "lastLogin", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public DateTime? LastLogin { get; set; } - - [JsonProperty ( - "avatar", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Avatar { get; set; } - - [JsonProperty ( - "gender", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public XGender Gender { get; set; } - - [JsonProperty ( - "bio", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Bio { get; set; } - - [JsonProperty ( - "coverImage", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string CoverImage { get; set; } - - [JsonProperty ( - "openToSearch", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public bool OpenToSearch { get; set; } - - [JsonProperty ( - "friendshipInfo", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public XFriendshipInfoDto FriendshipInfo { get; set; } - - [JsonProperty ( - "roles", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public ICollection Roles { get; set; } = new HashSet (); - - [JsonProperty ( - "avatars", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public ICollection Avatars { get; set; } = new HashSet (); - - [JsonProperty ( - "isEnable", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public bool IsEnable { get; set; } - - [JsonProperty ( - "isBanned", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public bool IsBanned { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Extensions\DIExtensions.cs - -using xCommons.Extensions; -using xIdentityModels.Providers; -using xIdentityModels.Interfaces; -using Microsoft.Extensions.DependencyInjection; - -namespace xIdentityModels.Extensions { - public static class DIExtensions { - /// - /// since registering IXUserRoleHelper need to add default instance if - /// user not provided we create this helper ... - /// - /// - /// - public static void AddXUserRoleHandler ( - this IServiceCollection services, - IXUserRoleHelper helper = null - ) { - // - // Check if Provider is null ... - if (helper.IsNull ()) { - helper = services.GetRegisteredService (); - } - - // - // check if Provider registered or not ... - if (helper.IsNull ()) { - // - // Create Default provider ... - services.AddSingleton (new XDefaultUserRoleHelper ()); - } else { - // - // Register Given Helper ... - services.AddSingleton (helper); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Extensions\XIdentityExtensions.cs - -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Models; -using xIdentityModels.Constants; -using System.Collections.Generic; - -namespace xIdentityModels.Extensions { - public static class XIdentityExtensions { - public static XUserSelectBy GetUserSelectByType ( - this string source, - bool forceUserSelectByParamNotEmpty = true, - bool forceUserSelectByTypeMustSpecified = false - ) { - // - // Validate Args ... - if (source.IsNullOrEmpty () && - forceUserSelectByParamNotEmpty) { - XException.InvalidArgs.Throw (); - } - - // - var result = XUserSelectBy.NotSpecified; - var userSelectByParam = source.ToNormalString (); - if (userSelectByParam.IsValidEmail ()) { - // - // Find User by Email ... - result = XUserSelectBy.Email; - } else if (userSelectByParam.IsValidMobileNumber ()) { - // - // Find User by Mobile Number ... - result = XUserSelectBy.MobileNumber; - } else if (userSelectByParam.IsGuid ()) { - // - // Find User By it's ID ... - result = XUserSelectBy.ID; - } else { - // - // UserName ... - result = XUserSelectBy.Username; - } - - // - // Validation Result ... - if (forceUserSelectByTypeMustSpecified && - result == XUserSelectBy.NotSpecified) { - XException.InvalidData.Throw (); - } - - // - return result; - } - - public static string GetUserSelectByParam ( - this XActionRequest source, - bool forceNotNull = true, - ICollection excludes = null - ) { - // - // Validate Args ... - if (source.IsNull ()) { - XException.InvalidArgs.Throw (); - } - - // - var id = source.UserId; - var userName = source.UserName; - var email = source.Email; - var phoneNumber = source.MobileNumber; - - // - if (excludes != null) { - // - if (excludes.Contains (XUserSelectBy.ID)) { - id = null; - } - if (excludes.Contains (XUserSelectBy.Email)) { - email = null; - } - if (excludes.Contains (XUserSelectBy.MobileNumber)) { - phoneNumber = null; - } - if (excludes.Contains (XUserSelectBy.Username)) { - userName = null; - } - } - - // - var selectByParam = - id.IsNullOrEmpty () ? - userName.IsNullOrEmpty () ? - email.IsNullOrEmpty () ? - phoneNumber.IsNullOrEmpty () ? null : phoneNumber : email : userName : id; - - // - // Check result ... - if (forceNotNull && - selectByParam.IsNullOrEmpty ()) { - XException.InvalidData.Throw (); - } - - // - return selectByParam; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Extensions\xIdentityModelsExtensions.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xCommons.Constants; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using xIdentityModels.Models; -using System.Security.Claims; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Configurations; - -namespace xIdentityModels.Extensions -{ - public static class xIdentityModelsExtensions - { - /// - /// Converts a User Entity to Profile Dto ... - /// - /// - /// - /// - /// - /// - /// - /// - public static XUserProfileDto ToXProfileDto( - this XUser source, - bool isAdmin = false, - bool isSameUser = false, - IEnumerable roles = null, - XFriendshipInfoDto friendship = null, - XIdentityProfile profileConfig = null - ) - { - // - XUserProfileDto result = null; - - // - if (roles == null) - { - roles = new List(); - } - - // - // Prepare Dto ... - if (!source.IsNullOrDefault()) - { - // - result = new XUserProfileDto - { - Bio = source.Bio, - UserId = source.Id, - Email = source.Email, - Roles = roles.ToList(), - Avatar = source.Avatar, - IsEnable = source.IsEnable, - IsBanned = source.IsBanned, - UserName = source.UserName, - LastName = source.LastName, - FriendshipInfo = friendship, - FirstName = source.FirstName, - LastLogin = source.LastLogin, - CoverImage = source.CoverImage, - PhoneNumber = source.PhoneNumber, - DateOfBirth = source.DateOfBirth, - CreationDate = source.CreationDate, - OpenToSearch = source.OpenToSearch, - Gender = (XGender)(int)source.Gender, - EmailConfirmed = source.EmailConfirmed, - PhoneNumberConfirmed = source.PhoneNumberConfirmed, - Avatars = source.Avatars.Select(pfi => - { - // - return new XProfileImageDto - { - Id = pfi.Id, - Name = pfi.Name, - Path = pfi.Path, - Thumb = pfi.Thumb, - ThumbPath = pfi.ThumbPath, - CreationDate = pfi.CreationDate - }; - }).ToList(), - }; - } - - // - // Apply Profiling Configuration ... - - // - bool isPassed = false; - - // - // Handle Friendship ... - isPassed = !isSameUser; - if (!isPassed) - { - result.FriendshipInfo = null; - } - - // - // Handle Email Info ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsEmail); - if (!isPassed) - { - result.Email = string.Empty; - result.EmailConfirmed = false; - } - - // - // Handle PhoneNumber Info ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsPhoneNumber); - if (!isPassed) - { - source.PhoneNumber = string.Empty; - source.PhoneNumberConfirmed = false; - } - - // - // Handle Last Login ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsLastLogin); - if (!isPassed) - { - result.LastLogin = null; - } - - // - // Handle Date Of Birth ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsDateOfBirth); - if (!isPassed) - { - result.DateOfBirth = null; - } - - // - // Handle Creation Date ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsCreationDate); - if (!isPassed) - { - result.CreationDate = null; - } - - // - // Handle Roles ... - isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsRoles); - if (!isPassed) - { - result.Roles = new List(); - } - - // - return result; - } - - /// - /// Check Specified User Has Access to Provided Roles ... - /// - /// - /// - /// - public static bool HasAccess( - this XUserClaimsInfoDto source, - string[] roles - ) - { - // - var result = - !source.IsNullOrDefault() && - source.Roles - .Any(r => roles - .Any(ar => r.ToNormalString() - .Contains(ar.ToNormalString()))); - - // - return result; - } - - /// - /// Extract Top XApiKey Scope inside an Enumerable ... - /// - /// - /// - public static XApiKeyScope GetTopXApiKeyScope( - this IEnumerable scopes - ) - { - // - // Check Scopes Has Child ... - if (!scopes.HasChild()) - { - XException.NotFound.Throw(); - } - - // - var hasAdmin = scopes - .Any(s => - s.GetStringValue().ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString()); - var hasRead = scopes - .Any(s => - s.GetStringValue().ToNormalString() == XApiKeyScope.Read.GetStringValue().ToNormalString()); - var hasWrite = scopes - .Any(s => - s.GetStringValue().ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString()); - var hasManage = - (hasRead && hasWrite) || - scopes - .Any(s => - s.GetStringValue().ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString()); - - // - // Admin ... - if (hasAdmin) - { - return XApiKeyScope.Admin; - } - else if (hasManage) - { - return XApiKeyScope.Manage; - } - else if (hasWrite) - { - return XApiKeyScope.Write; - } - else - { - return XApiKeyScope.Read; - } - } - - /// - /// Check Source ApiKey Scope Has Access to Dest ... - /// - /// - /// - /// - public static bool HasAccess( - this XApiKeyScope source, - XApiKeyScope dest - ) - { - // - var result = source == dest; - if (result) - { - return result; - } - - // - var alls = Enumerable.Empty(); - switch (source) - { - // - // Admin ... - case XApiKeyScope.Admin: - // - alls = [ - XApiKeyScope.Admin, - XApiKeyScope.Manage, - XApiKeyScope.Write, - XApiKeyScope.Read - ]; - - // - result = alls.Contains(dest); - break; - - // - // Manage ... - case XApiKeyScope.Manage: - // - alls = [ - XApiKeyScope.Manage, - XApiKeyScope.Write, - XApiKeyScope.Read - ]; - - // - result = alls.Contains(dest); - break; - - // - // Write ... - case XApiKeyScope.Write: - // - alls = [XApiKeyScope.Write]; - - // - result = alls.Contains(dest); - break; - - // - // Read ... - case XApiKeyScope.Read: - // - alls = [XApiKeyScope.Read]; - - // - result = alls.Contains(dest); - break; - } - - // - return result; - } - - /// - /// Check Allowed Scopes passed Based on Required Scopes ... - /// - /// - /// - /// - public static bool IsScopePassed( - this IEnumerable allowedScopes, - IEnumerable requiredScopes - ) - { - // - // if Allowed Scopes is Empty, this means access to - // All Scopes are Valid ... - var result = !allowedScopes.HasChild(); - if (result) - { - return result; - } - - // - // Make Sure we Have at least one Required Scope for Validation ... - result = requiredScopes.HasChild(); - if (!result) - { - return result; - } - - // - // Converts each Allowed or Required Scopes to XApiKeyScope ... - var alloweds = allowedScopes.Select(asc => - { - // - if (asc.ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Admin; - } - else if (asc.ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Manage; - } - else if (asc.ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Write; - } - else - { - return XApiKeyScope.Read; - } - }); - var requireds = requiredScopes.Select(asc => - { - // - if (asc.ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Admin; - } - else if (asc.ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Manage; - } - else if (asc.ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString()) - { - return XApiKeyScope.Write; - } - else - { - return XApiKeyScope.Read; - } - }); - - // - // Retrieve top Allowed ApiKey Scope ... - var topAllowed = alloweds.GetTopXApiKeyScope(); - var topRequired = requireds.GetTopXApiKeyScope(); - - // - result = topAllowed.HasAccess(topRequired); - - // - return result; - } - - /// - /// Check Dest Client IP is Exists in Source or not ... - /// - /// - /// - /// - public static bool IsClientIpPassed( - this IEnumerable source, - string dest - ) - { - // - // if Allowed IPs Empty means all Client IPs is Valid ... - var result = - !source.HasChild(); - if (result) - { - return result; - } - - // - result = !dest.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - result = source.Any(s => s.ToNormalString() == dest.ToNormalString()); - if (!result) - { - // - if (dest == "::1") - { - // - result = source.Any(s => - s.ToNormalString() == "127.0.0.1" || - s.ToNormalString() == "localhost"); - } - } - - // - return result; - } - - /// - /// Check Specified User Contains Specified UserSelectByParam or not ... - /// - /// - /// - /// - public static bool ContainsUserSelectByParam( - this XUser source, - string userSelectByParam - ) - { - // - var result = - !source.IsNull() && - !userSelectByParam.IsNullOrEmpty() && - (source.Id == userSelectByParam || - source.Email.ToNormalString() == userSelectByParam.ToNormalString() || - source.UserName.ToNormalString() == userSelectByParam.ToNormalString() || - source.PhoneNumber.ToNormalString() == userSelectByParam.ToNormalString()); - - // - return result; - } - - /// - /// Check Specified Api Key is Revoked or not ... - /// - /// - /// - public static bool IsRevoked(this XApiKey source) - { - // - var result = - !source.IsNullOrDefault() && - source.RevokedAt.HasValue; - - // - return result; - } - - /// - /// Check Specified Api Key is Expired or not ... - /// - /// - /// - public static bool IsExpired(this XApiKey source) - { - // - var result = - !source.IsNullOrDefault() && - DateTime.UtcNow >= source.ExpiresAt; - - // - return result; - } - - /// - /// Check Specified Api Key is Active or not ... - /// - /// - /// - public static bool IsActive(this XApiKey source) - { - // - var result = - !source.IsNullOrDefault() && - !source.IsRevoked() && - !source.IsExpired(); - - // - return result; - } - - /// - /// Extract ApiKey Validated User ... - /// - /// - /// - public static XPersonDto ExtractApiKeyUser( - this ClaimsPrincipal source - ) - { - // - XPersonDto result = null; - - // - // Validate ... - if (!source.IsNull() && - source.Claims.HasChild()) - { - source.Claims.ExtractApiKeyUser(); - } - - // - return result; - } - - /// - /// Extract ApiKey Validated User ... - /// - /// - /// - public static XPersonDto ExtractApiKeyUser( - this IEnumerable source - ) - { - // - XPersonDto result = null; - - // - // Validate ... - if (source.HasChild()) - { - // - result = new XPersonDto - { - UserId = source.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? "", - Avatar = source.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? "", - Username = source.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? "", - Lastname = source.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? "", - Firstname = source.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? "", - }; - } - - // - return result; - } - - /// - /// Extract JWT Validated User ... - /// - /// - /// - public static XPersonDto ExtractAuthenticatedUser( - this ClaimsPrincipal source - ) - { - // - XPersonDto result = null; - - // - // Validate ... - if (!source.IsNull() && - source.Claims.HasChild()) - { - source.Claims.ExtractAuthenticatedUser(); - } - - // - return result; - } - - /// - /// Extract JWT Validated User ... - /// - /// - /// - public static XPersonDto ExtractAuthenticatedUser( - this IEnumerable source - ) - { - // - XPersonDto result = null; - - // - // Validate ... - if (source.HasChild()) - { - // - result = new XPersonDto - { - UserId = source.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? "", - Avatar = source.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? "", - Username = source.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? "", - Lastname = source.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? "", - Firstname = source.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? "", - }; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Extensions\XModelExtensions.cs - -using System; -using xModels.Dtos; -using IdentityModel; -using xCommons.Constants; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xIdentityModels.Models; -using System.Security.Claims; -using System.Collections.Generic; -using xIdentityModels.Descriptors; -using xIdentityModels.Navigations; - -namespace xIdentityModels.Extensions -{ - public static class XModelExtensions - { - /// - /// /// Convert XIdentityUserDescriptor instance to XUser - /// - /// - /// - public static XUser ToXUser(this XIdentityUserDescriptor source) - { - return new XUser - { - Id = source.Id, - FirstName = source.FirstName, - LastName = source.LastName, - UserName = source.UserName, - Email = source.Email, - EmailConfirmed = source.EmailConfirmed, - PhoneNumber = source.PhoneNumber, - PhoneNumberConfirmed = source.PhoneNumberConfirmed, - IsEnable = true, - IsBanned = false, - CreationDate = DateTime.UtcNow, - DateOfBirth = DateTime.Parse(source.DateOfBirth) - }; - } - - /// - /// Converts a User to Person ... - /// - /// - /// - public static XPersonDto ToXPerson(this XUser source) - { - // - XPersonDto result = null; - - // - if (!source.IsNullOrDefault()) - { - // - result = new XPersonDto - { - UserId = source.Id, - Avatar = source.Avatar, - Username = source.UserName, - Lastname = source.LastName, - Firstname = source.FirstName, - }; - } - - // - return result; - } - - /// - /// Check a User is Same as Descriptor User - /// - /// - /// - /// - public static bool IsSameAs(this XUser source, XIdentityUserDescriptor dest) - { - // - if (source.IsNull() || - dest.IsNull()) - { - return false; - } - - // - var isSame = source.IsSameContent(dest, propertyWhiteList: new[] { - nameof (XIdentityUserDescriptor.FirstName), - nameof (XIdentityUserDescriptor.LastName), - nameof (XIdentityUserDescriptor.UserName), - nameof (XIdentityUserDescriptor.Email), - nameof (XIdentityUserDescriptor.EmailConfirmed), - nameof (XIdentityUserDescriptor.PhoneNumber), - nameof (XIdentityUserDescriptor.PhoneNumberConfirmed), - nameof (XIdentityUserDescriptor.IsEnable), - nameof (XIdentityUserDescriptor.IsBanned), - nameof (XIdentityUserDescriptor.DateOfBirth) - }, - propertyValueCheckers: new[] { - new KeyValuePair> ( - nameof (XIdentityUserDescriptor.DateOfBirth), - (user, descriptorUser) => { - // - var descriptorUserDateOfBirth = DateTime.Parse (descriptorUser.DateOfBirth); - return DateTime.Equals (user.DateOfBirth, descriptorUserDateOfBirth); - }) - } - ); - - // - return isSame; - } - - /// - /// Check to XDevice instance to be same or not - /// - /// - /// - /// - public static bool IsSameAs(this XDevice source, XDevice dest) - { - // - if (source.IsNull() || - dest.IsNull()) - { - return false; - } - - // - var isSame = source.Os.ToNormalString() == dest.Os.ToNormalString() && - source.OsVersion.ToNormalString() == dest.OsVersion.ToNormalString() && - source.Browser.ToNormalString() == dest.Browser.ToNormalString() && - source.UserAgent.ToNormalString() == dest.UserAgent.ToNormalString() && - source.DeviceType == dest.DeviceType; - - // - return isSame; - } - - /// - /// convert UserClaimsInfo to TokenResponse ... - /// - /// - /// - public static XTokenResponse ToXTokenResponse(this XUserClaimsInfoDto source) - { - // - if (source.IsNull() || - (source.AccessToken.IsNullOrEmpty() && source.RefreshToken.IsNullOrEmpty())) - { - return null; - } - - // - var result = new XTokenResponse - { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = source.ExpiresAt - }; - - // - return result; - } - - /// - /// Converts XPersonDto to XUserClaimsInfoDto ... - /// - /// - /// - public static XUserClaimsInfoDto ToXUserClaimsInfoDto(this XPersonDto source) - { - // - XUserClaimsInfoDto result = null; - - // - if (!source.IsNullOrDefault()) - { - // - result = new XUserClaimsInfoDto( - userid: source.UserId, - avatar: source.Avatar, - username: source.Username, - lastname: source.Lastname, - firstname: source.Firstname - ); - } - - // - return result; - } - - /// - /// Validate ... - /// - /// - /// - public static bool IsValid(this XCreateApiKeyRequest source) - { - // - var result = !source.IsNull(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApplication source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApplicationDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.Name.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApiKey source) - { - // - var result = - !source.IsNullOrDefault() && - !source.ApplicationId.IsValidIntId() && - !source.KeyHash.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApiKeyDto source) - { - // - var result = - !source.IsNullOrDefault() && - source.ApplicationId.IsValidIntId() && - !source.KeyHash.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApiKeyUsage source) - { - // - var result = - !source.IsNullOrDefault() && - !source.ApiKeyId.IsDefaultGuid() && - !source.ClientIP.IsNullOrEmpty() && - !source.Endpoint.IsNullOrEmpty() && - !source.HttpMethod.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Validate Item for Add or Update ... - /// - /// - /// - public static bool IsValidForAdd(this XApiKeyUsageDto source) - { - // - var result = - !source.IsNullOrDefault() && - !source.ApiKeyId.IsDefaultGuid() && - !source.ClientIP.IsNullOrEmpty() && - !source.Endpoint.IsNullOrEmpty() && - !source.HttpMethod.IsNullOrEmpty(); - - // - return result; - } - - /// - /// Converts XApiKeyValidationResult to Claims ... - /// - /// - /// - public static IList ToXClaims( - this XApiKeyValidationResult source - ) - { - // - var result = new List(); - - // - // Validate ... - if (!source.IsNullOrDefault() && - !source.Owner.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() && - source.ApplicationId.IsValidIntId() - ) - { - // - result.Add(new(ClaimTypes.Name, source.OwnerId)); - result.Add(new(XCustomClaims.UserId, source.OwnerId)); - result.Add(new(JwtClaimTypes.Subject, source.OwnerId)); - result.Add(new(XCustomClaims.Picture, source.Owner.Avatar)); - result.Add(new(XCustomClaims.UserName, source.Owner.Username)); - result.Add(new(XCustomClaims.LastName, source.Owner.Lastname)); - result.Add(new(XCustomClaims.AuthType, XAuthorization.XApiKey)); - result.Add(new(XCustomClaims.FirstName, source.Owner.Firstname)); - result.Add(new(XCustomClaims.ApplicationId, source.ApplicationId.ToString())); - - // - if (source.Scopes.HasChild()) - { - // - foreach (var scope in source.Scopes) - { - result.Add(new(JwtClaimTypes.Scope, scope)); - } - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Extensions\XTokenExtensions.cs - -using System; -using System.Linq; -using System.Net.Http; -using xCommons.Constants; -using xCommons.Extensions; -using IdentityModel.Client; -using xExceptions.Constants; -using System.Security.Claims; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Net.Http.Headers; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using Microsoft.IdentityModel.Tokens; -using System.IdentityModel.Tokens.Jwt; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authentication; - -namespace xIdentityModels.Extensions { - public static class XTokenExtensions { - // - #region Identity Token Extensions ... - /// - /// Convert a SecurityToken to it's Token String - /// - /// - /// - /// - public static string ToTokenString ( - this SecurityToken source, - JwtSecurityTokenHandler tokenHandler - ) { - return tokenHandler.WriteToken (source); - } - - /// - /// Validate a Token - /// - /// - /// - /// - /// - public static bool ValidateToken ( - this string token, - JwtSecurityTokenHandler tokenHandler, - TokenValidationParameters tokenValidationParams) { - // - if (token.IsNullOrEmpty ()) { - return false; - } - - // - SecurityToken tokenObj = null; - try { - tokenHandler.ValidateToken (token, tokenValidationParams, out tokenObj); - } catch { - return false; - } - - // - return tokenObj != null; - } - - /// - /// Convert a token string to Security Token - /// - /// - /// - /// - /// - public static SecurityToken ToSecurityToken ( - this string token, - JwtSecurityTokenHandler tokenHandler, - TokenValidationParameters tokenValidationParams) { - // - if (token.IsNullOrEmpty () || - !token.ValidateToken (tokenHandler, tokenValidationParams)) { - // - return null; - } - - // - // convert token from String to JWTSecurity Token ... - try { - return tokenHandler.ReadToken (token); - } catch { - return null; - } - } - - /// - /// Parse Action Token and return Corresponding RegistrationRequestDto - /// - /// - /// - /// - /// - public static XActionRequestToken ParseActionRequestToken ( - this string token, - JwtSecurityTokenHandler tokenHandler, - TokenValidationParameters tokenValidationParams) { - // - if (token.IsNullOrEmpty () || - !token.ValidateToken (tokenHandler, tokenValidationParams)) { - // - return null; - } - - // - // convert token from String to JWTSecurity Token ... - JwtSecurityToken tokenObj = null; - try { - tokenObj = tokenHandler.ReadToken (token) as JwtSecurityToken; - } catch { - return null; - } - - // - if (tokenObj == null) { - return null; - } - - // - // Extract Registered Payload Claims ... - var mCurrentStepClaim = tokenObj.Claims - .FirstOrDefault (c => c.Type == nameof (XActionRequestToken.Action)); - var mContextClaim = tokenObj.Claims - .FirstOrDefault (c => c.Type == nameof (XActionRequestToken.Context)); - var mTokenClaim = tokenObj.Claims - .FirstOrDefault (c => c.Type == nameof (XActionRequestToken.Token)); - - // - // Check All Claims to be NotNull ... - if (mCurrentStepClaim == null || - mContextClaim == null || - mTokenClaim == null) { - return null; - } - - // - // Reading all Claims Values ... - var mCurrentStepStr = mCurrentStepClaim.Value; - var mCurrentStep = 0; - try { - int.TryParse (mCurrentStepStr, out mCurrentStep); - } catch { } - - // - var mContext = mContextClaim.Value.IsNullOrEmpty () ? - null : mContextClaim.Value.FromJSON (); - var mToken = mTokenClaim.Value; - - // - // Create Instance of UserInvite ... - var result = new XActionRequestToken { - Action = (XAction) mCurrentStep, - Context = mContext, - Token = mToken - }; - - // - return result; - } - - /// - /// Check to ActionRequestContext object is same or not - /// - /// - /// - /// - public static bool IsSameAs ( - this XActionRequestContext source, - XActionRequestContext dest - ) { - // - if (source == null || - dest == null) { - return false; - } - - // - var result = source.ToJSON () == dest.ToJSON (); - - // - return result; - } - - /// - /// Convert a RegistrationRequestDto object to it's jwt token Claims - /// - /// - /// - public static Claim[] ToJwtClaims (this XActionRequestToken source) { - // - // Generate Required Fields ... - var action = source.Action; - var context = source.Context; - var token = source.Token; - - // - // Generate Claims Array ... - var claims = new Claim[] { - new Claim (nameof (XActionRequestToken.Action), ((int) action).ToString (), ClaimValueTypes.Integer), - new Claim (nameof (XActionRequestToken.Context), context == null ? "" : context.ToJSON (), ClaimValueTypes.String), - new Claim (nameof (XActionRequestToken.Token), token.IsNullOrEmpty () ? "" : token, ClaimValueTypes.String) - }; - - // - // Return Result ... - return claims; - } - - /// - /// Generate a SecurityToken based on RegistrationRequestDto object - /// - /// - /// - /// - /// - public static SecurityToken ToJwtToken ( - this XActionRequestToken source, - JwtSecurityTokenHandler tokenHandler, - SecurityTokenDescriptor tokenDescriptor) { - // - // Getting Claims ... - var claims = source.ToJwtClaims (); - tokenDescriptor.Subject = new ClaimsIdentity (claims); - - // - // Generate Token Object ... - var tokenObject = tokenHandler.CreateToken (tokenDescriptor); - - // - // Return Result ... - return tokenObject; - } - #endregion - - // - #region IdentityServer Token Extensions ... - /// - /// Retrieve Tokens From Headers - /// - /// - /// - public static XTokenResponse RetrieveTokens (this HttpRequest source) { - // - var accessToken = source.Headers[XAuthorization.Header].ToString (); - var refreshToken = source.Headers[XAuthorization.RefreshToken].ToString (); - - // - var expiresAtStr = source.Headers[XAuthorization.ExpiresAt].ToString (); - long expiresAt = expiresAtStr.ConvertTo (); - - // - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - // - return new XTokenResponse { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrieve Tokens From HttpContext - /// - /// - /// - public static async Task RetrieveTokens (this HttpContext source) { - // - var accessToken = await source.GetTokenAsync (XAuthorization.AccessToken); - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - var refreshToken = await source.GetTokenAsync (XAuthorization.RefreshToken); - var expiresAtStr = await source.GetTokenAsync (XAuthorization.ExpiresAt); - long expiresAt = expiresAtStr.ConvertTo (); - - // - var headerRequestTokens = source.Request.RetrieveTokens (); - - // - var result = new XTokenResponse { - AccessToken = accessToken ?? headerRequestTokens.AccessToken, - RefreshToken = refreshToken ?? headerRequestTokens.RefreshToken, - ExpiresAt = expiresAt != 0 ? expiresAt : headerRequestTokens.ExpiresAt - }; - - // - return result; - } - - /// - /// Retrieve Tokens From ActionExecutingContext - /// - /// - /// - public static async Task RetrieveTokens (this ActionExecutingContext source) { - // - var result = await source.HttpContext.RetrieveTokens (); - return result; - } - - /// - /// Retrieve Tokens From XUserInfo instance - /// - /// - /// - public static XTokenResponse RetrieveTokens (this XUserClaimsInfoDto source) { - // - var result = new XTokenResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = source.ExpiresAt - }; - - // - return result; - } - - /// - /// Retrieve Tokens From IHeader Dictionary - /// - /// - /// - public static XTokenResponse RetrieveTokens (this IHeaderDictionary source) { - // - var accessToken = source[XAuthorization.Header].ToString () ?? ""; - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - // - var refreshToken = source[XAuthorization.RefreshToken].ToString () ?? ""; - - // - var expiresAtStr = source[XAuthorization.ExpiresAt].ToString () ?? ""; - var expiresAt = expiresAtStr.ConvertTo (); - - // - var result = new XTokenResponse { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - - // - return result; - } - - /// - /// Generate XTokenResponse instance based on TokenResponse - /// - /// - /// - public static XLoginResponse CreateXLoginResponse (this TokenResponse source) { - // - if (source.IsNull () || - source.IsError) { - XException.InvalidToken.Throw (); - } - - // - var expiresAt = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds () + - source.ExpiresIn; - - // - var result = new XLoginResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = expiresAt - }; - - // - return result; - } - - /// - /// Generate XTokenResponse instance based on TokenResponse - /// - /// - /// - public static XTokenResponse CreateXTokenResponse (this TokenResponse source) { - // - if (source.IsNull () || - source.IsError) { - XException.InvalidToken.Throw (); - } - - // - var expiresAt = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds () + - source.ExpiresIn; - - // - var result = new XTokenResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = expiresAt - }; - - // - return result; - } - - /// - /// Convert XLoginResponse to XTokenResponse - /// - /// - /// - public static XTokenResponse ToXTokenResponse (this XLoginResponse source) { - // - if (source.IsNull ()) { - return null; - } - - // - return new XTokenResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = source.ExpiresAt - }; - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this IHeaderDictionary source, - XLoginResponse model, - string secret = null - ) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - - // - if (!secret.IsNullOrEmpty ()) { - var revisionChecksum = model.GetRevisionChecksum (secret); - source.Add (XAuthorization.RevisionChecksum, revisionChecksum); - } - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this IHeaderDictionary source, - XTokenResponse model, - string secret = null - ) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - - // - if (!secret.IsNullOrEmpty ()) { - var revisionChecksum = model.GetRevisionChecksum (secret); - source.Add (XAuthorization.RevisionChecksum, revisionChecksum); - } - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequestHeaders source, - XLoginResponse model - ) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequestHeaders source, - XTokenResponse model - ) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequest source, - XLoginResponse model - ) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequest source, - XTokenResponse model - ) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequestMessage source, - XLoginResponse model - ) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpRequestMessage source, - XTokenResponse model - ) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add ReNewed Authorization Tokens in Headers of - /// Specific Response. - /// Later in HttpInterceptors we can Look for AccessToken-ReNewed - /// header Value and Renew User Tokens based on it - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpResponse source, - XLoginResponse model, - string secret - ) { - source.Headers.SetXAuthenticationTokens (model, secret); - } - - /// - /// Add ReNewed Authorization Tokens in Headers of - /// Specific Response. - /// Later in HttpInterceptors we can Look for AccessToken-ReNewed - /// header Value and Renew User Tokens based on it - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpResponse source, - XTokenResponse model, - string secret - ) { - source.Headers.SetXAuthenticationTokens (model, secret); - } - - /// - /// Determines a Token Can Refrsh or not - /// - /// - /// - public static bool IsRefreshable (this XLoginResponse source) { - // - var containsTokenData = !source.IsNull () && - !source.AccessToken.IsNullOrEmpty () && - !source.RefreshToken.IsNullOrEmpty (); - if (!containsTokenData) { - return false; - } - - // - var current = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds (); - - // - // var result = current > source.ExpiresAt || current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - var result = current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - - // - return result; - } - - /// - /// Determines a Token Can Refrsh or not - /// - /// - /// - public static bool IsRefreshable (this XTokenResponse source) { - // - var containsTokenData = !source.IsNull () && - !source.AccessToken.IsNullOrEmpty () && - !source.RefreshToken.IsNullOrEmpty (); - if (!containsTokenData) { - return false; - } - - // - var current = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds (); - - // - // var result = current > source.ExpiresAt || current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - var result = current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - - // - return result; - } - - /// - /// Generate a Revision Checksum for new Tokens - /// - /// - /// - /// - public static string GetRevisionChecksum ( - this XLoginResponse source, - string secret - ) { - return (source.AccessToken + - secret + - source.RefreshToken + - secret + - source.ExpiresAt.ToString () - ) - .ToMd5String (); - } - - /// - /// Generate a Revision Checksum for new Tokens - /// - /// - /// - /// - public static string GetRevisionChecksum ( - this XTokenResponse source, - string secret - ) { - return (source.AccessToken + - secret + - source.RefreshToken + - secret + - source.ExpiresAt.ToString () - ) - .ToMd5String (); - } - - /// - /// Check an XLoginResponse instance is Valid with it's revision - /// - /// - /// - /// - /// - public static bool ValidateRevisionChecksum ( - this XLoginResponse source, - string checksum, - string secret - ) { - // - var xChecksum = source.GetRevisionChecksum (secret); - return checksum == xChecksum; - } - - /// - /// Check an XTokenResponse instance is Valid with it's revision - /// - /// - /// - /// - /// - public static bool ValidateRevisionChecksum ( - this XTokenResponse source, - string checksum, - string secret - ) { - // - var xChecksum = source.GetRevisionChecksum (secret); - return checksum == xChecksum; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Interfaces\IXUserRoleHelper.cs - -using xIdentityModels.Models; - -namespace xIdentityModels.Interfaces { - public interface IXUserRoleHelper { - bool canReadCriticalData (XUserClaimsInfoDto userInfo); - bool canDoDangerousAction (XUserClaimsInfoDto userInfo); - bool isInRole (XUserClaimsInfoDto userInfo, string role); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XActionRequest.cs - -using System; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Navigations; - -namespace xIdentityModels.Models { - /// - /// represent a system wide actions - /// - public class XActionRequest { - /// - /// Client Device Locale - /// - /// user's client device local such as en-US - public string Lang { get; set; } = null; - /// - /// Requested Action Token - /// - /// a hashed content - public string ActionToken { get; set; } = null; - /// - /// user's device - /// - /// an instance of XDevice which represent user's device - public XDevice Device { get; set; } = null; - /// - /// FirstName - /// - /// users FirstName - public string FirstName { get; set; } = null; - /// - /// LastName - /// - /// user's LastName - public string LastName { get; set; } = null; - /// - /// an Optional Value which represetns User's DateOfBirth - /// - /// user's DateOfBirth - public DateTime? DateOfBirth { get; set; } = DateTime.MinValue; - /// - /// User's Id - /// - /// a GUID string which represent user's Id - public string UserId { get; set; } = null; - /// - /// UserName - /// - /// user's UserName - public string UserName { get; set; } = null; - /// - /// Email - /// - /// user's Email address - public string Email { get; set; } = null; - /// - /// MobileNumber / PhoneNumber - /// - /// user's PhoneNumber - public string MobileNumber { get; set; } = null; - /// - /// Password - /// - /// user's Password - public string Password { get; set; } = null; - /// - /// NewPassword - /// - /// a passwor string which used to Change/Reset password - public string NewPassword { get; set; } = null; - /// - /// EmailVerificationCode - /// - /// a Verification Code which assign to user's for confirm it's Email Address - public string EmailVerificationCode { get; set; } = null; - /// - /// MobileVerificationCode - /// - /// a Verification Code which assign to user's for confirm it's Phone Number - public string MobileVerificationCode { get; set; } = null; - /// - /// Thumbnail - /// - /// an instance of IFormFile which is used as user's avatar - public IFormFile Thumbnail { get; set; } - /// - /// ReturnUrl - /// - /// - /// a url string which used in many used cases for providing a way to lead users to right places. - /// - public string ReturnUrl { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XActionRequestContext.cs - -using System; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Navigations; - -namespace xIdentityModels.Models { - public class XActionRequestContext { - // - public string Lang { get; set; } - - // - public string UserId { get; set; } - public string UserName { get; set; } - - // - public string MobileNumber { get; set; } - public string MobileVerificationCode { get; set; } - public bool MobileVerified { get; set; } - - // - public string Email { get; set; } - public string EmailVerificationCode { get; set; } - public bool EmailVerified { get; set; } - - // - public string FirstName { get; set; } - public string LastName { get; set; } - public DateTime DateOfBirth { get; set; } - - // - public XDevice Device { get; set; } - public IFormFile Thubmnail { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XActionRequestToken.cs - -using xCommons.Extensions; -using xIdentityModels.Constants; - -namespace xIdentityModels.Models { - public class XActionRequestToken { - public XAction Action { get; set; } - public XActionRequestContext Context { get; set; } - public string Token { get; set; } - - public void Prepare (string secret) { - Token = (Action.ToString () + - secret + - Context.ToJSON ()).ToMd5String (); - } - - public bool Validate (string secret) { - return (Action.ToString () + - secret + - Context.ToJSON ()).ToMd5String () == Token; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XActionResponse.cs - -using System; -using Newtonsoft.Json; - -namespace xIdentityModels.Models { - /// - /// represent a system wide action result - /// - public class XActionResponse { - /// - /// ActionToken - /// - /// a hashed string which carry required info for doing system actions. - [JsonProperty ( - "token", - Required = Required.Default, - NullValueHandling = NullValueHandling.Ignore)] - public string Token { get; set; } - - /// - /// ActionToken Lifetime - /// - /// an instance of DateTime which represent token expiration time - [JsonProperty ( - "expiration", - Required = Required.DisallowNull, - NullValueHandling = NullValueHandling.Ignore)] - public DateTime Expiration { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XApiKey.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xIdentityModels.Models -{ - /// - /// an Specified Api Key ... - /// - public class XApiKey : XBaseGuidIDEntity - { - /// - /// Related Application Id ... - /// - [Required] - public int ApplicationId { get; set; } - - /// - /// ApiKey ... - /// - [Required] - public string Key { get; set; } - - /// - /// Hash ... - /// SHA256 of ApiKey ... - /// - [Required] - [StringLength(512)] - public string KeyHash { get; set; } - - /// - /// a Prefix ... - /// - [StringLength(100)] - public string KeyPrefix { get; set; } - - /// - /// Expiration Type ... - /// - [Required] - public DateTime ExpiresAt { get; set; } - - /// - /// Cration Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Last Usage Date ... - /// - public DateTime? LastUsedAt { get; set; } - - /// - /// Revoked Time ... - /// - public DateTime? RevokedAt { get; set; } - - /// - /// Revoker User Id ... - /// - public string RevokedBy { get; set; } - - /// - /// a Json Array String ... - /// XApiKeyScope ... - /// - [StringLength(1000)] - public string AllowedScopes { get; set; } - - /// - /// a Comma-separated List which Specified White List IP ... - /// - [StringLength(2000)] - public string AllowedIPs { get; set; } - - /// - /// Rate Limit Per Minute ... - /// - public int RateLimitPerMinute { get; set; } = 60; - - // - #region Navigation ... - /// - /// Related Application ... - /// - public virtual XApplication Application { get; set; } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XApiKeyUsage.cs - -using System; -using xModels.Base; - -namespace xIdentityModels.Models -{ - public class XApiKeyUsage : XBaseLongIDEntity - { - /// - /// Api Key Id ... - /// - public Guid ApiKeyId { get; set; } - - /// - /// Called Endpoint ... - /// - public string Endpoint { get; set; } - - /// - /// Called Http Method ... - /// - public string HttpMethod { get; set; } - - /// - /// Client IP Address ... - /// - public string ClientIP { get; set; } - - /// - /// Status Code ... - /// - public int StatusCode { get; set; } - - /// - /// Request Time ... - /// - public DateTime RequestedOn { get; set; } - - /// - /// Response Time in Milliseconds ... - /// - public long ResponseTimeMs { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XApiKeyValidationRequest.cs - -namespace xIdentityModels.Models -{ - public class XApiKeyValidationRequest - { - public string ApiKey { get; set; } - public string ClientIP { get; set; } - public string RequiredScope { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XApiKeyValidationResult.cs - -using xModels.Dtos; -using System.Collections.Generic; - -namespace xIdentityModels.Models -{ - public class XApiKeyValidationResult - { - public string OwnerId { get; set; } - public int ApplicationId { get; set; } - public XPersonDto Owner {get; set; } = new(); - public IList Scopes {get; set;} = []; - public IList Errors { get; set; } = []; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XApplication.cs - -using System; -using xModels.Base; -using xIdentityModels.Constants; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace xIdentityModels.Models -{ - /// - /// an Application in xDashboard ... - /// - public class XApplication : XBaseIntIDEntity - { - /// - /// Name ... - /// - [Required] - [StringLength(255)] - public string Name { get; set; } - - /// - /// Descriptor ... - /// - [StringLength(1000)] - public string Description { get; set; } - - /// - /// Owner Id ... - /// - [Required] - [StringLength(255)] - public string OwnerId { get; set; } - - /// - /// Application Type ... - /// - public XApplicationType Type { get; set; } - - /// - /// Specified Application is Active or not ... - /// - public bool IsActive { get; set; } = true; - - /// - /// Application Create Time ... - /// - public DateTime CreatedOn { get; set; } - - /// - /// Application Update Type ... - /// - public DateTime UpdatedAt { get; set; } - - // - #region Navigation ... - /// - /// a Collection of ApiKeys which Related to this Application ... - /// - public virtual ICollection ApiKeys { get; set; } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XBannedDevice.cs - -using System; -using xModels.Base; -using xCommons.Extensions; -using xIdentityModels.Navigations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Models { - public class XBannedDevice : XBaseIntIDEntity { - public DateTime BannedOn { get; set; } - - public string DeviceStr { get; set; } - - [NotMapped] - public XDevice Device { - get { - return DeviceStr.FromJSON (); - } - set { - DeviceStr = value.ToJSON (); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XCreateApiKeyRequest.cs - -using System.Collections.Generic; - -namespace xIdentityModels.Models -{ - /// - /// Create Specified Api Key ... - /// - public class XCreateApiKeyRequest - { - public int? RateLimit {get; set;} = null; - public int? ExpirationMinutes {get; set;} = null; - public IEnumerable Scopes {get; set;} = null; - public IEnumerable AllowedIPs {get; set;} = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XLoginRequest.cs - -using xIdentityModels.Navigations; -using System.ComponentModel.DataAnnotations; - -namespace xIdentityModels.Models { - /// - /// Represent Requirements for Authenticationg a User - /// - public class XLoginRequest { - /// - /// how select an specific User - /// - /// an string value which represent how system select user such as: UserName, Email Address or MobileNumber - [Required] - public string UserSelectBy { get; set; } - - /// - /// user's password - /// - /// an string which represent user's pasword - [Required] - public string Password { get; set; } - - /// - /// user's device - /// - /// an instance of XDevice which represent user's device - public XDevice Device { get; set; } - - /// - /// user's language - /// - /// an string which represent user's language and locale, such as: en-US - public string Language { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XLoginResponse.cs - -using xIdentityModels.Dtos; - -namespace xIdentityModels.Models { - public class XLoginResponse : XTokenResponse { - public XUserProfileDto Profile { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XProfileUpdateRequest.cs - -using System; -using xIdentityModels.Constants; -using System.Collections.Generic; - -namespace xIdentityModels.Models { - public class XProfileUpdateRequest { - public string Email { get; set; } - public bool? EmailConfirmed { get; set; } - public string PhoneNumber { get; set; } - public bool? PhoneNumberConfirmed { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Avatar { get; set; } - public DateTime? DateOfBirth { get; set; } - public DateTime? CreationDate { get; set; } - public DateTime? LastLogin { get; set; } - public XGender? Gender { get; set; } - public ICollection Roles { get; set; } = new HashSet (); - public bool? IsEnable { get; set; } - public bool? IsBanned { get; set; } - public string Bio { get; set; } - public string CoverImage { get; set; } - public bool OpenToSearch { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XRotateApiKeyRequest.cs - -namespace xIdentityModels.Models -{ - /// - /// Rotate Specified Api Key ... - /// - public class XRotateApiKeyRequest - { - /// - /// New Expiration in Minutes ... - /// - public int? NewExpirationMinutes { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XToken.cs - -using xModels.Base; -using xCommons.Extensions; -using xIdentityModels.Constants; -using xIdentityModels.Navigations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Models { - public class XToken : XBaseIntIDEntity { - public string Token { get; set; } - public string Hash { get; set; } - public string UserSelectByParam { get; set; } - public string DeviceStr { get; set; } - public XAction Type { get; set; } - - [NotMapped] - public XDevice Device { - get { - return DeviceStr.FromJSON (); - } - - set { - DeviceStr = value.ToJSON (); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XTokenResponse.cs - -using System.ComponentModel.DataAnnotations; - -namespace xIdentityModels.Models { - public class XTokenResponse { - [Required] - public string AccessToken { get; set; } - public string RefreshToken { get; set; } - public long ExpiresAt { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XUserClaimsInfoDto.cs - -using System; -using System.Linq; -using xModels.Base; -using xCommons.Helpers; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Security.Claims; -using xIdentityModels.Constants; -using System.Collections.Generic; - -namespace xIdentityModels.Models -{ - public class XUserClaimsInfoDto : XBaseDto - { - // - #region Properties ... - public string AccessToken { get; } - public string RefreshToken { get; } - public long ExpiresAt { get; } - public string UserId { get; } - public string UserName { get; } - public string FirstName { get; } - public string LastName { get; } - public string Picture { get; } - public string Email { get; } - public string PhoneNumber { get; } - public XGender Gender { get; } - public bool IsBanned { get; } - public bool IsEnabled { get; } - public bool EmailConfirmed { get; } - public bool PhoneNumberConfirmed { get; } - public string Bio { get; set; } - public string CoverImage { get; set; } - public bool OpenToSearch { get; set; } - public long? ExpiredOn { get; } - public long? AuthenticatedOn { get; } - public DateTime? BrithDate { get; } - public IEnumerable Issuers { get; } = new HashSet(); - public IEnumerable Audiences { get; } = new HashSet(); - public IEnumerable ClientIds { get; } = new HashSet(); - public IEnumerable Scopes { get; } = new HashSet(); - public IEnumerable Roles { get; } = new HashSet(); - #endregion - - // - public XUserClaimsInfoDto() { } - - public XUserClaimsInfoDto( - string userid, - string username, - string firstname, - string lastname, - string avatar - ) - { - // - var isValid = - !userid.IsNullOrEmpty() && - !username.IsNullOrEmpty() && - !firstname.IsNullOrEmpty() && - !lastname.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - UserId = userid; - Picture = avatar; - UserName = username; - LastName = lastname; - FirstName = firstname; - } - - public XUserClaimsInfoDto( - string accessToken, - string refreshToken, - long expiresAt, - IEnumerable claims - ) - { - // - // refreshToken.IsNullOrEmpty () - if (claims.IsNull() || - accessToken.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Attach XLogin Properties ... - AccessToken = accessToken; - RefreshToken = refreshToken; - ExpiresAt = expiresAt; - - // - if (!claims.IsNull()) - { - // - UserId = claims.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? ""; - UserName = claims.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? ""; - FirstName = claims.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? ""; - LastName = claims.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? ""; - Picture = claims.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? ""; - Email = claims.FirstOrDefault(c => c.Type == XCustomClaims.Email)?.Value ?? null; - PhoneNumber = claims.FirstOrDefault(c => c.Type == XCustomClaims.PhoneNumber)?.Value ?? null; - - // - Bio = claims.FirstOrDefault(c => c.Type == XCustomClaims.Bio)?.Value ?? null; - CoverImage = claims.FirstOrDefault(c => c.Type == XCustomClaims.CoverImage)?.Value ?? null; - - // - var openToSearchStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.OpenToSearch)?.Value ?? null; - if (openToSearchStr.IsNullOrEmpty()) - { - OpenToSearch = false; - } - else - { - // - var openToSearch = false; - bool.TryParse(openToSearchStr, out openToSearch); - - // - OpenToSearch = openToSearch; - } - - // - // Handle Gender ... - var genders = ObjectHelper.ToEnumerableKeys(); - var genderStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.Gender).Value ?? null; - if (genderStr.IsNullOrEmpty()) - { - Gender = XGender.Male; - } - else - { - Gender = genderStr.GetValue(); - } - - // - // Handle IsBanned ... - var isBannedStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.IsBanned).Value ?? null; - if (isBannedStr.IsNullOrEmpty()) - { - IsBanned = false; - } - else - { - // - var isBanned = false; - Boolean.TryParse(isBannedStr, out isBanned); - - // - IsBanned = isBanned; - } - - // - // Handle IsEnabled ... - var isEnabledStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.IsEnabled).Value ?? null; - if (isEnabledStr.IsNullOrEmpty()) - { - IsEnabled = false; - } - else - { - // - var isEnabled = false; - Boolean.TryParse(isEnabledStr, out isEnabled); - - // - IsEnabled = isEnabled; - } - - // - // Handle Email Confirmed ... - var emailConfirmedStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.EmailVerified).Value ?? null; - if (emailConfirmedStr.IsNullOrEmpty()) - { - EmailConfirmed = false; - } - else - { - // - var emailConfirmed = false; - Boolean.TryParse(emailConfirmedStr, out emailConfirmed); - - // - EmailConfirmed = emailConfirmed; - } - - // - // Handle PhoneNumber Confirmed ... - var phoneNumberConfirmedStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.PhoneNumberVerified).Value ?? null; - if (phoneNumberConfirmedStr.IsNullOrEmpty()) - { - PhoneNumberConfirmed = false; - } - else - { - // - var phoneNumberConfirmed = false; - Boolean.TryParse(phoneNumberConfirmedStr, out phoneNumberConfirmed); - - // - PhoneNumberConfirmed = phoneNumberConfirmed; - } - - // - // Handle ExpiredOn ... - var expiredOnStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.ExpiredOn).Value ?? null; - if (expiredOnStr.IsNullOrEmpty()) - { - ExpiredOn = null; - } - else - { - // - long expiredOn = 0; - long.TryParse(expiredOnStr, out expiredOn); - - // - ExpiredOn = expiredOn; - } - - // - // Handle AuthenticatedOn ... - var authenticatedOnStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.AuthenticatedOn).Value ?? null; - if (authenticatedOnStr.IsNullOrEmpty()) - { - AuthenticatedOn = null; - } - else - { - // - long authenticatedOn = 0; - long.TryParse(authenticatedOnStr, out authenticatedOn); - - // - AuthenticatedOn = authenticatedOn; - } - - // - // Handle BrithDate ... - var brithDateStr = claims.FirstOrDefault(c => c.Type == XCustomClaims.BrithDate)?.Value ?? ""; - if (brithDateStr.IsNullOrEmpty()) - { - // BrithDate = null; - } - else - { - // - DateTime bDate; - DateTime.TryParse(brithDateStr, out bDate); - - // - BrithDate = bDate; - } - - // - // Collections ... - Issuers = claims.Where(c => c.Type == XCustomClaims.Issuer)? - .Select(c => c.Value) ?? new HashSet(); - Audiences = claims.Where(c => c.Type == XCustomClaims.Audience)? - .Select(c => c.Value) ?? new HashSet(); - ClientIds = claims.Where(c => c.Type == XCustomClaims.ClientId)? - .Select(c => c.Value) ?? new HashSet(); - Scopes = claims.Where(c => c.Type == XCustomClaims.Scope)? - .Select(c => c.Value) ?? new HashSet(); - Roles = claims.Where(c => c.Type == XCustomClaims.Role)? - .Select(c => c.Value) ?? new HashSet(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Models\XVerificationRequest.cs - -using System; -using xModels.Base; -using xCommons.Extensions; -using xIdentityModels.Navigations; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Models { - public class XVerificationRequest : XBaseIntIDEntity { - - [Required] - public string VerificationCode { get; set; } - - public int NumberOfTries { get; set; } - public DateTime LastTryOn { get; set; } - - [NotMapped] - public XActionRequestToken Request { - get { - return RequestStr.FromJSON (); - } - set { - RequestStr = value.ToJSON (); - } - } - - public string RequestStr { get; set; } - - [NotMapped] - public XDevice Device { - get { - return DeviceStr.FromJSON (); - } - set { - DeviceStr = value.ToJSON (); - } - } - - public string DeviceStr { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Navigations\XDevice.cs - -using xModels.Base; -using xCommons.Constants; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Navigations { - /// - /// Represent a Client Device which used by User - /// - public class XDevice : XBaseIntIDEntity { - /// - /// Operating System - /// - /// device operating system identifier - public string Os { get; set; } - /// - /// Operating System Version - /// - /// which version of operatin system is in use - public string OsVersion { get; set; } - /// - /// Device Browser - /// - /// the Browser identifier - public string Browser { get; set; } - /// - /// Browser Engine Agent - /// - /// browser engine Agent - public string UserAgent { get; set; } - /// - /// Type of client Device - /// - /// represent device type XDeviceType - public XDeviceType DeviceType { get; set; } - - // - #region User ... - /// - /// UserId - /// - /// Represent this Devie belong to which User Identifier - public string UserId { get; set; } - /// - /// User - /// - /// Represent Device User XUser - [ForeignKey (nameof (UserId))] - public virtual XUser User { get; set; } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Navigations\XFriendshipFollower.cs - -using xModels.Base; -using xIdentityModels.Constants; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Navigations { - /// - /// represent a Follower of specific User - /// - public class XFriendshipFollower : XBaseIntIDEntity { - /// - /// XFriendshipState - /// - /// state of Friendship at current moment XFriendshipState - public XFriendshipState State { get; set; } - - // - #region User ... - /// - /// UserId - /// - /// source User's Id - public string UserId { get; set; } - /// - /// User - /// - /// source User XUser - [ForeignKey (nameof (UserId))] - public virtual XUser User { get; set; } - #endregion - - // - #region Dest User ... - /// - /// DestId - /// - /// destination User's Id - public string DestId { get; set; } - /// - /// Dest - /// - /// dest User XUser - [ForeignKey (nameof (DestId))] - public virtual XUser Dest { get; set; } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Navigations\XFriendshipFollowing.cs - -using xModels.Base; -using xIdentityModels.Constants; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Navigations { - /// - /// represent a Following of specific User - /// - public class XFriendshipFollowing : XBaseIntIDEntity { - /// - /// XFriendshipState - /// - /// state of Friendship at current moment XFriendshipState - public XFriendshipState State { get; set; } - - // - #region User ... - /// - /// UserId - /// - /// source User's Id - public string UserId { get; set; } - /// - /// User - /// - /// source User XUser - [ForeignKey (nameof (UserId))] - public virtual XUser User { get; set; } - #endregion - - // - #region Dest User ... - /// - /// DestId - /// - /// destination User's Id - public string DestId { get; set; } - /// - /// Dest - /// - /// dest User XUser - [ForeignKey (nameof (DestId))] - public virtual XUser Dest { get; set; } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Navigations\XProfileImage.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace xIdentityModels.Navigations { - /// - /// Represent a User's Avatar Entity - /// - public class XProfileImage : XBaseIntIDEntity { - /// - /// UserId - /// - /// represent current Avatar belongs to which User - public string UserId { get; set; } - /// - /// User - /// - /// User instance XUser - [ForeignKey (nameof (UserId))] - public XUser User { get; set; } - /// - /// Name - /// - /// Avatar's file name - [Required] - [StringLength (255)] - public string Name { get; set; } - /// - /// Thumb - /// - /// Avatar's thumbnail file's name - [Required] - [StringLength (255)] - public string Thumb { get; set; } - /// - /// Path - /// - /// Avatar's Image path on Profile Server - [Required] - [StringLength (255)] - public string Path { get; set; } - /// - /// ThumbPath - /// - /// Avatar's Thumbnail Image path on Profile Service - [Required] - [StringLength (255)] - public string ThumbPath { get; set; } - /// - /// CreationDate - /// - /// Upload Time - public DateTime CreationDate { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityModels\Providers\XDefaultUserRoleHelper.cs - -using System.Linq; -using xCommons.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Interfaces; - -namespace xIdentityModels.Providers { - public class XDefaultUserRoleHelper : IXUserRoleHelper { - public bool canReadCriticalData (XUserClaimsInfoDto userInfo) { - return isInRole (userInfo, "admin"); - } - - public bool canDoDangerousAction (XUserClaimsInfoDto userInfo) { - return isInRole (userInfo, "admin"); - } - - public bool isInRole (XUserClaimsInfoDto userInfo, string role) { - return userInfo.Roles - .Any (r => - r.ToNormalString () == role.ToNormalString () - ); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xIdentityService-20261109_152622.txt b/Documents/GeneratedContext/xDashboard-xIdentityService-20261109_152622.txt deleted file mode 100644 index 9f230a1..0000000 --- a/Documents/GeneratedContext/xDashboard-xIdentityService-20261109_152622.txt +++ /dev/null @@ -1,13017 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Attributes\XApiKeyAccessAttribute.cs - -using System; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Models; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using xIdentityModels.Extensions; -using xIdentityService.Constants; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.Extensions.DependencyInjection; - -namespace xIdentityService.Attributes -{ - [AttributeUsage( - AttributeTargets.Class | AttributeTargets.Method, - AllowMultiple = false, - Inherited = true - )] - public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter - { - /// - /// Optional allowed scopes. If empty, no scope enforcement. - /// - public XApiKeyScope[] Scopes { get; set; } - - public XApiKeyAccessAttribute( - XApiKeyScope[] scopes = null - ) - { - // - if (!scopes.HasChild()) - { - scopes = [XApiKeyScope.Read]; - } - - // - Scopes = scopes; - } - - /// - /// Authorization Filtering ... - /// - /// - public void OnAuthorization(AuthorizationFilterContext context) - { - Task.FromResult(OnAuthorizationAsync(context)); - } - - /// - /// Handle Authorization Filtering Using Tasks ... - /// - /// - /// - /// - private async Task OnAuthorizationAsync( - AuthorizationFilterContext context, - CancellationToken cancellationToken = default - ) - { - // - // Access HttpContext ... - var http = context.HttpContext; - var error = XException.NotAuthorized.ToXError(); - var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); - - // - try - { - // - // Obtain the endpoint currently being executed - var endpointFeature = http.Features.Get(); - var endpoint = endpointFeature?.Endpoint; - if (endpoint.IsNull() || - endpointFeature.IsNull() - ) - { - // - error.Message = "Endpoint not Accessible ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Retrieve Identity Provider Service from DI ... - var identityService = http.RequestServices - .GetService(); - if (identityService.IsNull()) - { - // - error.Message = "Api Key Service not Registered ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Checking Header ... - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); - if (!http.Request.Headers.ContainsKey(apiKeyHeader)) - { - // - error.Message = "ApiKey not Exists ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Extract ApiKey from Header ... - var apiKey = http.Request.Headers[apiKeyHeader].ToString(); - if (apiKey.IsNullOrEmpty()) - { - // - error.Message = "ApiKey not Provided ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Extract Client IP ... - var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - var scopes = - !Scopes.HasChild() - ? string.Empty - : Scopes.ToListString(); - - // - // Prepare Validation Request ... - var validationRequest = new XApiKeyValidationRequest - { - ApiKey = apiKey, - ClientIP = clientIP, - RequiredScope = scopes - }; - - // - // Validating ApiKey ... - var validationResponse = identityService.ValidateApiKey( - request: validationRequest, - cancellationToken: cancellationToken - ) - .GetAwaiter() - .GetResult(); - if (validationResponse.Errors.HasChild()) - { - // - var message = validationResponse.Errors.ToListString(','); - error.Message = message; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Creating Claims ... - var claims = validationResponse.ToXClaims(); - - // - // Create Principal and Ticket ... - var identity = new ClaimsIdentity(claims, apiKeyAuthentication); - var principal = new ClaimsPrincipal(identity); - - // - http.User = principal; - } - catch - { - // - error.Message = "ApiKey authorization failed ..."; - context.Result = new UnauthorizedObjectResult(error); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Configuration\XIdentityServiceConfiguration.cs - -using xIdentityService.Constants; - -namespace xIdentityService.Configuration { - public partial class XIdentityServiceConfiguration { - public string Authority { get; set; } - public string ApiName { get; set; } - public string ApiSecret { get; set; } - public string ClientId { get; set; } - public string ClientSecret { get; set; } - public string XPoweredValue { get; set; } - public XTokenType TokenType { get; set; } - public string XRevisionSecretKey { get; set; } - public int DefaultClientTimeout { get; set; } = 360; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Configuration\XProxyConfiguration.cs - -using xModels.Base; -using System.Collections.Generic; - -namespace xIdentityService.Configuration { - /// - /// XProxy Middleware Configuration ... - /// - public class XProxyConfiguration { - /// - /// Proxy Host Address for Clients Which Use XProxy Server ... - /// - /// - public string Host { get; set; } - - /// - /// if EnableXPoweredByAthorization property setted to true, this property determines - /// the header must be this value ... - /// - /// - public string XPoweredValue { get; set; } - - /// - /// Determines Proxy Http Handler Check SSL or not ... - /// - /// - public bool DisableSSLCheck { get; set; } - - /// - /// Determines Http Client Handler Allow Auto Redirect or not ... - /// - /// - public bool AllowAutoRedirect { get; set; } - - /// - /// Determines Proxy Server Log Received Requests or not ... - /// - /// - public bool EnableLogging { get; set; } - - /// - /// DefineRoutes for Handling ... - /// - /// - public HashSet Routes { get; set; } - } - - /// - /// Describe a Proxy Route ... - /// - public class XProxyRouteDescriptor : XBaseDescriptor { - /// - /// Determines which route can handled for Proxyfing ... - /// - /// - public string Route { get; set; } - - /// - /// Determines Proxy Server Handle Athorization or not ... - /// - /// - public bool EnableAuthorization { get; set; } - - /// - /// Determines Which Scopes allowed to this route if authorizations enabled ... - /// - /// - public HashSet AllowedScopes { get; set; } - - /// - /// Determines Which Roles allowed to this route if authorizations enabled ... - /// - /// - public HashSet AllowedRoles { get; set; } - - /// - /// Determines XProxy Can Check XPowered By Authorization or not ... - /// - /// - public bool EnableXPoweredByAthorization { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\ConfigurationNodeNames.cs - -namespace xIdentityService.Constants { - public partial struct ConfigurationNodeNames { - public const string XPROXY_CONFIGURATION_NODE_NAME = "ProxyConfiguration"; - public const string IDENTITY_SERVICE_NODE_NAME = "IdentityServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XApiAccountEndpoint.cs - -using xExceptions.Attributes; - -namespace xIdentityService.Constants -{ - public enum XApiAccountEndpoint - { - // - #region Authentication ... - [StringValue("Account/DiscoveryDocument")] - DiscoveryDocument, - - [StringValue("Account/RequestScopeAccessToken")] - RequestScopeAccessToken, - - [StringValue("Account/Authenticate")] - Authenticate, - - [StringValue("Account/Login")] - Login, - - [StringValue("Account/RefreshTokens")] - RefreshTokens, - - [StringValue("Account/ChangePassword")] - ChangePassword, - - [StringValue("Account/ResetPassword")] - ResetPassword, - #endregion - - // - #region Proile ... - [StringValue("Account/Profile/{ids}/GetNames")] - GetNames, - - [StringValue("Account/Profile/GetNameIds")] - GetNameIds, - - [StringValue("Account/Profile/{userSelectByParam}")] - GetProfile, - - [StringValue("Account/Profile/Query")] - QueryProfiles, - - [StringValue("Account/Profile/Avatars/Query/{userSelectByParam}")] - QueryAvatars, - - [StringValue("Account/Profile/Update/{userSelectByParam}")] - UpdateProfile, - - [StringValue("Account/Profile/{userSelectByParam}")] - FullUpdateProfile, - - [StringValue("Account/Profile/Avatar")] - AddAvatar, - - [StringValue("Account/Profile/Avatars")] - AddAvatars, - - [StringValue("Account/Profile/Avatars/{ids}")] - RemoveAvatars, - - [StringValue("Account/Profile/Avatars/{id}/Set")] - SetAvatar, - #endregion - - // - #region Search ... - [StringValue("Account/OpenToSearch/Query")] - QueryOpenToSearchProfiles, - #endregion - - // - #region Registration ... - [StringValue("Account/CanRegisterUserName/{userName}")] - CanRegisterUserName, - - [StringValue("Account/CanRegisterMobileNumber/{mobileNumber}")] - CanRegisterMobileNumber, - - [StringValue("Account/CanRegisterEmail/{email}")] - CanRegisterEmail, - - [StringValue("Account/IsConfirmedEmail")] - IsConfirmedEmail, - - [StringValue("Account/IsConfirmedMobile")] - IsConfirmedMobile, - - [StringValue("Account/ConfirmRegistration")] - ConfirmRegistration, - - [StringValue("Account/ConfirmMobileNumber")] - ConfirmMobileNumber, - - [StringValue("Account/ConfirmEmailAddress")] - ConfirmEmailAddress, - - [StringValue("Account/RequestConfirmMobile")] - RequestConfirmMobile, - - [StringValue("Account/RequestConfirmEmail")] - RequestConfirmEmail, - - [StringValue("Account/RequestResetPassword")] - RequestResetPassword, - - [StringValue("Account/RequestConfirmRegistration")] - RequestConfirmRegistration, - - [StringValue("Account/InviteUser")] - InviteUser, - - [StringValue("Account/RequestRegistration")] - RequestRegistration, - - [StringValue("Account/AddAccountInfo")] - AddAccountInfo, - - [StringValue("Account/AttachProfileImage")] - AttachProfileImage, - - [StringValue("Account/FinishRegistration")] - FinishRegistration, - #endregion - - // - #region Friendship ... - [StringValue("Account/Friendship/{destUser}/Follow")] - Follow, - - [StringValue("Account/Friendship/{destUser}/Cancel")] - Cancel, - - [StringValue("Account/Friendship/{destUser}/UnFollowFollower")] - UnFollowFollower, - - [StringValue("Account/Friendship/{destUser}/UnFollowFollowing")] - UnFollowFollowing, - - [StringValue("Account/Friendship/{destUser}/Block")] - Block, - - [StringValue("Account/Friendship/{destUser}/UnBlock")] - UnBlock, - - [StringValue("Account/Friendship/{destUser}/AcceptRequest")] - AcceptRequest, - - [StringValue("Account/Friendship/{destUser}/RejectRequest")] - RejectRequest, - - [StringValue("Account/Friendship/{destUser}/FriendshipInfo")] - FriendshipInfo, - - [StringValue("Account/Friendship/{destUser}/IsFollower")] - IsFollower, - - [StringValue("Account/Friendship/{destUser}/FollowerState")] - FollowerState, - - [StringValue("Account/Friendship/{destUser}/Follower")] - Follower, - - [StringValue("Account/Friendship/Followers")] - Followers, - - [StringValue("Account/Friendship/AllFollowers")] - AllFollowers, - - [StringValue("Account/Friendship/FollowersList")] - FollowersList, - - [StringValue("Account/Friendship/QueryFollowers")] - QueryFollowers, - - [StringValue("Account/Friendship/{destUser}/IsFollowing")] - IsFollowing, - - [StringValue("Account/Friendship/{destUser}/FollowingState")] - FollowingState, - - [StringValue("Account/Friendship/{destUser}/Following")] - Following, - - [StringValue("Account/Friendship/Followings")] - Followings, - - [StringValue("Account/Friendship/AllFollowings")] - AllFollowings, - - [StringValue("Account/Friendship/FollowingsList")] - FollowingsList, - - [StringValue("Account/Friendship/QueryFollowings")] - QueryFollowings, - #endregion - - // - #region Admin ... - [StringValue("Account/Ban")] - Ban, - - [StringValue("Account/UnBan")] - UnBan, - - [StringValue("Account/IsBanned/{userSelectByParam}")] - IsBanned, - #endregion - - // - #region Open Actions ... - [StringValue("Account/Open")] - Open, - #endregion - - // - #region Applications ... - // - #region Application ... - [StringValue("Applications")] - CreateApplication, - - [StringValue("Applications/{id}")] - UpdateApplication, - - [StringValue("Applications/{id}")] - RemoveApplication, - - [StringValue("Applications/{id}")] - GetApplication, - - [StringValue("Applications")] - GetAllApplications, - - [StringValue("Applications/Query")] - QueryApplications, - #endregion - - // - #region ApiKey ... - [StringValue("Applications/ApiKeys/{id}")] - GetApiKey, - - [StringValue("Applications/ApiKeys/{id}")] - RemoveApiKey, - - [StringValue("Applications/ApiKeys/{id}")] - UpdateApiKey, - - [StringValue("Applications/ApiKeys")] - GetAllApiKeys, - - [StringValue("Applications/ApiKeys/Query")] - QueryApiKeys, - #endregion - - // - #region ApiKeyUsage ... - [StringValue("Applications/ApiKeys/Usages")] - AddApiKeyUsage, - - [StringValue("Applications/ApiKeys/Usages/{id}")] - GetApiKeyUsage, - - [StringValue("Applications/ApiKeys/Usages/{id}")] - RemoveApiKeyUsage, - - [StringValue("Applications/ApiKeys/Usages/{id}")] - UpdateApiKeyUsage, - - [StringValue("Applications/Usages")] - GetAllApiKeyUsages, - - [StringValue("Applications/Usages/Query")] - QueryApiKeyUsages, - #endregion - - // - #region Custom ... - [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Show")] - ShowApiKey, - - [StringValue("Applications/{applicationId}/ApiKeys/Create")] - CreateApiKey, - - [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")] - RemoveApiKeyCustom, - - [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")] - RotateApiKey, - - [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Revoke")] - RevokeApiKey, - - [StringValue("Applications/{applicationId}/ApiKeys")] - GetApiKeys, - - [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Usages")] - GetApiKeyUsages, - - [StringValue("Applications/ApiKeys/Validate")] - ValidateApiKey, - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XAuthenticationScheme.cs - -using xExceptions.Attributes; - -namespace xIdentityService.Constants { - public enum XAuthenticationScheme { - [StringValue ("token")] - XToken, - [StringValue ("introspection")] - XIntrospection, - [StringValue("XApiKey")] - XApiKey, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XHeader.cs - -using xExceptions.Attributes; - -namespace xIdentityService.Constants -{ - /// - /// All Available Headers ... - /// - public enum XHeader - { - /// - /// Hub Connection ID Header Keys ... - /// - [StringValue("requestID")] - ConnectionId, - - /// - /// Api Key Header Key ... - /// - [StringValue("X-Api-Key")] - ApiKey, - - /// - /// Checksum Digest Header Key ... - /// - [StringValue("X-Check-Sum")] - ChecksumDigest, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XParam.cs - -using xExceptions.Attributes; - -namespace xIdentityService.Constants { - public enum XParam { - [StringValue ("Content-Type")] - XContentType, - - [StringValue ("{boundary}")] - XBoundary, - - [StringValue ("{userSelectByParam}")] - XUserSelectByParam, - - [StringValue ("{destUser}")] - XDestUser, - - [StringValue ("{id}")] - XId, - - [StringValue ("{ids}")] - XIds, - - [StringValue ("Origin")] - XOrigin, - - [StringValue ("{userName}")] - XUserName, - - [StringValue ("{mobileNumber}")] - XMobileNumber, - - [StringValue ("{email}")] - XEmail, - - [StringValue ("role")] - XRole, - - [StringValue ("forceRole")] - XForceRole, - - [StringValue ("IsRefreshed")] - XIsRefreshed, - - [StringValue ("file")] - XFile, - - [StringValue ("files")] - XFiles, - - [StringValue ("actionToken")] - XActionToken, - - [StringValue ("request")] - XRequest, - - [StringValue ("scope")] - XScope, - - [StringValue("{apiKeyId}")] - XApiKeyId, - - [StringValue("{applicationId}")] - XApplicationId, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XProxyConstants.cs - -namespace xIdentityService.Constants { - public struct XProxyConstants { - public const string XPROXY_HTTP_CLIENT = "XProxyHttpClient"; - public const string XPROXY_FORWARD_HEADER = "xForwardHeader"; - public const string XPROXY_ACCEPTED_HEADERS = "xAcceptedHeaders"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XResponseContentTypes.cs - -namespace xIdentityService.Constants { - public struct XResponseContentTypes { - public const string HTML = "text/html"; - public const string JSON = "application/json"; - public const string JavaScript = "text/javascript"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XTokenType.cs - -namespace xIdentityService.Constants { - public enum XTokenType { - // - // Summary: - // Self-contained Json Web Token - Jwt, - // - // Summary: - // Reference token - Reference - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseAccountController.cs - -using System; -using xModels.Dtos; -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using IdentityModel.Client; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Extensions; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xIdentityService.Controllers -{ - [AllowAnonymous] - [RequireXPowered(true)] - public abstract class XBaseAccountController : XBaseIdentityController - { - protected XBaseAccountController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { } - - // - #region Authentication Actions ... - /// - /// Retrieve OAuth Discovery Document - /// - /// an instance of DiscoveryDocumentResponse - [AllowAnonymous] - [RequireXPowered] - [HttpGet("DiscoveryDocument")] - public virtual async Task> GetDiscoveryDocument() - { - // - try - { - // - var result = await IdentityProvider - .RequestDiscoveryDocument(); - - // - // Ceck Response Result ... - if (result.IsError) - { - XException.InvalidConfiguration.Throw(); - } - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Authenticate User - /// - /// - /// Sample request: - /// - /// { - /// "password": "", - /// "userSelectBy": "", - /// } - /// - /// - /// User Login Required Info, an instance of XLoginRequest - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("Authenticate")] - public virtual async Task> Authenticate( - [FromBody] XLoginRequest model - ) - { - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroupAsync(); - - // - var result = await IdentityProvider - .Authenticate(model); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Authenticate User - /// - /// - /// Sample request: - /// - /// { - /// "language": "fa-IR" - /// "password": "", - /// "userSelectBy": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// User Login Required Info, an instance of XLoginRequest - /// an instance of XLoginResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("Login")] - public virtual async Task> Login( - [FromBody] XLoginRequest model - ) - { - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull( - model, - model.Device) - .AddNotEmpty( - model.Language, - model.UserSelectBy, - model.Password - ) - .ValidateGroupAsync(); - - // - var result = await IdentityProvider - .Login(model); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Refresh Expired Tokens - /// - /// - /// in addition to AccessToken, you had to pass RefreshToken due to Headers - /// - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RefreshTokens")] - public virtual async Task> RefreshTokens() - { - // - try - { - // - // Retrieve Toke Response ... - var model = await RetrieveTokensAsXTokenResponse(); - - // - // Validate Args ... - ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.AccessToken, - model.RefreshToken) - .ValidateGroup(); - - // - var result = await IdentityProvider - .RefreshTokens(model); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Open Actions ... - /// - /// Retriev User Info Based on Open Actions ... - /// - /// - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("GetUserInfo")] - public virtual async Task> GetUserInfo( - [FromHeader] string token, - [FromQuery] string request - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(token) - .AddNotEmpty(request) - .ValidateGroupAsync(); - - // - var result = await IdentityProvider.GetUserInfo( - token: token, - request: request - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retriev User Info Based on Open Actions ... - /// - /// - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("GetUserInfoByDevice")] - public virtual async Task> GetUserInfoByDevice( - [FromQuery] string userSelectByParam, - [FromBody] XDeviceDto device - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(userSelectByParam) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - var result = await IdentityProvider.GetUserInfo( - userSelectByParam: userSelectByParam, - device: device - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Registration ... - /// - /// Check a UserName is Available For Registration or not - /// - /// an string value which represent desired username - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet ("CanRegisterUserName/{userName?}")] - public virtual async Task> CanRegisterUserName ( - [FromRoute] string userName - ) { - // - // Do Action ... - try { - // - // Validate Args ... - ValidationProvider.NotEmpty (userName); - - // - // Validate Type ... - var type = userName.GetUserSelectByType (); - if (type != XUserSelectBy.Username) { - XException.InvalidArgs.Throw (); - } - - // - var result = await IdentityProvider - .CanRegister (userName); - - // - // Return Result - return Ok (result); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - - // - return result; - } - } - - /// - /// Check a Mobile Number is Available For Registration or not - /// - /// an string value which represent desired mobile number - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet ("CanRegisterMobileNumber/{mobileNumber?}")] - public virtual async Task> CanRegisterMobileNumber ( - [FromRoute] string mobileNumber - ) { - // - // Do Action ... - try { - // - // Validate Args ... - ValidationProvider.NotEmpty (mobileNumber); - - // - // Validate Type ... - var type = mobileNumber.GetUserSelectByType (); - if (type != XUserSelectBy.MobileNumber) { - XException.InvalidArgs.Throw (); - } - - // - var result = await IdentityProvider - .CanRegister (mobileNumber); - - // - // Return Result - return Ok (result); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - - // - return result; - } - } - - /// - /// Check a Email Address is Available For Registration or not - /// - /// an string value which represent desired email address - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet ("CanRegisterEmail/{email?}")] - public virtual async Task> CanRegisterEmail ( - [FromRoute] string email - ) { - // - // Do Action ... - try { - // - // Validate Args ... - ValidationProvider.NotEmpty (email); - - // - // Validate Type ... - var type = email.GetUserSelectByType (); - if (type != XUserSelectBy.Email) { - XException.InvalidArgs.Throw (); - } - - // - var result = await IdentityProvider - .CanRegister (email); - - // - // Return Result - return Ok (result); - } catch (Exception ex) { - // - var result = GetExceptionActionResult (ex); - - // - return result; - } - } - - /// - /// Recieve some Basic Informations and Start Registration Proccess - /// if they Valid - /// - /// Registration Proccess Starts with Invoking this Action - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - FirstName: user's FirstName. - /// - LastName: user's LastName. - /// - DateOfBirth: user's dob date. - /// - MobileNumber: user's MobileNumber optional. - /// - Email: user's Email optional. - /// - ActionToken: user's requested action token for this action (if user invited). - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "firstName": "", - /// "lastName": "", - /// "dateOfBirth": "", - /// "email": "", - /// "mobileNumber": "", - /// "actionToken": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestRegistration")] - public virtual async Task> RequestRegistration ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.FirstName, - model.LastName) - .AddNotNull ( - model.Device, - model.DateOfBirth) - .ValidateGroupAsync (); - - // - // Get Request ... - var result = await IdentityProvider - .RequestRegistration ( - model - ); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - - // - return exResult; - } - } - - /// - /// Add User Account Informations - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - UserName: user name. - /// - Password: assigne password. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userName": "", - /// "password": "", - /// "actionToken": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("AddAccountInfo")] - public virtual async Task> AddAccountInfo ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.UserName, - model.Password) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - var result = await IdentityProvider - .AddAccountInfo ( - model - ); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Upload and Attach a Profile Image for User. this is an Optional Step - /// - /// user's requested action token - /// an instance of IFormFile for user's Avatar - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("AttachProfileImage")] - public virtual async Task> AttachProfileImage ( - [FromForm] string actionToken, [FromForm] IFormFile file - ) { - // - // Do Action ... - try { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty (actionToken) - .AddNotNull (file) - .ValidateGroupAsync (); - - // - var result = await IdentityProvider - .AttachProfileImage ( - actionToken, - file - ); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Finish Registrationn Proccess - /// - /// - /// for this action you have to provide: - /// - a proper User Identifier such as: (UserId, UserName, Email or MobileNumber). - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Password: assigne password. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userName": "", - /// "password": "", - /// "returnUrl": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("FinishRegistration")] - public virtual async Task FinishRegistration ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - var userSelectByParam = IdentityProvider - .GetUserSelectByParam (model); - ValidationProvider - .NotEmpty (userSelectByParam); - - // - // Get Request ... - await IdentityProvider - .FinishRegistration (model); - - // - return Ok (); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - - // - return exResult; - } - } - - /// - /// Request Registration Confirm - /// - /// - /// for this action you have to provide: - /// - a UserSelectedBy identifier which represet User. - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Confirm Registration URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userId": "" - /// "password": "", - /// "returnUrl": "http://localhost/confirm", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestConfirmRegistration")] - public virtual async Task RequestConfirmRegistration ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = model.GetUserSelectByParam (); - ValidationProvider.NotEmpty (userSelectByParam); - - // - await IdentityProvider - .RequestConfirmRegistration (model); - - // - return Ok (); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Confirm Registration - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("ConfirmRegistration")] - public virtual async Task ConfirmRegistration ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.ReturnUrl - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - await IdentityProvider - .ConfirmRegistration (model); - - // - return Ok (); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Request For Mobile Number Change/Confirm - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - MobileNumber: which phone number is going to confirm. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "", - /// "mobileNumber": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestConfirmMobile")] - public virtual async Task> RequestConfirmMobile ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.MobileNumber) - .AddNotNull (model.Device) - .AddMobileNumber (model.MobileNumber) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : [ - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - ]); - - // - // Get Request ... - var result = await IdentityProvider - .RequestConfirmMobile (model); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Confirm Requested Mobile Number - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - MobileVerificationCode: a verification code which produced due Request Action. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "mobileVerificationCode": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("ConfirmMobileNumber")] - public virtual async Task> ConfirmMobileNumber ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.MobileVerificationCode, - model.ActionToken - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - var result = await IdentityProvider - .ConfirmMobileNumber (model); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Request For Email Address Change/Confirm - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - Email: which email address is going to confirm. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "", - /// "email": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestConfirmEmail")] - public virtual async Task> RequestConfirmEmail ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Email, - model.Password) - .AddNotNull (model.Device) - .AddEmailAddress (model.Email) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // Get Request ... - var result = await IdentityProvider - .RequestConfirmEmail (model); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Confirm Requested Email Address - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - EmailVerificationCode: a verification code which produced due Request Action. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "emailVerificationCode": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("ConfirmEmailAddress")] - public virtual async Task> ConfirmEmailAddress ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.EmailVerificationCode, - model.ActionToken - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - var result = await IdentityProvider - .ConfirmEmailAddress (model); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Request Reset Password Action - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application ResetPassword URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "returnUrl": "http://localhost/reset-password", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("RequestResetPassword")] - public virtual async Task> RequestResetPassword ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // Get Request ... - var result = await IdentityProvider - .RequestResetPassword (model); - - // - return Ok (result - .ToDynamicObject ()); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - - /// - /// Reset a User's Password - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - NewPassword: user's new password to change. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "", - /// "newPassword": "", - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost ("ResetPassword")] - public virtual async Task ResetPassword ( - [FromBody] XActionRequest model - ) { - // - // Do Action ... - try { - // - // Validate Args ... - if (!ModelState.IsValid) { - XException.InvalidArgs.Throw (); - } - await ValidationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.NewPassword, - model.ReturnUrl) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - // Get Request ... - await IdentityProvider - .ResetPassword (model); - - // - return Ok (); - } catch (Exception ex) { - // - var exResult = GetExceptionActionResult (ex); - return exResult; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityApiController.cs - -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xIdentityService.Controllers -{ - /// - /// Base Identity Api Controller - /// - [ApiController] - [RequireXPowered(true)] - [Route("api/[controller]")] - [Produces("application/json")] - public abstract class XBaseIdentityApiController : XBaseIdentityController - { - protected XBaseIdentityApiController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityApiV1Controller.cs - -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xIdentityService.Controllers -{ - /// - /// Base Identity Api V1 Controller - /// - [ApiController] - [ApiVersion("1.0")] - [RequireXPowered(true)] - [Route("api/v{version:apiVersion}/[controller]")] - public abstract class XBaseIdentityApiV1Controller : XBaseIdentityApiController - { - protected XBaseIdentityApiV1Controller( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityController.cs - -using xModels.Dtos; -using xCommons.Constants; -using xCommons.Providers; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityService.Constants; -using xIdentityModels.Extensions; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authentication; - -namespace xIdentityService.Controllers -{ - public abstract class XBaseIdentityController : XBaseController - { - // - public IXIdentityProvider IdentityProvider { get; } - - protected XBaseIdentityController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - IdentityProvider = identityProvider; - } - - // - #region NonActions ... - /// - /// Retrieve Connection ID for Hubs ... - /// - /// - [NonAction] - public string GetConnectionId() - { - // - var result = ""; - - // - var headerKey = XHeader.ConnectionId.GetStringValue(); - - // - // Check if Connection ID is Provided ... - if (Request.Headers.ContainsKey(headerKey)) - { - result = Request.Headers[headerKey]; - } - - // - return result; - } - - /// - /// Extract Checksum From Headers ... - /// - /// - [NonAction] - public string GetRequestChecksum() - { - // - var result = string.Empty; - - // - var headerKey = XHeader.ChecksumDigest.GetStringValue(); - - // - // Check if Connection ID is Provided ... - if (Request.Headers.ContainsKey(headerKey)) - { - result = Request.Headers[headerKey]; - } - - // - return result; - } - - /// - /// Extract ApiKey From Headers ... - /// - /// - [NonAction] - public string GetRequestApiKey() - { - // - var result = string.Empty; - - // - var headerKey = XHeader.ApiKey.GetStringValue(); - - // - // Check if Connection ID is Provided ... - if (Request.Headers.ContainsKey(headerKey)) - { - result = Request.Headers[headerKey]; - } - - // - return result; - } - - /// - /// Retrieve User Identifier Base on XActionRequest - /// - /// - /// - /// - /// - [NonAction] - public string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(model); - - // - var result = IdentityProvider.GetUserSelectByParam( - model, - forceNotNull, - excludes - ); - - // - return result; - } - - /// - /// Retrieve Access Token - /// - /// - [NonAction] - public async Task GetAccessToken() - { - // - var accessToken = Request.Headers[XAuthorization.Header].ToString(); - if (accessToken.IsNullOrEmpty()) - { - // - accessToken = await HttpContext - .GetTokenAsync(XAuthorization.AccessToken); - } - - // - if (accessToken - .ToNormalString() - .Contains(XAuthorization.TokenIdentifier - .ToNormalString())) - { - // - accessToken = accessToken - .Remove(0, XAuthorization.TokenIdentifier.Length); - } - - // - return accessToken; - } - - /// - /// Retrieve Refresh Token - /// - /// - [NonAction] - public async Task GetRefreshToken() - { - // - var refreshToken = Request.Headers[XAuthorization.RefreshToken].ToString(); - if (refreshToken.IsNullOrEmpty()) - { - // - refreshToken = await HttpContext - .GetTokenAsync(XAuthorization.RefreshToken); - } - - // - return refreshToken; - } - - /// - /// Retrieve Access Token Expiration Date - /// - /// - [NonAction] - public async Task GetTokenExpiresAt() - { - // - var expiresAtStr = Request.Headers[XAuthorization.ExpiresAt].ToString(); - if (expiresAtStr.IsNullOrEmpty()) - { - // - expiresAtStr = await HttpContext - .GetTokenAsync(XAuthorization.ExpiresAt); - } - - // - var expiresAt = expiresAtStr.ConvertTo(); - - // - return expiresAt; - } - - /// - /// Retrieve All Required Tokens - /// - /// - [NonAction] - public async Task RetrieveTokensAsXLoginResponse() - { - // - var accessToken = await GetAccessToken(); - var refreshToken = await GetRefreshToken(); - var expiresAt = await GetTokenExpiresAt(); - - // - return new XLoginResponse - { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrieve All Required Tokens - /// - /// - [NonAction] - public async Task RetrieveTokensAsXTokenResponse() - { - // - var accessToken = await GetAccessToken(); - var refreshToken = await GetRefreshToken(); - var expiresAt = await GetTokenExpiresAt(); - - // - return new XTokenResponse - { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrive UserInfo - /// - /// - [NonAction] - public async Task GetUserInfo() - { - // - var claims = User.Claims ?? null; - if (!claims.HasChild()) - { - return null; - } - - // - var xTokens = await RetrieveTokensAsXTokenResponse(); - var result = new XUserClaimsInfoDto( - xTokens.AccessToken, - xTokens.RefreshToken, - xTokens.ExpiresAt, - User.Claims - ); - - // - return result; - } - - /// - /// Validate User Authenticated and Retrieve User Info - /// - /// - [NonAction] - public async Task ValidateAndGetUserInfo() - { - // - if (!User.Identity.IsAuthenticated) - { - XException.NotAuthorized.Throw(); - } - - // - var result = await GetUserInfo(); - if (result.IsNull()) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - - /// - /// Get Authenticated ApiKey Person ... - /// - /// - [NonAction] - public XPersonDto GetApiKeyPerson() - { - // - var result = User.ExtractApiKeyUser(); - return result; - } - - /// - /// Validate and Get Authenticated ApiKey Person ... - /// - /// - [NonAction] - public XPersonDto ValidateAndGetApiKeyPerson() - { - // - var result = User.ExtractApiKeyUser(); - if (result.IsNullOrDefault()) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - - /// - /// Get Authenticated JWT Person ... - /// - /// - [NonAction] - public XPersonDto GetAuthenticatedPerson() - { - // - var result = User.ExtractAuthenticatedUser(); - return result; - } - - /// - /// Validate and Get Authenticated JWT Person ... - /// - /// - [NonAction] - public XPersonDto ValidateAndGetAuthenticatedPerson() - { - // - var result = User.ExtractAuthenticatedUser(); - if (result.IsNullOrDefault()) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseTestIdentityController.cs - -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using xIdentityService.Interfaces; -using xIdentityService.Attributes; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; - -namespace xIdentityService.Controllers -{ - public abstract class XBaseTestIdentityController : XBaseIdentityController - { - protected XBaseTestIdentityController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base(logger, appConfiguration, identityProvider, validationProvider) - { } - - // - #region ApiKey Actions ... - /// - /// a simple Hello for Accessing ApiKey Authorization ... - /// - /// - [XApiKeyAccess] - [AllowAnonymous] - [RequireXPowered] - [HttpGet("HiApiKeyAccess")] - public ActionResult HiApiKeyAccess() - { - // - var result = $"Hi ApiKey Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Read Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("HiApiKeyReadAccess")] - [XApiKeyAccess(Scopes = [XApiKeyScope.Read])] - public ActionResult HiApiKeyReadAccess() - { - // - var result = $"Hi ApiKey Read Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Write Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("HiApiKeyWriteAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Write])] - public ActionResult HiApiKeyWriteAccess() - { - // - var result = $"Hi ApiKey Write Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Manage Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("HiApiKeyManageAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Manage])] - public ActionResult HiApiKManageAccess() - { - // - var result = $"Hi ApiKey Manage Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Admin Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("HiApiKeyAdminAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Admin])] - public ActionResult HiApiKeyAdminAccess() - { - // - var result = $"Hi ApiKey Admin Access, is Passed ..."; - - // - return Ok(result); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\DI\XDIHelperExtension.cs - -using System; -using xCommons.Extensions; -using xCommons.Authorization; -using Microsoft.AspNetCore.Http; -using xIdentityService.Security; -using xIdentityService.Constants; -using xIdentityService.Providers; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using xIdentityService.Configuration; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using IdentityModel.AspNetCore.OAuth2Introspection; - -namespace xIdentityService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Extract Module Configuration Structure from IConfiguration interface - /// - /// - /// - public static XIdentityServiceConfiguration GetXIdentityServiceConfiguration(this IConfiguration config) - { - // - var xIdentityServiceConfigSection = config.GetSection(ConfigurationNodeNames.IDENTITY_SERVICE_NODE_NAME); - return xIdentityServiceConfigSection.Get(); - } - - /// - /// Register Service and All it's Requirements - /// - /// - /// - /// - public static void AddXIdentityService( - this IServiceCollection services, - IConfiguration configuration, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - { - // - var identityConfiguration = configuration.GetXIdentityServiceConfiguration(); - AddIdentityService( - services, - identityConfiguration, - lifeTime - ); - } - - /// - /// Register Service and All it's Requirements - /// - /// - /// - /// - public static void AddXIdentityService( - this IServiceCollection services, - XIdentityServiceConfiguration configuration, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - { - AddIdentityService(services, configuration, lifeTime); - } - - /// - /// Register Custome Token Provider - /// - /// - /// - /// - public static void AddXTokenProvider( - this IServiceCollection services, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - where T : IXTokenProvider - { - // - Console.WriteLine("IdentityService: Add Custom Token Provider ..."); - services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(T), lifeTime)); - } - - /// - /// Register Person Service ... - /// - /// - /// - public static void AddXPersonService( - this IServiceCollection source, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - { - source.Add(new ServiceDescriptor(typeof(IXPersonService), typeof(XPersonService), lifeTime)); - Console.WriteLine("IdentityService: Add PersonService ..."); - } - - /// - /// Register Policy Handler Service ... - /// - /// - public static void AddXPolicyHandler( - this IServiceCollection source - ) - { - source.AddSingleton(); - } - - /// - /// Use Authentication - /// - /// - public static void UseXIdentityService(this IApplicationBuilder app) - { - app.UseAuthentication(); - } - - // - #region Private ... - private static void AddIdentityService( - this IServiceCollection services, - XIdentityServiceConfiguration config, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - { - // - services.AddSingleton(config); - - // - // Register Policy Handler ... - services.AddXPolicyHandler(); - - // - var builder = services - .AddAuthentication(XAuthenticationScheme.XToken.GetStringValue()); - - // - // Add JWT Handler ... - builder.AddJwtBearer( - XAuthenticationScheme.XToken.GetStringValue(), options => - { - // - options.Authority = config.Authority; - options.TokenValidationParameters.ValidateAudience = false; - options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" }; - - // - options.ForwardDefaultSelector = context => - { - // - var path = context.Request.Path.Value; - - // - var fromHeader = TokenRetrieval.FromAuthorizationHeader(); - var fromQuery = TokenRetrieval.FromQueryString(); - var bearerToken = fromHeader(context.Request) ?? fromQuery(context.Request); - - // - var result = XAuthenticationScheme.XToken.GetStringValue(); - if (!bearerToken.IsNull() && !bearerToken.Contains(".")) - { - result = XAuthenticationScheme.XIntrospection.GetStringValue(); - } - - // - return result; - }; - }); - - // - // Add OAuthIntrospect ... - builder.AddOAuth2Introspection( - XAuthenticationScheme.XIntrospection.GetStringValue(), options => - { - // - options.Authority = config.Authority; - options.ClientId = config.ApiName; - options.ClientSecret = config.ClientSecret; - - // - options.TokenRetriever = new Func(req => - { - // - var fromHeader = TokenRetrieval.FromAuthorizationHeader(); - var fromQuery = TokenRetrieval.FromQueryString(); - - // - var bearerToken = fromHeader(req) ?? fromQuery(req); - - // - return bearerToken; - }); - }); - - // - // Register Authorization Handler ... - services.AddSingleton(); - Console.WriteLine("IdentityService: register Authorization Handlers ..."); - - // - // Register Identity Provider ... - services.Add(new ServiceDescriptor(typeof(IXIdentityProvider), typeof(XIdentityProvider), lifeTime)); - Console.WriteLine("IdentityService: Register IdentityProvider ..."); - - // - // Register Person Service ... - services.AddXPersonService(lifeTime); - - // - // Try To Register InMemoryTokenProvier if it's not Provided ... - IXTokenProvider xTokenProvider = null; - try - { - xTokenProvider = services.GetRegisteredService(); - } - catch { } - if (xTokenProvider.IsNull()) - { - // - Console.WriteLine("IdentityService: there is no Custom Token Provider, Adding InMemoryTokenProvider instead ..."); - services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(XInMemoryTokenProvider), lifeTime)); - } - - // - // Adding Security Provider ... - services.Add(new ServiceDescriptor(typeof(IXSecurityProvider), typeof(XSecurityProvider), lifeTime)); - Console.WriteLine("IdentityService: Register Security Provider ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\AuthorizationPolicyBuilderExtensions.cs - -using IdentityModel; -using Microsoft.AspNetCore.Authorization; - -namespace xIdentityService.Extensions { - public static class AuthorizationPolicyBuilderExtensions { - /// - /// Adds a policy to check for required scopes. - /// - /// - /// List of any required scopes. The token must contain at least one of the listed scopes. - /// - public static AuthorizationPolicyBuilder RequireScope (this AuthorizationPolicyBuilder builder, params string[] scope) { - return builder.RequireClaim (JwtClaimTypes.Scope, scope); - } - } - - /// - /// Helper for creating scope-related policies - /// - public static class ScopePolicy { - /// - /// Creates a policy to check for required scopes. - /// - /// List of any required scopes. The token must contain at least one of the listed scopes. - /// - public static AuthorizationPolicy Create (params string[] scopes) { - return new AuthorizationPolicyBuilder () - .RequireScope (scopes) - .Build (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\HttpContextExtensions.cs - -using xCommons.Constants; -using xCommons.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Http; -using xIdentityService.Constants; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.DependencyInjection; - -namespace xIdentityService.Extensions -{ - public static class HttpContextExtensions - { - /// - /// Retrieve Authentication Service ... - /// - /// - /// - public static IAuthenticationService GetAuthenticationService(this HttpContext context) - { - // - var result = context.RequestServices - .GetRequiredService(); - - // - return result; - } - - /// - /// Retrieve Specific Token from HttpContext ... - /// - /// - /// - /// - /// - public static async Task GetXTokenAsync( - this HttpContext context, - string tokenName, - XAuthenticationScheme scheme = XAuthenticationScheme.XToken - ) - { - // - // Validate Args ... - if (tokenName.IsNullOrEmpty()) - { - return null; - } - - // - var authService = context.GetAuthenticationService(); - if (authService.IsNull()) - { - return null; - } - - // - var authResult = await authService - .AuthenticateAsync( - context, - scheme - .GetStringValue() - ); - - // - var result = authResult?.Properties? - .GetTokenValue(tokenName); - return result; - } - - /// - /// Retrieve Access Token - /// - /// - public static async Task GetAccessToken(this HttpContext context) - { - // - var accessToken = context.Request.Headers[XAuthorization.Header] - .ToString(); - if (accessToken.IsNullOrEmpty()) - { - accessToken = await context - .GetTokenAsync(XAuthorization.AccessToken); - } - - // - if (accessToken - .ToNormalString() - .Contains(XAuthorization.TokenIdentifier - .ToNormalString())) - { - accessToken = accessToken - .Remove(0, XAuthorization.TokenIdentifier.Length); - } - - // - return accessToken; - } - - /// - /// Retrieve Refresh Token - /// - /// - public static async Task GetRefreshToken(this HttpContext context) - { - // - var refreshToken = context.Request.Headers[XAuthorization.RefreshToken] - .ToString(); - if (refreshToken.IsNullOrEmpty()) - { - refreshToken = await context - .GetTokenAsync(XAuthorization.RefreshToken); - } - - // - return refreshToken; - } - - /// - /// Retrieve Access Token Expiration Date - /// - /// - public static async Task GetTokenExpiresAt(this HttpContext context) - { - // - var expiresAtStr = context.Request.Headers[XAuthorization.ExpiresAt] - .ToString(); - if (expiresAtStr.IsNullOrEmpty()) - { - expiresAtStr = await context - .GetTokenAsync(XAuthorization.ExpiresAt); - } - - // - var expiresAt = expiresAtStr.ConvertTo(); - - // - return expiresAt; - } - - /// - /// Retrieve All Required Tokens - /// - /// - public static async Task RetrieveTokensAsXTokenResponse(this HttpContext context) - { - // - var accessToken = await GetAccessToken(context); - var refreshToken = await GetRefreshToken(context); - var expiresAt = await GetTokenExpiresAt(context); - - // - return new XTokenResponse - { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrieve Request Path ... - /// - /// - /// - public static string GetRequestPath(this HttpContext source) - { - // - var result = source.Request.GetRequestPath(); - return result; - } - - /// - /// Retrieve Request Path ... - /// - /// - /// - public static string GetRequestPath(this HttpRequest source) - { - // - var path = source.Path; - var pathBase = source.PathBase; - var query = source.QueryString; - - // - var result = $"{pathBase}{path}{query}"; - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\StreamExtensions.cs - -using System.IO; -using System.Linq; -using System.Threading; -using xCommons.Extensions; -using System.Collections.Generic; - -namespace xIdentityService.Extensions -{ - public static partial class StreamExtensions - { - /// - /// Converts an Stream to Async Enumerable ... - /// - /// - /// - /// - /// - public static async IAsyncEnumerable ToAsyncEnumerable( - this Stream stream, - int bufferSize = 8192, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - var buffer = new byte[bufferSize]; - while (true) - { - // - int read = await stream - .ReadAsync( - buffer, - 0, - buffer.Length, - cancellationToken - ); - - // - if (read == 0) - { - yield break; - } - - // - yield return buffer.Take(read).ToArray(); - } - } - - /// - /// Converts an Stream to Async Enumerable ... - /// - /// - /// - /// - /// - public static async IAsyncEnumerable ToAsyncEnumerable( - this Stream stream, - int bufferSize = 8192, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - var buffer = new byte[bufferSize]; - while (true) - { - // - int read = await stream - .ReadAsync( - buffer, - 0, - buffer.Length, - cancellationToken - ); - if (read == 0) - { - yield break; - } - - // - T chunk = default(T); - var readedBuffer = buffer.Take(read).ToArray(); - var str = readedBuffer.FromBytes(); - if (str.IsNullOrEmpty()) - { - yield return chunk; - } - try - { - chunk = str.FromJSON(); - } - catch - { } - - // - yield return chunk; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XModelExtensions.cs - -using xModels.Dtos; -using xIdentityModels.Dtos; - -namespace xIdentityService.Extensions -{ - public static class XModelExtensions - { - public static XPersonDto ToXPersonDto(this XOpenActionUserInfoDto source) - { - // - var result = new XPersonDto - { - UserId = source.UserId, - Avatar = source.Avatar, - Lastname = source.Lastname, - Username = source.Username, - Firstname = source.Firstname, - }; - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XRequestExtensions.cs - -using xCommons.Extensions; -using Microsoft.AspNetCore.Http; -using xIdentityService.Constants; - -namespace xIdentityService.Extensions -{ - public static class XRequestExtensions - { - /// - /// Extract ApiKey from Request Headers ... - /// - /// - /// - public static string ExtractApiKey(this HttpContext source) - { - return source.Request.ExtractApiKey(); - } - - /// - /// Extract ApiKey from Request Headers ... - /// - /// - /// - public static string ExtractApiKey(this HttpRequest source) - { - // - var key = XHeader.ApiKey.GetStringValue(); - var result = source?.Headers?[key] ?? string.Empty; - return result; - } - - /// - /// Extract Client Id of Specified Request .... - /// - /// - /// - public static string ExtractClientIP(this HttpRequest source) - { - // - var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString(); - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XTokenExtensions.cs - -using System; -using System.Net.Http; -using xCommons.Constants; -using xExceptions.Models; -using xCommons.Extensions; -using IdentityModel.Client; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Net.Http.Headers; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authentication; - -public static partial class XTokenExtensions { - /// - /// Retrieve Tokens From Headers - /// - /// - /// - public static XLoginResponse RetrieveTokens (this HttpRequest source) { - // - var accessToken = source.Headers[XAuthorization.Header].ToString (); - var refreshToken = source.Headers[XAuthorization.RefreshToken].ToString (); - - // - var expiresAtStr = source.Headers[XAuthorization.ExpiresAt].ToString (); - long expiresAt = expiresAtStr.ConvertTo (); - - // - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - // - return new XLoginResponse { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrieve Tokens From HttpContext - /// - /// - /// - public static async Task RetrieveTokens (this HttpContext source) { - // - var accessToken = await source.GetTokenAsync (XAuthorization.AccessToken); - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - var refreshToken = await source.GetTokenAsync (XAuthorization.RefreshToken); - var expiresAtStr = await source.GetTokenAsync (XAuthorization.ExpiresAt); - long expiresAt = expiresAtStr.ConvertTo (); - - // - var headerRequestTokens = source.Request.RetrieveTokens (); - - // - var result = new XLoginResponse { - AccessToken = accessToken ?? headerRequestTokens.AccessToken, - RefreshToken = refreshToken ?? headerRequestTokens.RefreshToken, - ExpiresAt = expiresAt != 0 ? expiresAt : headerRequestTokens.ExpiresAt - }; - - // - return result; - } - - /// - /// Retrieve Tokens From ActionExecutingContext - /// - /// - /// - public static async Task RetrieveTokens (this ActionExecutingContext source) { - // - var result = await source.HttpContext.RetrieveTokens (); - return result; - } - - /// - /// Retrieve Tokens From XUserInfo instance - /// - /// - /// - public static XTokenResponse RetrieveTokens (this XUserClaimsInfoDto source) { - // - var result = new XLoginResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = source.ExpiresAt - }; - - // - return result; - } - - /// - /// Retrieve Tokens From IHeader Dictionary - /// - /// - /// - public static XLoginResponse RetrieveTokens (this IHeaderDictionary source) { - // - var accessToken = source[XAuthorization.Header].ToString () ?? ""; - if (accessToken - .ToNormalString () - .Contains (XAuthorization.TokenIdentifier.ToNormalString ())) { - accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length); - } - - // - var refreshToken = source[XAuthorization.RefreshToken].ToString () ?? ""; - - // - var expiresAtStr = source[XAuthorization.ExpiresAt].ToString () ?? ""; - var expiresAt = expiresAtStr.ConvertTo (); - - // - var result = new XLoginResponse { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - - // - return result; - } - - /// - /// Retrieve IXIdentityProvider from HttpContext - /// - /// - /// - public static IXIdentityProvider GetXApiIdentityProvider (this FilterContext source) { - // - var services = source.HttpContext.RequestServices; - return (IXIdentityProvider) services - .GetService (typeof (IXIdentityProvider)); - } - - /// - /// Generate XLoginResponse instance based on TokenResponse - /// - /// - /// - public static XLoginResponse CreateXLoginResponse (this TokenResponse source) { - // - if (source.IsNull () || - source.IsError) { - XException.InvalidToken.Throw (); - } - - // - var expiresAt = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds () + - source.ExpiresIn; - - // - var result = new XLoginResponse { - AccessToken = source.AccessToken, - RefreshToken = source.RefreshToken, - ExpiresAt = expiresAt - }; - - // - return result; - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this IHeaderDictionary source, - XLoginResponse model, - string secret = null - ) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - - // - if (!secret.IsNullOrEmpty ()) { - var revisionChecksum = model.GetRevisionChecksum (secret); - source.Add (XAuthorization.RevisionChecksum, revisionChecksum); - } - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific IHeaderDictionary instance - /// - /// - /// - public static void SetXAuthenticationTokens (this HttpRequestHeaders source, XLoginResponse model) { - // - source.Remove (XAuthorization.Header); - source.Remove (XAuthorization.RefreshToken); - source.Remove (XAuthorization.ExpiresAt); - source.Remove (XAuthorization.RevisionChecksum); - - // - source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}"); - source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}"); - source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}"); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens (this HttpRequest source, XLoginResponse model) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add Authorization Tokens in Headers of - /// Specific HttpRequest instance - /// - /// - /// - public static void SetXAuthenticationTokens (this HttpRequestMessage source, XLoginResponse model) { - source.Headers.SetXAuthenticationTokens (model); - } - - /// - /// Add ReNewed Authorization Tokens in Headers of - /// Specific Response. - /// Later in HttpInterceptors we can Look for AccessToken-ReNewed - /// header Value and Renew User Tokens based on it - /// - /// - /// - /// - public static void SetXAuthenticationTokens ( - this HttpResponse source, - XLoginResponse model, - string secret - ) { - source.Headers.SetXAuthenticationTokens (model, secret); - } - - /// - /// Determines a Token Can Refrsh or not - /// - /// - /// - public static bool IsRefreshable (this XLoginResponse source) { - // - var containsTokenData = !source.IsNull () && - !source.AccessToken.IsNullOrEmpty () && - !source.RefreshToken.IsNullOrEmpty (); - if (!containsTokenData) { - return false; - } - - // - var current = new DateTimeOffset (DateTime.UtcNow) - .ToUnixTimeSeconds (); - - // - // var result = current > source.ExpiresAt || current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - var result = current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration; - - // - return result; - } - - /// - /// Generate a Revision Checksum for new Tokens - /// - /// - /// - /// - public static string GetRevisionChecksum (this XLoginResponse source, string secret) { - return (source.AccessToken + - secret + - source.RefreshToken + - secret + - source.ExpiresAt.ToString () - ) - .ToMd5String (); - } - - /// - /// Generate a Revision Checksum for new Tokens - /// - /// - /// - /// - public static string GetRevisionChecksum (this XTokenResponse source, string secret) { - return (source.AccessToken + - secret + - source.RefreshToken + - secret + - source.ExpiresAt.ToString () - ) - .ToMd5String (); - } - - /// - /// Check an XLoginResponse instance is Valid with it's revision - /// - /// - /// - /// - /// - public static bool ValidateRevisionChecksum (this XLoginResponse source, string checksum, string secret) { - // - var xChecksum = source.GetRevisionChecksum (secret); - return checksum == xChecksum; - } - - /// - /// Check an XTokenResponse instance is Valid with it's revision - /// - /// - /// - /// - /// - public static bool ValidateRevisionChecksum (this XTokenResponse source, string checksum, string secret) { - // - var xChecksum = source.GetRevisionChecksum (secret); - return checksum == xChecksum; - } - - /// - /// Retrieve Exception Details if Fails - /// - /// - /// - public static Exception GetException (this TokenResponse source) { - // - // Validate Args ... - if (source.IsNull () || !source.IsError) { - return XException.ActionFailed.ToException (); - } - - // - XError error = source.ErrorDescription.FromJSON (); - return error.ToException (); - } - - /// - /// Convert XTokenResponse to Header Dictionary - /// - /// - /// - public static IDictionary ToHeaderDictionary (this XTokenResponse source) { - // - var result = new Dictionary { { XAuthorization.RefreshToken, source.RefreshToken }, - { XAuthorization.ExpiresAt, source.ExpiresAt.ToString () } - }; - - // - return result; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XUserClaimsInfoDtoExtensions.cs - -using xCommons.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Constants; - -namespace xIdentityService.Extensions { - public static class XUserClaimsInfoDtoExtensions { - public static string GetUserSelectByParam ( - this XUserClaimsInfoDto source, - XUserSelectBy userSelectBy = XUserSelectBy.Username - ) { - // - var result = ""; - - // - switch (userSelectBy) { - // - case XUserSelectBy.ID: - result = source.UserId; - break; - - // - case XUserSelectBy.Username: - result = source.UserName; - break; - - // - case XUserSelectBy.Email: - result = source.Email; - break; - - // - case XUserSelectBy.MobileNumber: - result = source.PhoneNumber; - break; - } - - // - if (result.IsNullOrEmpty ()) { - // - if (!source.UserId.IsNullOrEmpty ()) { - result = source.UserId; - } else if (!source.UserName.IsNullOrEmpty ()) { - result = source.UserName; - } else if (!source.Email.IsNullOrEmpty ()) { - result = source.Email; - } else if (!source.PhoneNumber.IsNullOrEmpty ()) { - result = source.PhoneNumber; - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseIdentityHttpProvider.cs - -using System; -using System.IO; -using RestSharp; -using System.Net.Http; -using System.Threading; -using xCommons.Providers; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xIdentityService.Models; -using xIdentityModels.Constants; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xIdentityService.Interfaces -{ - /// - /// an interface for Identity Provided Http Based Services ... - /// - public interface IXBaseIdentityHttpProvider - { - /// - /// Client Base Url ... - /// - /// - string BaseUrl { get; } - - /// - /// Logger ... - /// - /// - ILogger Logger { get; } - - /// - /// Powered Value ... - /// - /// - string XPoweredValue { get; } - - /// - /// Default Client Timeout ... - /// - /// - int DefaultClientTimeout { get; } - - /// - /// Default Buffering Chunk Size ... - /// - /// - int DefaultBufferingChunckSize { get; } - - /// - /// Validation Provider ... - /// - /// - XValidationProvider ValidationProvider { get; } - - /// - /// Get an Instance of Http Client - /// - /// - HttpClient GetHttpClient(XTokenResponse tokens = null); - HttpClient GetHttpClient(XUserClaimsInfoDto userInfo = null); - - /// - /// Get an Instance of RestClient - /// - /// - RestClient GetRestClient(XTokenResponse tokens = null); - RestClient GetRestClient(XUserClaimsInfoDto userInfo = null); - - /// - /// Get an Instance of RestRequest - /// - /// - /// - /// - /// - /// - /// - RestRequest GetRestRequet( - Enum endpoint, - bool addXPoweredValue = true, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null - ); - - /// - /// Handle Call Specific Request and retrieve Response - /// - /// - /// - /// - /// - /// - /// - /// - Task RunRestRequest( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true, - CancellationToken cancellationToken = default - ); - - /// - /// Access a Get Request Stream as AsyncEnumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task StreamData( - Enum endpoint, - int bufferLength = 8194, - bool addXPoweredValue = true, - XTokenResponse tokens = null, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null, - CancellationToken cancellationToken = default - ); - - /// - /// Handle Call Specified Request and Retrieve XBaseRestResponse ... - /// - /// - /// - /// - /// - /// - /// - /// an instance of XBaseRestResponse - Task> RunRestRequestByResponse( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true, - CancellationToken cancellationToken = default - ); - - /// - /// Get User SelectBy Param - /// - /// - /// - /// - /// - string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ); - - /// - /// Converts UserInfo to TokenResponse model ... - /// - /// - /// - XTokenResponse ToTokenResponse(XUserClaimsInfoDto userInfo = null); - - /// - /// Prepare Url Address of Specified Enum by Filling Params - /// and Query Strings Attach ... - /// - /// - /// - /// - /// - /// - string PrepareUrl( - Enum endpoint, - bool attachBaseUrl = false, - IDictionary @params = null, - IDictionary queryStrings = null - ); - - /// - /// Prepare Url Address by Filling Params - /// and Query Strings Attach ... - /// - /// - /// - /// - /// - /// - string PrepareUrl( - string url, - bool attachBaseUrl = false, - IDictionary @params = null, - IDictionary queryStrings = null - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseReferenced.cs - -using xModels.Base; -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xIdentityService.Interfaces -{ - /// - /// a Referenced Service is a Service which can Referenced to other Items ... - /// - public interface IXBaseReferenced - where TEntity : XBaseEntity - { - /// - /// Get Reference Identifier for Specified Provider and Specified Item ... - /// - /// - /// - /// - string GetIdentifier( - string providedFor, - TReferenceKey forProvidedId - ); - - /// - /// Check Specified Item has Refernce to Provider ... - /// - /// - /// - /// - /// - /// - Task IsProvidedFor( - string providedFor, - TReferenceKey forProvidedId, - TKey id, - CancellationToken cancellationToken = default - ); - - /// - /// Add Specified Reference to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task AddReference( - string providedFor, - TReferenceKey forProvidedId, - TKey id, - int forIndex = 0, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Reference from Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task RemoveReference( - string providedFor, - TReferenceKey forProvidedId, - TKey id, - int forIndex = 0, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified References ... - /// - /// - /// - /// - /// - Task>> GetReferences( - string providedFor, - TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseReferencedController.cs - -using xModels.Base; -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; - -namespace xIdentityService.Interfaces -{ - public interface IXBaseReferencedController - where TEntity : XBaseEntity - { - /// - /// Check an Item Has Reference to Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/Reference/IsProvidedFor")] - Task> IsProvidedFor( - [FromRoute] TKey id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - CancellationToken cancellationToken = default - ); - - /// - /// Add a Reference to Item for Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("{id}/Reference")] - Task AddReference( - [FromRoute] TKey id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - [FromQuery] int forIndex = 0, - CancellationToken cancellationToken = default - ); - - /// - /// Remove a Reference from Item for Specified ProvideFor and Specified forProvidedId ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}/Reference")] - Task RemoveReference( - [FromRoute] TKey id, - [FromQuery] string providedFor, - [FromQuery] object forProvidedId, - [FromQuery] int forIndex = 0, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve References of Specified Itemfor providedFor ... - /// - /// - /// - /// - /// - [HttpGet("{id}/References")] - Task>>> GetReferences( - [FromRoute] TKey id, - [FromQuery] string providedFor, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXIdentityBaseReferencedProvider.cs - -using xModels.Dtos; -using xDataService.Models; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xIdentityService.Interfaces -{ - /// - /// in Some Cases we have Entities Which Can Referenced for Specified - /// Provider and Types ... - /// this interface Globaly introduce all available Actions for those ... - /// - /// TKey: type of Provider Models Keys ... - /// TModel: type of Dto which Referenced ... - /// - public interface IXIdentityBaseReferencedProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - string Provider { get; } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - Task GetReference( - TKey providedForId, - int forIndex = 0 - ); - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - Task> GetAllReferences(TKey providedForId); - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - Task>> GetAllReferencings(TKey providedForId); - - /// - /// Count References ... - /// - /// - /// - Task CountReferences(TKey providedForId); - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - Task> QueryReferences( - XQuery query, - TKey providedForId - ); - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - TKey providedForId, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ); - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task AddReference( - TModel model, - XReference reference, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ); - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - TKey providedForId, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ); - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - TModel model, - XReference reference, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ); - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - Task RemoveReferences( - TKey providedForId, - string connectionId = null, - XUserClaimsInfoDto userInfo = null - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXIdentityProvider.cs - -using System; -using RestSharp; -using xModels.Dtos; -using System.Threading; -using IdentityModel.Client; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Navigations; - -namespace xIdentityService.Interfaces -{ - public partial interface IXIdentityProvider - { - // - string BaseUrl { get; } - string RevisionSecretKey { get; } - IXSecurityProvider SecurityProvider { get; } - - // - #region Tools ... - string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ); - #endregion - - // - #region Tools ... - Task RunRestRequest( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = false - ); - #endregion - - // - #region Authentication ... - Task RequestDiscoveryDocument(); - Task RequestScopeAccessToken(string scope); - Task Validate(XTokenResponse model); - Task Introspection(XTokenResponse model); - Task Login(XLoginRequest model); - Task Logout(XTokenResponse model); - Task Authenticate(XLoginRequest model); - Task RefreshTokens(XTokenResponse model); - - Task ChangePassword( - XTokenResponse tokens, - XActionRequest model - ); - #endregion - - // - #region Profile ... - Task> GetUserNames( - XTokenResponse tokens, - string userIds - ); - - Task> GetUserNameIds( - XTokenResponse tokens, - XUserNameIdRequest model - ); - - Task GetUserProfile( - XTokenResponse tokens, - string userSelectByParam - ); - - Task> QueryUsers( - XTokenResponse tokens, - XQuery query - ); - - Task> QueryInRoleUsers( - XTokenResponse tokens, - string role, - XQuery query, - bool forceRole = false - ); - - Task> QueryAvatars( - XTokenResponse tokens, - string userSelectByParam, - XQuery query - ); - - Task ProfileUpdateAsync( - XTokenResponse tokens, - string userSelectByParam, - XProfileUpdateRequest model - ); - - Task FullProfileUpdateAsync( - XTokenResponse tokens, - string userSelectByParam, - XProfileUpdateRequest request - ); - - Task AddAvatar( - XTokenResponse tokens, - IFormFile file - ); - - Task AddAvatars( - XTokenResponse tokens, - IFormFileCollection files - ); - - Task SetAvatar( - XTokenResponse tokens, - int avatarId - ); - - Task RemoveAvatars( - XTokenResponse tokens, - string avatarIds - ); - #endregion - - // - #region Search ... - /// - /// Query Open To Search User Profiles ... - /// - /// requested user's identifiers - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - Task> QueryOpenToSearchUsers( - XTokenResponse tokens, - XQuery query - ); - #endregion - - // - #region Registration ... - Task CanRegister(string userSelectByParam); - - Task InviteUser( - XTokenResponse tokens, - XActionRequest model - ); - - Task RequestRegistration( - XActionRequest model - ); - - Task AddAccountInfo( - XActionRequest model - ); - - Task AttachProfileImage( - string actionToken, - IFormFile file - ); - - Task FinishRegistration(XActionRequest model); - - Task IsConfirmedEmail( - XTokenResponse tokens, - string userSelectByParam - ); - - Task IsConfirmedMobile( - XTokenResponse tokens, - string userSelectByParam - ); - - Task RequestConfirmRegistration(XActionRequest model); - - Task ConfirmRegistration( - XActionRequest model - ); - - Task RequestConfirmMobile(XActionRequest model); - - Task ConfirmMobileNumber(XActionRequest model); - - Task RequestConfirmEmail(XActionRequest model); - - Task ConfirmEmailAddress(XActionRequest model); - - Task RequestResetPassword(XActionRequest model); - - Task ResetPassword(XActionRequest model); - #endregion - - // - #region Friendship ... - Task Follow( - XTokenResponse tokens, - string destUser - ); - - Task Cancel( - XTokenResponse tokens, - string destUser - ); - - Task UnFollowFollower( - XTokenResponse tokens, - string destUser - ); - - Task UnFollowFollowing( - XTokenResponse tokens, - string destUser - ); - - Task Block( - XTokenResponse tokens, - string destUser - ); - - Task UnBlock( - XTokenResponse tokens, - string destUser - ); - - Task AcceptRequest( - XTokenResponse tokens, - string destUser - ); - - Task RejectRequest( - XTokenResponse tokens, - string destUser - ); - - Task GetFriendshipInfo( - XTokenResponse tokens, - string destUser - ); - - Task IsFollower( - XTokenResponse tokens, - string destUser - ); - - Task GetFollower( - XTokenResponse tokens, - string destUser - ); - - Task GetFollowerState( - XTokenResponse tokens, - string destUser - ); - - Task> GetFollowers(XTokenResponse tokens); - - Task> GetAllFollowers(XTokenResponse tokens); - - Task> GetFollowingList(XTokenResponse tokens); - - Task> QueryFollowers( - XQuery query, - string destUser, - XTokenResponse tokens - ); - - Task IsFollowing( - XTokenResponse tokens, - string destUser - ); - - Task GetFollowing( - XTokenResponse tokens, - string destUser - ); - - Task GetFollowingState( - XTokenResponse tokens, - string destUser - ); - - Task> GetFollowings(XTokenResponse tokens); - - Task> GetAllFollowings(XTokenResponse tokens); - - Task> GetFollowersList(XTokenResponse tokens); - - Task> QueryFollowings( - XQuery query, - string destUser, - XTokenResponse tokens - ); - #endregion - - // - #region Admin ... - Task> Ban( - XTokenResponse tokens, - XUserNameIdRequest model - ); - - Task> UnBan( - XTokenResponse tokens, - XUserNameIdRequest model - ); - - Task IsBanned( - XTokenResponse tokens, - string userSelectByParam - ); - #endregion - - // - #region Open Actions ... - // - XDeviceDto GetDevice(); - - // - Task OpenGet( - XOpenActionInnerDto model - ); - - // - Task GetApiKey( - XDeviceDto device, - string apiKey - ); - Task GetApiKey( - XOpenActionInnerDto dto - ); - Task GetApiKey( - string token, - string request - ); - - // - Task UseApiKey( - XDeviceDto device, - XApiKeyUsageDto apiKeyUsage - ); - Task UseApiKey( - XOpenActionInnerDto dto - ); - Task UseApiKey( - string token, - string request - ); - - // - Task GetUserInfo( - XDeviceDto device, - string userSelectByParam - ); - Task GetUserInfo( - XOpenActionInnerDto dto - ); - Task GetUserInfo( - string token, - string request - ); - - // - Task> GetUserInfos( - XDeviceDto device, - string ids - ); - Task> GetUserInfos( - XOpenActionInnerDto dto - ); - Task> GetUserInfos( - string token, - string request - ); - #endregion - - // - #region Applications ... - // - #region Application ... - /// - /// Create Application ... - /// - /// - /// - /// - /// - Task CreateApplication( - XTokenResponse tokens, - XApplicationDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Application ... - /// - /// - /// - /// - /// - /// - Task UpdateApplication( - XTokenResponse tokens, - int id, - XApplicationDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Application ... - /// - /// - /// - /// - /// - Task RemoveApplication( - XTokenResponse tokens, - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Application ... - /// - /// - /// - /// - /// - Task GetApplication( - XTokenResponse tokens, - int id, - CancellationToken cancellationToken = default - ); - - /// - /// Query Applications ... - /// - /// - /// - /// - /// - Task> QueryApplications( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Application ... - /// - /// - /// - /// - Task> GetAllApplications( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region XApiKey ... - /// - /// Get Specified ApiKey ... - /// - /// - /// - /// - /// - Task GetApiKey( - XTokenResponse tokens, - Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified ApiKey ... - /// - /// - /// - /// - /// - Task RemoveApiKey( - XTokenResponse tokens, - Guid id, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified ApiKey ... - /// - /// - /// - /// - /// - /// - Task UpdateApiKey( - XTokenResponse tokens, - Guid id, - XApiKeyDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Query ApiKeys ... - /// - /// - /// - /// - /// - Task> QueryApiKeys( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Specified ApiKeys ... - /// - /// - /// - /// - Task> GetAllApiKeys( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region XApiKeyUsage ... - /// - /// Add Api Key Usage ... - /// - /// - /// - /// - /// - Task AddApiKeyUsage( - XTokenResponse tokens, - XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Api Key Usage ... - /// - /// - /// - /// - /// - Task GetApiKeyUsage( - XTokenResponse tokens, - long id, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Api Key Usage ... - /// - /// - /// - /// - /// - Task RemoveApiKeyUsage( - XTokenResponse tokens, - long id, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Api Key Usage ... - /// - /// - /// - /// - /// - /// - Task UpdateApiKeyUsage( - XTokenResponse tokens, - long id, - XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Query Api Key Usages ... - /// - /// - /// - /// - /// - Task> QueryApiKeyUsages( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Api Key Usages ... - /// - /// - /// - /// - Task> GetAllApiKeyUsages( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Custom ... - /// - /// Show Api Key ... - /// - /// - /// - /// - /// - /// - Task ShowApiKey( - XTokenResponse tokens, - Guid apiKeyId, - int applicationId, - CancellationToken cancellationToken = default - ); - - /// - /// Create Api Key ... - /// - /// - /// - /// - /// - /// - Task CreateApiKey( - XTokenResponse tokens, - int applicationId, - XCreateApiKeyRequest request, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Api Key ... - /// - /// - /// - /// - /// - /// - Task RemoveApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ); - - /// - /// Rotate Specified Api Key ... - /// - /// - /// - /// - /// - /// - /// - Task RotateApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - XRotateApiKeyRequest request, - CancellationToken cancellationToken = default - ); - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - /// - Task RevokeApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Application's Api Keys ... - /// - /// - /// - /// - /// - Task> GetApiKeys( - XTokenResponse tokens, - int applicationId, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Api Keys Usages ... - /// - /// - /// - /// - /// - /// - Task> GetApiKeyUsages( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ); - - /// - /// Validate Specifed Api Key ... - /// - /// - /// - /// - Task ValidateApiKey( - XApiKeyValidationRequest request, - CancellationToken cancellationToken = default - ); - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXPersonService.cs - -using xModels.Dtos; -using System.Threading.Tasks; - -namespace xIdentityService.Interfaces -{ - public interface IXPersonService - { - /// - /// Retrieve Person ... - /// - /// - /// - Task GetPerson(string userId); - - /// - /// Handle Cleanup ... - /// - void Cleanup(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXPolicyHandler.cs - -using System.Collections.Generic; - -namespace xIdentityService.Interfaces -{ - public interface IXPolicyHandler - { - /// - /// Add Specified Role ... - /// - /// - /// - /// - bool AddPolicy( - string policy, - IEnumerable requiredRoles - ); - - /// - /// Check Specified Role Exists or not ... - /// - /// - /// - bool HasPolicy(string policy); - - /// - /// Remove Specified Role ... - /// - /// - /// - bool RemovePolicy(string policy); - - /// - /// Check Specified Policy passed or not ... - /// - /// - /// - /// - bool IsPolicyPassed( - string policy, - IEnumerable roles - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXProxyHelper.cs - -using System; -using System.Linq.Expressions; -using System.Collections.Generic; -using xIdentityService.Configuration; - -namespace xIdentityService.Interfaces { - public interface IXProxyHelper { - /// - /// Proxy Configuration ... - /// - /// - XProxyConfiguration Configuration { get; } - - /// - /// retrie Normalize Host ... - /// - /// - string NormalizeHost (); - - /// - /// Validate XProxy Configuration for Client ... - /// - /// - bool ValidateConfiguration (); - - /// - /// Retrieve all Prepared url of Routes ... - /// - /// - IEnumerable GetRouteUrls (); - - /// - /// retrieve all registred Routes ... - /// - /// - IEnumerable GetRoutes (); - - /// - /// Prepare a request url for a Proxy Route ... - /// - /// - /// - /// - string PrepareActionUrlForXProxyRoute ( - string url, - XProxyRouteDescriptor descriptor - ); - - /// - /// Prepare a request url for a Selected Proxy Route ... - /// - /// - /// - /// - string PrepareActionUrlForXProxyRoute ( - string url, - Expression> whereClause - ); - - /// - /// Find an Specific Route ... - /// - /// - /// - XProxyRouteDescriptor FindRoute (Expression> whereClause); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXSecurityProvider.cs - -namespace xIdentityService.Interfaces -{ - public partial interface IXSecurityProvider - { - string Encrypt(string plainText); - string Decrypt(string cipherText); - string EncryptFromBytes(byte[] textBytes); - string DecryptFromBytes(byte[] cipherBytes); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXTokenProvider.cs - -using System.Threading.Tasks; -using xIdentityModels.Models; - -namespace xIdentityService.Interfaces { - public partial interface IXTokenProvider { - Task IsTokenExists (string accessToken); - Task IsTokenExists (XTokenResponse tokens); - Task RemoveToken (string accessToken); - Task RemoveToken (XTokenResponse tokens); - Task RetrieveToken (string accessToken); - Task AddToken (XTokenResponse tokens); - Task UpdateToken (XTokenResponse tokens); - Task AddOrUpdateToken (XTokenResponse tokens); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Middlewares\XApiKeyUsageMiddleware.cs - -using System; -using System.Diagnostics; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using xIdentityService.Attributes; -using xIdentityService.Interfaces; -using xIdentityService.Extensions; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http.Features; - -namespace xIdentityService.Middlewares -{ - public class XApiKeyUsageMiddleware - { - // - #region Properties ... - private readonly RequestDelegate next; - #endregion - - // - #region Constructor ... - public XApiKeyUsageMiddleware( - RequestDelegate next - ) - { - this.next = next; - } - #endregion - - - // - #region Actions ... - public async Task InvokeAsync( - HttpContext context, - IXIdentityProvider identityProvider - ) - { - // - // Check Context Has ApiKey Authorization Filter ... - var endpointFeature = context.Features.Get(); - var endpoint = - endpointFeature.IsNull() - ? null - : endpointFeature.Endpoint; - var apiKeyAccessAttibute = - endpoint.IsNull() - ? null - : endpoint.Metadata.GetMetadata(); - if (!apiKeyAccessAttibute.IsNull()) - { - // - var sw = Stopwatch.StartNew(); - var requestedOn = DateTime.UtcNow; - var httpMethod = context.Request.Method; - var statusCode = StatusCodes.Status200OK; - var endpointName = context.GetRequestPath(); - var clientIp = context.Request.ExtractClientIP(); - - // - var device = identityProvider.GetDevice(); - var apiKey = context.Request.ExtractApiKey(); - var cApiKeyId = context.Request.HttpContext.User.Identity; - var apiKeyId = await identityProvider.GetApiKey( - device: device, - apiKey: apiKey - ); - - // - try - { - await next(context); - statusCode = context.Response.StatusCode; - } - catch - { - statusCode = StatusCodes.Status500InternalServerError; - throw; - } - - // - sw.Stop(); - var dto = new XApiKeyUsageDto - { - ApiKeyId = apiKeyId, - ClientIP = clientIp, - Endpoint = endpointName, - StatusCode = statusCode, - HttpMethod = httpMethod, - RequestedOn = requestedOn, - ResponseTimeMs = sw.ElapsedMilliseconds, - }; - await identityProvider.UseApiKey( - device: device, - apiKeyUsage: dto - ); - } - else - { - await next(context); - } - } - #endregion - } - - public static class XApiKeyUsageMiddlewareDIExtensions - { - /// - /// Adding XProxy Middleware to Applications ... - /// - /// - public static void UseXApiKeyUsage(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Middlewares\XIdentityTokenRefresher.cs - -using System; -using xCommons.Constants; -using xCommons.Extensions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Extensions; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Logging; - -namespace xIdentityService.Middlewares { - public partial class XIdentityTokenRefresherMiddleware { - // - #region Properties ... - private readonly ILogger logger; - private readonly RequestDelegate next; - private readonly IXTokenProvider tokenProvider; - private readonly IXIdentityProvider identityProvider; - #endregion - - // - #region Constructor ... - public XIdentityTokenRefresherMiddleware ( - RequestDelegate next, - ILoggerFactory loggerFactory, - IXTokenProvider tokenProvider, - IXIdentityProvider identityProvider - ) { - // - this.next = next; - this.tokenProvider = tokenProvider; - this.identityProvider = identityProvider; - this.logger = loggerFactory - .CreateLogger (); - } - #endregion - - // - #region Actions ... - public async Task Invoke (HttpContext context) { - // - // Handle Request ... - await HandleRequest (context); - - // - // Do Main Task ... - try { - await next.Invoke (context); - } catch (Exception ex) { - logger.LogError ($"Error: {ex.Message}"); - } - - // - // Handle Response ... - await HandleResponse (context); - } - #endregion - - // - #region Private ... - private async Task HandleRequest (HttpContext context) { - // - // Log ... - logger.LogInformation ($"Start Process Request ..."); - - // - // Check Access Token ... - var hasAccessToken = HasAccessToken (context); - if (!hasAccessToken) { - return; - } - - // - // Check Access Token ... - var accessToken = GetAccessToken (context); - var isExists = await tokenProvider - .IsTokenExists (accessToken); - if (!isExists) { - return; - } - - // - // Try Check is Refreshable ... - var tokens = await tokenProvider - .RetrieveToken (accessToken); - if (tokens.IsNull ()) { - return; - } - - // - // Check is Expired or Refreshable ... - var isRefreshable = tokens.IsRefreshable (); - if (!isRefreshable) { - return; - } - - // - // Refresh Token ... - var refreshedTokens = await identityProvider - .RefreshTokens (tokens); - if (refreshedTokens.IsNull ()) { - return; - } - - // - // Set Refreshed AccessToken to Request ... - context - .Request - .Headers[XAuthorization.Header] = - $"{XAuthorization.TokenIdentifier}{refreshedTokens.AccessToken}"; - } - - private async Task HandleResponse (HttpContext context) { - // - // Log ... - logger.LogInformation ($"Start Process Response ..."); - - // - await Task.Run (() => { }); - } - - private bool HasAccessToken (HttpContext context) { - // - // Check Headers ... - if (context.IsNull () || - context.Request.IsNull () || - context.Request.Headers.IsNull ()) { - return false; - } - - // - var result = context - .Request - .Headers - .ContainsKey ( - XAuthorization.Header - ); - - // - return result; - } - - private string GetAccessToken (HttpContext context) { - // - var hasAccessToken = HasAccessToken (context); - if (!hasAccessToken) { - return string.Empty; - } - - // - // Get Result ... - var result = context - .Request - .Headers[ - XAuthorization.Header - ]; - result = result - .ToString () - .Replace ( - XAuthorization.TokenIdentifier, - "" - ); - - // - return result; - } - #endregion - } - - /// - /// Provide all DI Requirements for XIdentityTokenRefresher Middleware - /// - public static class XIdentityTokenRefresherDIHelper { - /// - /// Use XTokenValidator Middleware - /// - /// - public static void UseXIdentityTokenRefresher (this IApplicationBuilder app) { - app.UseMiddleware (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Middlewares\XProxyMiddleware.cs - -using System; -using System.Net; -using System.Web; -using System.Linq; -using System.Text; -using xModels.Base; -using IdentityModel; -using System.Net.Http; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Constants; -using xIdentityService.Providers; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Logging; -using xIdentityService.Configuration; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xIdentityService.Middlewares { - /// - /// Proxy Server Middleware ... - /// - public class XProxyMiddleware : XBaseClass { - // - #region Pros ... - private readonly HttpClient HTTP_CLIENT; - private readonly RequestDelegate NEXT_MIDDLEWARE; - private readonly XProxyConfiguration CONFIGURATION; - #endregion - - // - #region Constructor ... - public XProxyMiddleware ( - ILoggerFactory loggerFactory, - RequestDelegate nextMiddleware, - XProxyConfiguration configuration, - IHttpClientFactory httpClientFactory - ) : base (loggerFactory) { - // - CONFIGURATION = configuration; - NEXT_MIDDLEWARE = nextMiddleware; - - // - // Create Http Client ... - HTTP_CLIENT = httpClientFactory - .CreateClient (XProxyConstants.XPROXY_HTTP_CLIENT); - - // - // Logging Server Configuration ... - LogXProxyServerConfig (); - } - #endregion - - // - #region Public ... - public async Task InvokeAsync (HttpContext context) { - // - #region Bussiness Logic ... - // - var routeDescriptor = GetRouteDescriptor (context.Request); - if (!routeDescriptor.IsNull ()) { - // - #region Handle Authorization ... - // - try { - // - // Handle XPowered ... - if (routeDescriptor.EnableXPoweredByAthorization) { - // - var isPoweredByPass = context.Request.Headers - .Any (h => h.Key - .ToNormalString () == xCommons.Constants.XAuthorization.XPoweredBy - .ToNormalString () && - h.Value - .ToString () - .ToNormalString () == CONFIGURATION.XPoweredValue - .ToNormalString () - ); - - // - if (!isPoweredByPass) { - ThrowNotAuthorizedException (); - } - } - - // - // Handle EndableAuthorization ... - if (routeDescriptor.EnableAuthorization) { - // - // Retrieve User Info for Authentication ... - var userName = context.User.Identity.Name; - var isUserAuthenticated = !userName.IsNull () && - context.User.Identity.IsAuthenticated; - if (!isUserAuthenticated && - !routeDescriptor.AllowedScopes.HasChild () - ) { - ThrowNotAuthorizedException (); - } - - // - // Check Allowed Scopes Authorization ... - if (routeDescriptor.AllowedScopes.HasChild ()) { - // - var scopeClaims = context.User.Claims - .Where (c => c.Type == JwtClaimTypes.Scope) - .Select (c => c.Value); - var isScopePassed = scopeClaims.HasChild () && - scopeClaims.Any (c => routeDescriptor.AllowedScopes - .Any (allowedScope => allowedScope - .ToNormalString () == c - .ToNormalString () - ) - ); - if (!isScopePassed) { - ThrowNotAuthorizedException (); - } - } - - // - // Check Allowed Roles Authorization ... - if ( - isUserAuthenticated && - routeDescriptor.AllowedRoles.HasChild () - ) { - // - var roleClaim = context.User.Claims - .FirstOrDefault (c => c.Type == JwtClaimTypes.Role); - var isRolePassed = !roleClaim.IsNull () && - routeDescriptor.AllowedRoles - .Any (role => role - .ToNormalString () == roleClaim.Value - .ToNormalString ()); - if (!isRolePassed) { - ThrowNotAuthorizedException (); - } - } - } - } catch { - context.Response.StatusCode = (int) HttpStatusCode.Unauthorized; - return; - } - #endregion - - // - // Extract Request Uri from Received Request ... - var requestUri = GetUri (context.Request); - if (!requestUri.IsNull ()) { - // - // Retrieve Request based on current ... - var request = GetRequestMessage ( - uri: requestUri, - context: context - ); - - // - SendLog ($"Send Request to Recieve Response ...", LogLevel.Information); - - // - // Send Request and Retrieve Response ... - try { - // - var response = await HTTP_CLIENT.SendAsync ( - request, - HttpCompletionOption.ResponseContentRead - ); - - // - // Set Current Response Status Code ... - context.Response.StatusCode = (int) response.StatusCode; - - // - // Retrieve Response Headers and Set To Current Response ... - HandleResponseHeaders (context, response); - - // - // Processing Response Content ... - await ProcessResponseContent (context, response); - } catch (Exception ex) { - // - LogMessage ($"Exception: {ex.Message}", LogLevel.Error); - - // - context.Response.StatusCode = (int) HttpStatusCode.BadRequest; - } - - // - return; - } - } - #endregion - - // - await NEXT_MIDDLEWARE (context); - } - #endregion - - // - #region Private ... - /// - /// Throw Required Exception ... - /// - private void ThrowNotAuthorizedException () { - throw XException.NotAuthorized.ToException (); - } - - /// - /// Show propper logs if Enabled ... - /// - /// - /// - private void SendLog (string message, LogLevel logLevel = LogLevel.Information) { - // - if (!CONFIGURATION.EnableLogging) { - return; - } - - // - LogMessage ( - message: message, - logLevel: logLevel - ); - } - - /// - /// Log Proxy Server Configuration ... - /// - private void LogXProxyServerConfig () { - // - // Retrieve XProxyConfiguration class from Configurations and Validate them ... - if (CONFIGURATION.IsNull ()) { - throw XException.InvalidConfiguration.ToException (); - } - - // - // Try to Log Proxy Configuration ... - ConsoleMessage ("==============================="); - ConsoleMessage ("= Proxy Server Configurations: "); - ConsoleMessage ("==============================="); - - // - ConsoleMessage ($"Host: {CONFIGURATION.Host}"); - ConsoleMessage ($"XPoweredValue: {CONFIGURATION.XPoweredValue}"); - ConsoleMessage ($"EnableLogging: {CONFIGURATION.EnableLogging}"); - ConsoleMessage ($"DisableSSLCheck: {CONFIGURATION.DisableSSLCheck}"); - ConsoleMessage ($"AllowAutoRedirect: {CONFIGURATION.AllowAutoRedirect}"); - ConsoleMessage ($" "); - ConsoleMessage ($"Routes: "); - ConsoleMessage ($" "); - - // - CONFIGURATION.Routes - .ToList () - .ForEach (routeDescriptor => { - ConsoleMessage ("==============================="); - ConsoleMessage ($"= Rote => {routeDescriptor.Route}"); - ConsoleMessage ("==============================="); - ConsoleMessage ($"AllowedRoles: {routeDescriptor.AllowedRoles.ToJSON()}"); - ConsoleMessage ($"AllowedScopes: {routeDescriptor.AllowedScopes.ToJSON()}"); - ConsoleMessage ($"EnableAuthorization: {routeDescriptor.EnableAuthorization}"); - ConsoleMessage ($"EnableXPoweredByAthorization: {routeDescriptor.EnableXPoweredByAthorization}"); - ConsoleMessage ($" "); - }); - } - - /// - /// Retrieve Destination Request Path based on Current Request ... - /// - /// - /// - private Uri GetUri (HttpRequest request) { - // - // Create temp result ... - Uri result = null; - var requestPath = ""; - - // - SendLog ($"Receive Request: {request.Path} ...", LogLevel.Information); - - // - // Try to Findout Route Descriptor ... - var routeDescriptor = GetRouteDescriptor (request); - - // - // Route Descriptor Exists && Path for Delegating ... - if (!routeDescriptor.IsNull () && - request.Path - .StartsWithSegments (routeDescriptor.Route) - ) { - // - // Prepare Request Path by Cleaning Starter Path Segment ... - requestPath = request.Path - .ToString () - .Replace (routeDescriptor.Route, ""); - if (requestPath.StartsWith ("/")) { - requestPath = requestPath.Substring (1); - } - - // - // Decoding URL ... - requestPath = HttpUtility.UrlDecode (requestPath); - - // - var colonIndex = requestPath.IndexOf (":"); - if (colonIndex > -1) { - // - var doubleSlash = requestPath.Substring (colonIndex + 1, 2); - var isDoubleSlash = doubleSlash == "//"; - - // - if (!isDoubleSlash) { - // - var protocol = requestPath - .Substring (0, colonIndex); - var section = requestPath - .Substring (colonIndex + 2, requestPath.Length - colonIndex - 2); - - // - requestPath = $"{protocol}://{section}"; - } - } - } - - // - // Validate Request Path ... - if (!requestPath.IsNullOrEmpty ()) { - // - result = new Uri (requestPath); - - // - SendLog ($"Process Request: {requestPath} ...", LogLevel.Information); - } - - // - return result; - } - - /// - /// Retrieve Propper Request Message based on HttpContext and uri ...F - /// - /// - /// - /// - private HttpRequestMessage GetRequestMessage ( - HttpContext context, - Uri uri - ) { - // - var result = new HttpRequestMessage (); - FillRequest (context, result); - - // - // Handle Queries ... - SendLog ($"Start Processing Queries: "); - foreach (var query in context.Request.Query) { - // - var key = query.Key; - var value = HttpUtility.UrlDecode (query.Value); - - // - uri = new Uri ( - QueryHelpers.AddQueryString ( - uri.OriginalString, - new Dictionary { - [key] = value - } - ) - ); - - // - SendLog ($"Query : {key}:{value} was Processed ..."); - } - - // - result.RequestUri = uri; - result.Headers.Host = uri.Host; - - // - // Retrieve Request Method ... - result.Method = GetMethod (context.Request.Method); - - // - return result; - } - - /// - /// Fill Request Message by provide HttpContext ... - /// - /// - /// - private void FillRequest ( - HttpContext context, - HttpRequestMessage message - ) { - // - var requestMethod = context.Request.Method; - - // - if (!HttpMethods.IsGet (requestMethod) && - !HttpMethods.IsHead (requestMethod) && - !HttpMethods.IsTrace (requestMethod) && - !HttpMethods.IsDelete (requestMethod) - ) { - // - var streamContent = new StreamContent (context.Request.Body); - message.Content = streamContent; - } - - // - // Handle Base Headers ... - var regularHeaders = context.Request.Headers - .Where (hr => hr.Key != XProxyConstants.XPROXY_ACCEPTED_HEADERS && - !hr.Key - .Contains ( - XProxyConstants.XPROXY_FORWARD_HEADER - ) - ); - - // - // Handle Aceepted Headers ... - IEnumerable acceptedHeaders = null; - var acceptedHeadersKeyValue = context.Request.Headers - .FirstOrDefault (hr => - hr.Key == XProxyConstants.XPROXY_ACCEPTED_HEADERS - ); - if (!acceptedHeadersKeyValue.IsNull ()) { - // - acceptedHeaders = acceptedHeadersKeyValue.Value - .ToString () - .ParseListString (); - - // - // Filter Regular Headers ... - if ( - regularHeaders.HasChild () && - acceptedHeaders.HasChild () - ) { - // - regularHeaders = regularHeaders - .Where (rhr => acceptedHeaders - .Contains (rhr.Key) - ); - } - } - foreach (var header in regularHeaders) { - // - SendLog ($"Adding Header: {header.Key}:{header.Value} ..."); - - // - message.Headers.Add ( - header.Key, - header.Value - .ToString () - ); - } - - // - // Handle ForWarded Headers ... - // Since Forward Headers is Custom kind, this means user actually need this - // Header, so there is no need to put them on AcceptedHeaders ... - var forwardHeaders = context.Request.Headers - .Where (hr => hr.Key - .Contains ( - XProxyConstants.XPROXY_FORWARD_HEADER - ) - ); - foreach (var header in forwardHeaders) { - // - var key = header.Key - .Replace ( - XProxyConstants.XPROXY_FORWARD_HEADER, - string.Empty - ); - - // - SendLog ($"Forwarding Header: {header.Key} to {key} ..."); - - // - message.Headers - .Add ( - key, - header.Value - .ToString () - ); - } - } - - /// - /// Retreive and Extract Method Type of HttpRequest ... - /// - /// - /// - private static HttpMethod GetMethod (string method) { - // - if (HttpMethods.IsDelete (method)) { - return HttpMethod.Delete; - } else if (HttpMethods.IsGet (method)) { - return HttpMethod.Get; - } else if (HttpMethods.IsHead (method)) { - return HttpMethod.Head; - } else if (HttpMethods.IsOptions (method)) { - return HttpMethod.Options; - } else if (HttpMethods.IsPost (method)) { - return HttpMethod.Post; - } else if (HttpMethods.IsPut (method)) { - return HttpMethod.Put; - } else if (HttpMethods.IsTrace (method)) { - return HttpMethod.Trace; - } - - // - return new HttpMethod (method); - } - - /// - /// add all headers exists in HttpResponse MEssage to Current Context Response Headers ... - /// - /// - /// - private void HandleResponseHeaders ( - HttpContext context, - HttpResponseMessage message - ) { - // - // Handle Message Headers ... - foreach (var header in message.Headers) { - context.Response.Headers[header.Key] = header.Value - .ToArray (); - } - - // - // Handle Message Content Headers ... - foreach (var header in message.Content.Headers) { - context.Response.Headers[header.Key] = header.Value - .ToArray (); - } - - // - context.Response.Headers.Remove ("transfer-encoding"); - } - - /// - /// Processing Response Content and Handle it on HttpContextResponse ... - /// - /// - /// - /// - private async Task ProcessResponseContent ( - HttpContext context, - HttpResponseMessage message - ) { - // - // Reading Content as Byte Array ... - var contentBytes = await message.Content - .ReadAsByteArrayAsync (); - - // - // Check ContentType of Response ... - if ( - IsContentOfType (message, XResponseContentTypes.HTML) || - IsContentOfType (message, XResponseContentTypes.JSON) || - IsContentOfType (message, XResponseContentTypes.JavaScript) - ) { - // - // If their String Content ... - var stringContent = Encoding.UTF8.GetString (contentBytes); - - // - // TODO: here we can change String Contents ... - - // - // Writing new Content to Response ... - await context.Response - .WriteAsync ( - stringContent, - Encoding.UTF8 - ); - } else { - // - // if they have non string content ... - await context.Response.Body - .WriteAsync ( - buffer: contentBytes, - offset: 0, - count: contentBytes.Length - ); - } - - // - SendLog ($"Response Content Processed ...", LogLevel.Information); - } - - /// - /// Check Content Type of Specific Response ... - /// - /// - /// - /// - private bool IsContentOfType ( - HttpResponseMessage response, - string type - ) { - // - // Create EMpty Result ... - var result = false; - - // - // Retrieve and Check Content Type of Response ... - if (response.Content?.Headers?.ContentType != null) { - result = response.Content.Headers.ContentType.MediaType == type; - } - - // - return result; - } - - /// - /// Retrieve and Extract Route Descriptor ... - /// - /// - /// - private XProxyRouteDescriptor GetRouteDescriptor (HttpRequest request) { - // - // Validate Args ... - if ( - CONFIGURATION.IsNull () || - !CONFIGURATION.Routes.HasChild () - ) { - return null; - } - - // - var result = CONFIGURATION.Routes - .FirstOrDefault (rd => !rd.Route.IsNullOrEmpty () && - request.Path - .StartsWithSegments (rd.Route - .ToNormalString () - ) - ); - - // - return result; - } - #endregion - } - - /// - /// Provide all requirements for Dependency Injection Handler ... - /// - public static class XDIHelperExtension { - /// - /// Retrieve XProxy Middelware Configuration from Configuration ... - /// - /// - /// - public static XProxyConfiguration GetXProxyConfiguration (this IConfiguration config) { - // - var xProxyConfiguration = config.GetSection (ConfigurationNodeNames.XPROXY_CONFIGURATION_NODE_NAME); - return xProxyConfiguration.Get (); - } - - /// - /// Register HTTP Handler for XProxy Server ... - /// - /// - /// - /// - public static void AddXProxyHttpHandler ( - this IServiceCollection services, - IConfiguration configuration, - HttpClientHandler httpHandler = null - ) { - // - var proxyConfig = configuration.GetXProxyConfiguration (); - if (proxyConfig.IsNull ()) { - throw XException.InvalidConfiguration.ToException (); - } - - // - services.AddXProxyHttpHandler ( - httpHandler: httpHandler, - configuration: proxyConfig - ); - } - - /// - /// Register HTTP Handler for XProxy Server ... - /// - /// - /// - /// - public static void AddXProxyHttpHandler ( - this IServiceCollection services, - XProxyConfiguration configuration, - HttpClientHandler httpHandler = null - ) { - // - if (configuration.IsNull ()) { - throw XException.InvalidConfiguration.ToException (); - } - - // - if (httpHandler.IsNull ()) { - httpHandler = new HttpClientHandler (); - } - - // - httpHandler.AllowAutoRedirect = configuration.AllowAutoRedirect; - - // - if (configuration.DisableSSLCheck) { - httpHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; - } - - // - services - .AddHttpClient (XProxyConstants.XPROXY_HTTP_CLIENT) - .ConfigurePrimaryHttpMessageHandler (() => { - return httpHandler; - }); - } - - /// - /// Register XProxy On Server ... - /// - /// - /// - /// - public static void AddXProxyServer ( - this IServiceCollection services, - IConfiguration configuration, - HttpClientHandler httpHandler = null - ) { - // - var proxyConfig = configuration.GetXProxyConfiguration (); - - // - services.AddXProxyServer ( - httpHandler: httpHandler, - configuration: proxyConfig - ); - } - - /// - /// Register XProxy On Server ... - /// - /// - /// - /// - public static void AddXProxyServer ( - this IServiceCollection services, - XProxyConfiguration configuration, - HttpClientHandler httpHandler = null - ) { - // - // Validate Args ... - if (configuration.IsNull ()) { - throw XException.InvalidConfiguration.ToException (); - } - - // - // Register Proxy Configuration ... - services.AddSingleton (configuration); - - // - // Regiter Proxy Handler ... - services.AddXProxyHttpHandler ( - httpHandler: httpHandler, - configuration: configuration - ); - } - - /// - /// Register XProxy On Server ... - /// - /// - /// - public static void AddXProxyClient ( - this IServiceCollection services, - IConfiguration configuration - ) { - // - var proxyConfig = configuration.GetXProxyConfiguration (); - - // - services.AddXProxyClient ( - configuration: proxyConfig - ); - } - - /// - /// Register XProxy On Client ... - /// - /// - /// - public static void AddXProxyClient ( - this IServiceCollection services, - XProxyConfiguration configuration - ) { - // - // Validate Args ... - if (configuration.IsNull ()) { - throw XException.InvalidConfiguration.ToException (); - } - - // - // Register Proxy Configuration ... - services.AddSingleton (configuration); - - // - // Register IXProxyHelper ... - services.AddSingleton (); - } - - /// - /// Adding XProxy Middleware to Applications ... - /// - /// - public static void UseXProxy (this IApplicationBuilder app) { - app.UseMiddleware (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Models\XBaseRestResponse.cs - -using RestSharp; - -namespace xIdentityService.Models -{ - public class XBaseRestResponse - { - public T Model { get; set; } - public IRestResponse Response { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Admin.cs - -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using System.Collections.Generic; -using xIdentityService.Constants; - -namespace xIdentityService.Providers { - public partial class XIdentityProvider { - // - #region Admin ... - /// - /// Ban Specific Users - /// - /// Authentication Tokens - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of banned users identifiers - public async Task> Ban ( - XTokenResponse tokens, - XUserNameIdRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull ( - tokens, - model - ) - .AddNotEmpty (tokens.AccessToken) - .AddNotZeroChilds (model.Ids) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.Ban); - request.AddJsonBody (model); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// UnBann Specific Users - /// - /// Authentication Tokens - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of unbanned users identifiers - public async Task> UnBan ( - XTokenResponse tokens, - XUserNameIdRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull ( - tokens, - model - ) - .AddNotEmpty (tokens.AccessToken) - .AddNotZeroChilds (model.Ids) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.UnBan); - request.AddJsonBody (model); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Check Specific User is Banned or not - /// - /// Authentication Tokens - /// specified user's identifier - /// a boolean value which represent user banned or not - public async Task IsBanned ( - XTokenResponse tokens, - string userSelectByParam - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty ( - userSelectByParam, - tokens.AccessToken - ) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.IsBanned, - @params : new Dictionary { { XParam.XUserSelectByParam.GetStringValue (), userSelectByParam } } - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Application.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xHttpService.Constants; -using xHttpService.Extensions; -using System.Collections.Generic; -using xIdentityService.Constants; - -namespace xIdentityService.Providers -{ - public partial class XIdentityProvider - { - // - #region Applications ... - // - #region Application ... - /// - /// Create Application ... - /// - /// - /// - /// - /// - public async Task CreateApplication( - XTokenResponse tokens, - XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.CreateApplication); - request.AddJsonBody(item); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Update Specified Application ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApplication( - XTokenResponse tokens, - int id, - XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UpdateApplication, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - request.AddJsonBody(item); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.PUT - ); - return response; - } - - /// - /// Remove Specified Application ... - /// - /// - /// - /// - /// - public async Task RemoveApplication( - XTokenResponse tokens, - int id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RemoveApplication, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.DELETE - ); - return response; - } - - /// - /// Get Specified Application ... - /// - /// - /// - /// - /// - public async Task GetApplication( - XTokenResponse tokens, - int id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.GetApplication, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Query Applications ... - /// - /// - /// - /// - /// - public async Task> QueryApplications( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryApplications); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get All Application ... - /// - /// - /// - /// - public async Task> GetAllApplications( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.GetAllApplications); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - - // - #region XApiKey ... - /// - /// Get Specified ApiKey ... - /// - /// - /// - /// - /// - public async Task GetApiKey( - XTokenResponse tokens, - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.GetApiKey, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Remove Specified ApiKey ... - /// - /// - /// - /// - /// - public async Task RemoveApiKey( - XTokenResponse tokens, - Guid id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RemoveApiKey, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.DELETE - ); - return response; - } - - /// - /// Update Specified ApiKey ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApiKey( - XTokenResponse tokens, - Guid id, - XApiKeyDto item, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddIsGuid(id) - .AddNotNull(item) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (id != item.Id) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UpdateApiKey, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - request.AddJsonBody(item); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.PUT - ); - return response; - } - - /// - /// Query ApiKeys ... - /// - /// - /// - /// - /// - public async Task> QueryApiKeys( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryApiKeys); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get All Specified ApiKeys ... - /// - /// - /// - /// - public async Task> GetAllApiKeys( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.GetAllApiKeys); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - - // - #region XApiKeyUsage ... - /// - /// Add Api Key Usage ... - /// - /// - /// - /// - /// - public async Task AddApiKeyUsage( - XTokenResponse tokens, - XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.AddApiKeyUsage); - request.AddJsonBody(item); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Get Specified Api Key Usage ... - /// - /// - /// - /// - /// - public async Task GetApiKeyUsage( - XTokenResponse tokens, - long id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.GetApiKeyUsage, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Remove Specified Api Key Usage ... - /// - /// - /// - /// - /// - public async Task RemoveApiKeyUsage( - XTokenResponse tokens, - long id, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RemoveApiKeyUsage, - @params: new Dictionary { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.DELETE - ); - return response; - } - - /// - /// Update Specified Api Key Usage ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApiKeyUsage( - XTokenResponse tokens, - long id, - XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (id <= 0 || id != item.Id) { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UpdateApiKeyUsage, - @params: new Dictionary - { - { XParam.XId.GetStringValue (), id.ToString() } - } - ); - request.AddJsonBody(item); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.PUT - ); - return response; - } - - /// - /// Query Api Key Usages ... - /// - /// - /// - /// - /// - public async Task> QueryApiKeyUsages( - XTokenResponse tokens, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryApiKeyUsages); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get All Api Key Usages ... - /// - /// - /// - /// - public async Task> GetAllApiKeyUsages( - XTokenResponse tokens, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.GetAllApiKeyUsages); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - - // - #region Custom ... - /// - /// Show Api Key ... - /// - /// - /// - /// - /// - /// - public async Task ShowApiKey( - XTokenResponse tokens, - Guid apiKeyId, - int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddIsGuid(apiKeyId) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.ShowApiKey, - @params: new Dictionary { - { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Create Api Key ... - /// - /// - /// - /// - /// - /// - public async Task CreateApiKey( - XTokenResponse tokens, - int applicationId, - XCreateApiKeyRequest createRequest, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotNull(createRequest) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.CreateApiKey, - @params: new Dictionary { - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - request.AddJsonBody(createRequest); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Remove Specified Api Key ... - /// - /// - /// - /// - /// - /// - public async Task RemoveApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddIsGuid(apiKeyId) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RemoveApiKeyCustom, - @params: new Dictionary { - { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.DELETE - ); - return response; - } - - /// - /// Rotate Specified Api Key ... - /// - /// - /// - /// - /// - /// - /// - public async Task RotateApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - XRotateApiKeyRequest rotateRequest, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddIsGuid(apiKeyId) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RotateApiKey, - @params: new Dictionary { - { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - request.AddJsonBody(rotateRequest); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - /// - public async Task RevokeApiKey( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddIsGuid(apiKeyId) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RevokeApiKey, - @params: new Dictionary { - { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Retrieve Specified Application's Api Keys ... - /// - /// - /// - /// - /// - public async Task> GetApiKeys( - XTokenResponse tokens, - int applicationId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.GetApiKeys, - @params: new Dictionary { - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Retrieve Specified Api Keys Usages ... - /// - /// - /// - /// - /// - /// - public async Task> GetApiKeyUsages( - XTokenResponse tokens, - int applicationId, - Guid apiKeyId, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddIsGuid(apiKeyId) - .AddNotEmpty( - tokens.AccessToken - ) - .ValidateGroupAsync(); - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.GetApiKeyUsages, - @params: new Dictionary { - { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, - { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } - } - ); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Validate Specifed Api Key ... - /// - /// - /// - /// - public async Task ValidateApiKey( - XApiKeyValidationRequest validationRequest, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(validationRequest) - .ValidateGroupAsync(); - - // - var client = GetRestClient(); - - // - var checksum = SecurityProvider.Encrypt(validationRequest.ToJSON()).ToMd5String(); - - // - var request = GetRestRequet( - XApiAccountEndpoint.ValidateApiKey, - headers: new Dictionary{ - { XHeader.ChecksumDigest.GetStringValue(), checksum } - } - ); - request.AddJsonBody(validationRequest); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Authentication.cs - -using System; -using xCommons.Extensions; -using IdentityModel.Client; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityService.Constants; - -namespace xIdentityService.Providers -{ - public partial class XIdentityProvider - { - // - #region Authentication Handlers ... - /// - /// Request for Discovery Document - /// - /// an instance of DiscoveryDocumentResponse - public async Task RequestDiscoveryDocument() - { - // - var httpClient = GetHttpClient(); - - // - try - { - // - var result = httpClient - .GetDiscoveryDocumentAsync(identityConfiguration.Authority) - .ContinueWith(docTask => - { - // - httpClient.Dispose(); - return docTask.Result; - }); - - // - return await result; - } - catch - { - throw XException.ActionFailed.ToException(); - } - } - - /// - /// Request AccessToken for Specific XApiScope - /// - /// a member of XApiScope - /// an instance of XTokenResponse - public async Task RequestScopeAccessToken(string scope) - { - // - // Validate Args ... - var scopeName = string.Empty; - try - { - scopeName = scope; // scope.GetStringValue (); - } - catch { } - if (scopeName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var client = GetRestClient(); - var request = GetRestRequet( - XApiAccountEndpoint.RequestScopeAccessToken, - headers: new Dictionary { { XParam.XScope.GetStringValue(), scope.ToString() } }); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - - // - // Save Token ... - if (!response.IsNull()) - { - await tokenProvider.AddOrUpdateToken(response); - } - - // - return response; - } - - /// - /// Validate a token - /// - /// Authentication Tokens - /// an instance of TokenIntrospectionResponse - public async Task Introspection(XTokenResponse model) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.AccessToken) - .ValidateGroupAsync(); - - // - var httpClient = GetHttpClient(); - - // - try - { - // - var discoDoc = await RequestDiscoveryDocument(); - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - var response = await httpClient.IntrospectTokenAsync(new TokenIntrospectionRequest - { - // - Address = discoDoc.IntrospectionEndpoint, - ClientId = identityConfiguration.ClientId, - ClientSecret = identityConfiguration.ClientSecret, - - // - Token = model.AccessToken - }); - if (response.IsError) - { - throw new Exception(response.Error); - } - - // - return response; - } - catch - { - throw XException.ActionFailed.ToException(); - } - } - - /// - /// Validate Specified Token Model ... - /// - /// - /// - public async Task Validate(XTokenResponse model) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.AccessToken) - .ValidateGroupAsync(); - - // - var httpClient = GetHttpClient(); - - // - TokenIntrospectionResponse response = null; - try - { - // - var discoDoc = await RequestDiscoveryDocument(); - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - response = await httpClient.IntrospectTokenAsync(new TokenIntrospectionRequest - { - // - Address = discoDoc.IntrospectionEndpoint, - ClientId = identityConfiguration.ClientId, - ClientSecret = identityConfiguration.ClientSecret, - - // - Token = model.AccessToken - }); - } - catch - { } - - // - return response; - } - - /// - /// Authenticate a User - /// - /// User Login Required Info, an instance of XLoginRequest - /// an instance of XTokenResponse - public async Task Authenticate(XLoginRequest model) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroup(); - - // - var client = GetRestClient(); - var request = GetRestRequet(XApiAccountEndpoint.Authenticate); - request.AddJsonBody(model); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - - // - // Save Token ... - if (!response.IsNull()) - { - await tokenProvider.AddOrUpdateToken(response); - } - - // - return response; - } - - /// - /// Do Login based on XLoginRequest - /// - /// User Login Required Info, an instance of XLoginRequest - /// an instance of XTokenResponse - public async Task Login(XLoginRequest model) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(model, model.Device) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroup(); - - // - var client = GetRestClient(); - var request = GetRestRequet(XApiAccountEndpoint.Login); - request.AddJsonBody(model); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - - // - if (!response.IsNull()) - { - // - var tokens = response.ToXTokenResponse(); - await tokenProvider.AddOrUpdateToken(tokens); - } - - // - return response; - } - - /// - /// Logout from System - /// - /// - /// - public async Task Logout(XTokenResponse model) - { - // - await validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.AccessToken) - .ValidateGroupAsync(); - - // - var isExists = await tokenProvider - .IsTokenExists(model.AccessToken); - if (isExists) - { - await tokenProvider - .RemoveToken(model.AccessToken); - } - } - - /// - /// Refresh Tokens - /// - /// Authentication Tokens - /// an instance of XTokenResponse - public async Task RefreshTokens(XTokenResponse model) - { - // - // Validate Args ... - validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.AccessToken, - model.RefreshToken - ) - .ValidateGroup(); - - // - var client = GetRestClient(model); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RefreshTokens, - headers: model.ToHeaderDictionary()); - request.AddJsonBody(model); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - if (!response.IsNull()) - { - await tokenProvider.UpdateToken(response); - } - - // - return response; - } - #endregion - - // - #region Password Actions Handlers ... - /// - /// Change Password - /// - /// Authentication Tokens - /// an instance of XActionRequest class which provider requirement for action - /// - public async Task ChangePassword( - XTokenResponse tokens, - XActionRequest model - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens, model) - .AddNotEmpty( - model.Lang, - model.Password, - model.NewPassword, - model.ReturnUrl) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Validate User Select By Param ... - var userSelectByParam = GetUserSelectByParam( - model, - forceNotNull: true, - excludes: null); - - // - var client = GetRestClient(tokens); - var request = GetRestRequet( - XApiAccountEndpoint.ChangePassword, - headers: tokens.ToHeaderDictionary()); - request.AddJsonBody(model); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Friendship.cs - -using xModels.Dtos; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xHttpService.Extensions; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityService.Constants; -using xIdentityModels.Navigations; - -namespace xIdentityService.Providers -{ - public partial class XIdentityProvider - { - // - #region Friendship ... - /// - /// Follow a User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - public async Task Follow( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.Follow, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Cancel Following Request - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// a boolean value - public async Task Cancel( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.Cancel, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Unfollow a Follower - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// - public async Task UnFollowFollower( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UnFollowFollower, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - } - - /// - /// Unfollow Following - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// - public async Task UnFollowFollowing( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UnFollowFollowing, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - } - - /// - /// Block a Follower - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - public async Task Block( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.Block, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Unblock a Blocked User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - public async Task UnBlock( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.UnBlock, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Accept a Following Request - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - public async Task AcceptRequest( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.AcceptRequest, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Reject a Following Request - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - public async Task RejectRequest( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.RejectRequest, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Get Friendship Info Model between Specific User and Current User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipInfoDto - public async Task GetFriendshipInfo( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.FriendshipInfo, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Check a User IsFollower of Requested User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// a boolean value - public async Task IsFollower( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.IsFollower, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Specific Follower - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - public async Task GetFollower( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.Follower, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Follower State of a User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipState - public async Task GetFollowerState( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.FollowerState, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Followers List Of Current User - /// - /// Authentication Tokens - /// a collection of XFriendshipFollower - public async Task> GetFollowers( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.Followers); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get All Followers List Includes Blocked, Requested and etc - /// of Current User - /// - /// Authentication Tokens - /// a collection of XFriendshipFollower - public async Task> GetAllFollowers( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.AllFollowers); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Return Followers UserName's List of Current User - /// - /// Authentication Tokens - /// a collection of UserNames - public async Task> GetFollowersList( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.FollowersList); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Retrieve All User's Followers based on Query Model ... - /// - /// Query Model Descriptor - /// Dest User for Reading Followers - /// Requester User's Descriptor - /// - public async Task> QueryFollowers( - XQuery query, - string destUser, - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(destUser) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryFollowers); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - request = request.AttachDestUser(destUser); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Check a User is in Followings of Current User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// a boolean value - public async Task IsFollowing( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.IsFollowing, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Specific Following Model - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - public async Task GetFollowing( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.Following, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Following State Relation between Specific User - /// and Current User - /// - /// Authentication Tokens - /// a user identifier which represent destination user - /// an instance of XFriendshipState - public async Task GetFollowingState( - XTokenResponse tokens, - string destUser - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty( - destUser, - tokens.AccessToken - ) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet( - XApiAccountEndpoint.FollowingState, - @params: new Dictionary { { XParam.XDestUser.GetStringValue (), destUser } - } - ); - - // - var response = await RunRestRequest( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get Followings of Current User - /// - /// Authentication Tokens - /// a collection of XFriendshipFollowing - public async Task> GetFollowings( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.Followings); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Get All Following List Includes Blocked, Requested and etc - /// of Current User - /// - /// Authentication Tokens - /// a collection of XFriendshipFollowing - public async Task> GetAllFollowings( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.AllFollowings); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Return Following UserName's List of Current User - /// - /// Authentication Tokens - /// a collection of UserNames - public async Task> GetFollowingList( - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.FollowingsList); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Retrieve All User's Followings based on Query Model ... - /// - /// Query Model Descriptor - /// Dest User for Reading Followers - /// Requester User's Descriptor - /// - public async Task> QueryFollowings( - XQuery query, - string destUser, - XTokenResponse tokens - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens) - .AddNotEmpty(destUser) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryFollowings); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - request = request.AttachDestUser(destUser); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Open.cs - -using System; -using System.Linq; -using MongoDB.Bson; -using xModels.Dtos; -using xCommons.Constants; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using System.Collections.Generic; -using xIdentityService.Constants; -using System.Runtime.InteropServices; - -namespace xIdentityService.Providers -{ - public partial class XIdentityProvider - { - /// - /// Prepare API Based Device to Open Actions ... - /// - /// - public XDeviceDto GetDevice() - { - // - var os = "XSaherElmOS"; - bool isOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - bool isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - if (isOSX) - { - os = "MacOs"; - } - else if (isLinux) - { - os = "Linux"; - } - else if (isWindows) - { - os = "Windows"; - } - var agent = RuntimeInformation.FrameworkDescription; - if (agent.IsNullOrEmpty()) - { - agent = "XSaherElmOSAgent"; - } - var version = RuntimeInformation.OSArchitecture + ", " + RuntimeInformation.OSDescription; - if (version.IsNullOrEmpty()) - { - version = "XSaherElmOSVersion"; - } - var browser = "XSaherElmBrowser_" + RevisionSecretKey.ToMd5String(); - - // - var result = new XDeviceDto - { - Os = os, - Browser = browser, - UserAgent = agent, - OsVersion = version, - DeviceType = XDeviceType.Desktop, - }; - - // - return result; - } - - // - #region OpenGet ... - public async Task OpenGet( - XOpenActionInnerDto model - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.Token) - .AddNotEmpty(model.Payload) - .ValidateGroupAsync(); - - // - var result = await OpenGet( - token: model.Token, - actionRequest: model.Payload - ); - - // - return result; - } - public async Task OpenGet( - string token, - string actionRequest - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotEmpty(token) - .AddNotEmpty(actionRequest) - .ValidateGroupAsync(); - - // - // Retrieve Rest Client ... - var client = GetRestClient(); - - // - // Prepare Rest Request ... - var request = GetRestRequet( - XApiAccountEndpoint.Open, - headers: new Dictionary - { - { XAuthentication.TOKEN, token} - }, - queryStrings: new Dictionary - { - { XParam.XRequest.GetStringValue(), actionRequest } - } - ); - - // - // Run Request and Retrieve Response ... - var response = await RunRestRequestByResponse( - client, - request, - XHttpMethod.GET - ); - - // - // Now we Have to Validate the recieved response ... - - // - // Read token from Headers ... - var responseToken = response.Response.Headers - .First(h => h.Name == XAuthentication.TOKEN).Value.ToString(); - if (responseToken.IsNullOrEmpty()) - { - XException.ActionFailed.Throw(); - } - - // - // Decript Recieve Response ... - var responseJson = response.Model; // SecurityProvider.Decrypt(response.Model); - if (responseJson.IsNullOrEmpty()) - { - XException.ActionFailed.Throw(); - } - - // - var result = new XOpenActionInnerDto - { - Token = responseToken, - Payload = responseJson - }; - - // - // Retrieve Model and Validate it ... - var responseModel = responseJson.FromJSON(); - if (responseModel.IsNull() || - responseModel.Payload.IsNullOrEmpty() || - responseToken != responseModel.Checksum || - responseModel.Timestamp.FromTimestamp().IsExPired()) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - #endregion - - // - #region GetApiKey ... - public async Task GetApiKey( - XDeviceDto device, - string apiKey - ) - { - // - // Validate Args ... - validationProvider.NotNull(device); - validationProvider.NotEmpty(apiKey); - - // - // Prepare Open Action Model ... - var opaModel = new XOpenActionRequestDto - { - Device = device, - Payload = apiKey, - Action = XOpenActions.GetApiKey, - Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString() - }; - if (!opaModel.Validate()) - { - XException.InvalidArgs.Throw(); - } - - // - // Fill Checksum Filed ... - var token = opaModel.ToOpenActionToken(); - opaModel.Checksum = token; - - // - // Prepare Request ... - var opaJson = opaModel.ToJson(); - var requestString = SecurityProvider.Encrypt(opaJson); - - // - return await GetApiKey( - token: token, - request: requestString - ); - } - - public async Task GetApiKey( - XOpenActionInnerDto dto - ) - { - // - return await GetApiKey( - token: dto.Token, - request: dto.Payload - ); - } - - public async Task GetApiKey( - string token, - string request - ) - { - // - // Validate Args ... - validationProvider.NotEmpty(token); - validationProvider.NotEmpty(request); - - // - // Retrieve and Validate Response ... - var response = await OpenGet( - token: token, - actionRequest: request - ); - if (response.IsNull() || - response.Token.IsNullOrEmpty() || - response.Payload.IsNullOrEmpty() - ) - { - XException.ActionFailed.Throw(); - } - - // - // Now we Have to Converts Repose Payload to Result Model ... - // Note that the respose Model's payload here is Decrypted and - // actually is Json Representation of Result Model ... - var requestModel = response.Payload.FromJSON(); - if (requestModel.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - var resultString = SecurityProvider.Decrypt(requestModel.Payload); - var result = new Guid(resultString); - if (result.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - #endregion - - // - #region UseApiKey ... - public async Task UseApiKey( - XDeviceDto device, - XApiKeyUsageDto apiKeyUsage - ) - { - // - // Validate Args ... - validationProvider.NotNull(device); - validationProvider.NotNull(apiKeyUsage); - - // - // Prepare Open Action Model ... - var opaModel = new XOpenActionRequestDto - { - Device = device, - Payload = apiKeyUsage.ToJSON(), - Action = XOpenActions.UseApiKey, - Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString() - }; - if (!opaModel.Validate()) - { - XException.InvalidArgs.Throw(); - } - - // - // Fill Checksum Filed ... - var token = opaModel.ToOpenActionToken(); - opaModel.Checksum = token; - - // - // Prepare Request ... - var opaJson = opaModel.ToJson(); - var requestString = SecurityProvider.Encrypt(opaJson); - - // - return await UseApiKey( - token: token, - request: requestString - ); - } - - public async Task UseApiKey( - XOpenActionInnerDto dto - ) - { - // - return await UseApiKey( - token: dto.Token, - request: dto.Payload - ); - } - - public async Task UseApiKey( - string token, - string request - ) - { - // - // Validate Args ... - validationProvider.NotEmpty(token); - validationProvider.NotEmpty(request); - - // - // Retrieve and Validate Response ... - var response = await OpenGet( - token: token, - actionRequest: request - ); - if (response.IsNull() || - response.Token.IsNullOrEmpty() || - response.Payload.IsNullOrEmpty() - ) - { - XException.ActionFailed.Throw(); - } - - // - // Now we Have to Converts Repose Payload to Result Model ... - // Note that the respose Model's payload here is Decrypted and - // actually is Json Representation of Result Model ... - var requestModel = response.Payload.FromJSON(); - if (requestModel.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - var resultJson = SecurityProvider.Decrypt(requestModel.Payload).ToNormalString(); - var result = resultJson.FromJSON(); - if (result.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - #endregion - - // - #region GetUserInfo ... - public async Task GetUserInfo( - XDeviceDto device, - string userSelectByParam - ) - { - // - // Validate Args ... - validationProvider.NotNull(device); - validationProvider.NotEmpty(userSelectByParam); - - // - // Prepare Open Action Model ... - var opaModel = new XOpenActionRequestDto - { - Device = device, - Payload = userSelectByParam, - Action = XOpenActions.GetUserInfo, - Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString() - }; - if (!opaModel.Validate()) - { - XException.InvalidArgs.Throw(); - } - - // - // Fill Checksum Filed ... - var token = opaModel.ToOpenActionToken(); - opaModel.Checksum = token; - - // - // Prepare Request ... - var opaJson = opaModel.ToJson(); - var requestString = SecurityProvider.Encrypt(opaJson); - - // - return await GetUserInfo( - token: token, - request: requestString - ); - } - - public async Task GetUserInfo( - XOpenActionInnerDto dto - ) - { - // - return await GetUserInfo( - token: dto.Token, - request: dto.Payload - ); - } - - public async Task GetUserInfo( - string token, - string request - ) - { - // - // Validate Args ... - validationProvider.NotEmpty(token); - validationProvider.NotEmpty(request); - - // - // Retrieve and Validate Response ... - var response = await OpenGet( - token: token, - actionRequest: request - ); - if (response.IsNull() || - response.Token.IsNullOrEmpty() || - response.Payload.IsNullOrEmpty()) - { - XException.ActionFailed.Throw(); - } - - // - // Now we Have to Converts Repose Payload to Result Model ... - // Note that the respose Model's payload here is Decrypted and - // actually is Json Representation of Result Model ... - var requestModel = response.Payload.FromJSON(); - if (requestModel.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - var resultJson = SecurityProvider.Decrypt(requestModel.Payload); - var result = resultJson.FromJSON(); - if (result.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - #endregion - - // - #region GetUserInfos ... - public async Task> GetUserInfos( - XDeviceDto device, - string ids - ) - { - // - // Validate Args ... - validationProvider.NotNull(device); - validationProvider.NotEmpty(ids); - - // - // Prepare Open Action Model ... - var opaModel = new XOpenActionRequestDto - { - Payload = ids, - Device = device, - Action = XOpenActions.GetUserInfos, - Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString() - }; - if (!opaModel.Validate()) - { - XException.InvalidArgs.Throw(); - } - - // - // Fill Checksum Filed ... - var token = opaModel.ToOpenActionToken(); - opaModel.Checksum = token; - - // - // Prepare Request ... - var opaJson = opaModel.ToJson(); - var requestString = SecurityProvider.Encrypt(opaJson); - - // - return await GetUserInfos( - token: token, - request: requestString - ); - } - - public async Task> GetUserInfos( - XOpenActionInnerDto dto - ) - { - // - return await GetUserInfos( - token: dto.Token, - request: dto.Payload - ); - } - - public async Task> GetUserInfos( - string token, - string request - ) - { - // - // Validate Args ... - validationProvider.NotEmpty(token); - validationProvider.NotEmpty(request); - - // - // Retrieve and Validate Response ... - var response = await OpenGet( - token: token, - actionRequest: request - ); - if (response.IsNull() || - response.Token.IsNullOrEmpty() || - response.Payload.IsNullOrEmpty()) - { - XException.ActionFailed.Throw(); - } - - // - // Now we Have to Converts Repose Payload to Result Model ... - // Note that the respose Model's payload here is Decrypted and - // actually is Json Representation of Result Model ... - var requestModel = response.Payload.FromJSON(); - if (requestModel.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - var resultJson = SecurityProvider.Decrypt(requestModel.Payload); - var result = resultJson.FromJSON>(); - if (result.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Profile.cs - -using xModels.Dtos; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xHttpService.Extensions; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xIdentityService.Constants; -using xIdentityModels.Navigations; - -namespace xIdentityService.Providers { - public partial class XIdentityProvider { - // - #region User Actions ... - /// - /// Retrieve User Names based on UserIds - /// - /// Authentication Tokens - /// a comma seperated list of UserIds - /// a collection of UserNames - public async Task> GetUserNames ( - XTokenResponse tokens, - string ids - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty (ids, tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - var request = GetRestRequet ( - XApiAccountEndpoint.GetNames, - @params : new Dictionary { { XParam.XIds.GetStringValue (), ids } } - ); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// get user ids and retrieve corresponding user names - /// - /// Authentication Tokens - /// an instance of XUserNameIdRequest which represent required UserIds collection - /// a collection of XUserNameIdResponse instance - public async Task> GetUserNameIds ( - XTokenResponse tokens, - XUserNameIdRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (model, tokens) - .AddNotZeroChilds (model.Ids) - .AddNotEmpty (tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - var request = GetRestRequet (XApiAccountEndpoint.GetNameIds); - request.AddJsonBody (model); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.POST - ); - return response; - } - #endregion - - // - #region Profile Actions ... - /// - /// Get Profile Object of Specific User - /// - /// Authentication Tokens - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - public async Task GetUserProfile ( - XTokenResponse tokens, - string userSelectByParam - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty (userSelectByParam, tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.GetProfile, - @params : new Dictionary { { XParam.XUserSelectByParam.GetStringValue (), userSelectByParam } } - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Retrieve Users Based On Query - /// - /// Authentication Tokens - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryUsers ( - XTokenResponse tokens, - XQuery query - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, query) - .AddNotEmpty (tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.QueryProfiles); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery (query); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Retrieve Users Based On Query and Specified role - /// - /// Authentication Tokens - /// an string which represent user role - /// how to filter results based on XQuery structure - /// if it's true the user must has exact role, otherwise top level users also listed - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryInRoleUsers ( - XTokenResponse tokens, - string role, - XQuery query, - bool forceRole = false - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, query) - .AddNotEmpty (tokens.AccessToken, role) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.QueryProfiles, - headers : new Dictionary { { XParam.XRole.GetStringValue (), role }, - { XParam.XForceRole.GetStringValue (), forceRole.AsHttpParamString () } - } - ); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery (query); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Query Specified User's Profile Images - /// - /// Authentication Tokens - /// determine's which user profile must be retrieved - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XProfileImage - public async Task> QueryAvatars ( - XTokenResponse tokens, - string userSelectByParam, - XQuery query - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, query) - .AddNotEmpty (tokens.AccessToken, userSelectByParam) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.QueryAvatars, - @params : new Dictionary { { XParam.XUserSelectByParam.GetStringValue (), userSelectByParam } - } - ); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery (query); - - // - var response = await RunRestRequest> ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Update User Profile based on XProfileUpdateRequest (FirstName/LastName/DateOfBirth) - /// - /// Authentication Tokens - /// determine's which user profile must be retrieved - /// user update info, an instance of XProfileUpdateRequest - /// an instance of XUserProfileDto - public async Task ProfileUpdateAsync ( - XTokenResponse tokens, - string userSelectByParam, - XProfileUpdateRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, model) - .AddNotEmpty (tokens.AccessToken, userSelectByParam) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.UpdateProfile, - @params : new Dictionary { { XParam.XUserSelectByParam.GetStringValue (), userSelectByParam } - } - ); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Update a User Profile based on XProfileUpdateRequest Full - /// - /// Authentication Tokens - /// determine's which user profile must be retrieved - /// user update info, an instance of XProfileUpdateRequest - /// an instance of XUserProfileDto - public async Task FullProfileUpdateAsync ( - XTokenResponse tokens, - string userSelectByParam, - XProfileUpdateRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, model) - .AddNotEmpty (tokens.AccessToken, userSelectByParam) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.FullUpdateProfile, - @params : new Dictionary { { XParam.XUserSelectByParam.GetStringValue (), userSelectByParam } - } - ); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Add a New Profile Image - /// - /// Authentication Tokens - /// an specific File to upload, IFormFile - /// an instance of XUserProfileDto - public async Task AddAvatar ( - XTokenResponse tokens, - IFormFile file - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens, file) - .AddNotEmpty (tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.AddAvatar); - request.AlwaysMultipartFormData = true; - request.AddFileBytes ( - XParam.XFile.GetStringValue (), - file.ToByteArray (), - file.FileName, - file.ContentType - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Add a New Collection of Profile Images - /// - /// Authentication Tokens - /// a collection of Files to upload, IFormFileCollection - /// an instance of XUserProfileDto - public async Task AddAvatars ( - XTokenResponse tokens, - IFormFileCollection files - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotZeroChilds (files) - .AddNotEmpty (tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.AddAvatars); - request.AlwaysMultipartFormData = true; - - // - // Add Files ... - foreach (var file in files) { - // - // Add Single file ... - request.AddFileBytes ( - XParam.XFiles.GetStringValue (), - file.ToByteArray (), - file.FileName, - file.ContentType - ); - } - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// set Specified Profile Image as Avatar - /// - /// Authentication Tokens - /// an integer which reperesent AvatarId to set as current Avatar - /// an instance of XUserProfileDto - public async Task SetAvatar ( - XTokenResponse tokens, - int id - ) { - // - // Validate Args ... - id.ValidateIntId (); - - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty (tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.SetAvatar, - @params : new Dictionary { { XParam.XId.GetStringValue (), id.ToString () } - } - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Remove Profile Images - /// - /// Authentication Tokens - /// a comma seperated list of avatarIds to remove - /// an instance of XUserProfileDto - public async Task RemoveAvatars ( - XTokenResponse tokens, - string avatarIds - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty (avatarIds, tokens.AccessToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet ( - XApiAccountEndpoint.RemoveAvatars, - @params : new Dictionary { { XParam.XIds.GetStringValue (), avatarIds } - } - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.DELETE - ); - return response; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Registration.cs - -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityService.Constants; - -namespace xIdentityService.Providers { - public partial class XIdentityProvider { - // - #region Registration ... - /// - /// Check a User Selector is Available for Registration or Not - /// - /// an string value which reperesent a user - /// a boolean value - public async Task CanRegister (string userSelectByParam) { - // - // Validate ARgs ... - validationProvider.NotEmpty (userSelectByParam); - - // - var client = GetRestClient (); - - // - // Check Endpoint ... - var endpoint = XApiAccountEndpoint.CanRegisterUserName; - var @params = new Dictionary { { XParam.XUserName.GetStringValue (), userSelectByParam } }; - - // - // Check UserSelectByType ... - var type = userSelectByParam.GetUserSelectByType (); - switch (type) { - // - case XUserSelectBy.Username: - break; - - // - case XUserSelectBy.MobileNumber: - // - endpoint = XApiAccountEndpoint.CanRegisterMobileNumber; - @params = new Dictionary { { XParam.XMobileNumber.GetStringValue (), userSelectByParam } }; - break; - - // - case XUserSelectBy.Email: - // - endpoint = XApiAccountEndpoint.CanRegisterEmail; - @params = new Dictionary { { XParam.XEmail.GetStringValue (), userSelectByParam } }; - break; - - // - default: - throw XException.InvalidData.ToException (); - } - - // - var request = GetRestRequet ( - endpoint, - @params: @params - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Invite a User to Register on Dashboard - /// - /// Authentication Tokens - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task InviteUser ( - XTokenResponse tokens, - XActionRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull ( - tokens, - model, - model.Device) - .AddNotEmpty ( - tokens.AccessToken, - model.Lang, - model.Email, - model.ReturnUrl) - .AddEmailAddress (model.Email) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.InviteUser); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Recieve some Basic Informations and Start Registration Proccess - /// if they Valid - /// - /// Registration Proccess Starts with Invoking this Action - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task RequestRegistration ( - XActionRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull ( - model, - model.Device, - model.DateOfBirth) - .AddNotEmpty ( - model.Lang, - model.FirstName, - model.LastName) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.RequestRegistration); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Add User Account Informations - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task AddAccountInfo ( - XActionRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull ( - model, - model.Device) - .AddNotEmpty ( - model.Lang, - model.UserName, - model.Password, - model.ActionToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.AddAccountInfo); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Upload and Attach a Profile Image for User. this is an Optional Step - /// - /// user's requested action token - /// an instance of IFormFile for user's Avatar - /// an instance of XActionResponse - public async Task AttachProfileImage ( - string actionToken, - IFormFile file - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (file) - .AddNotEmpty (actionToken) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.AttachProfileImage); - - // - // Prepare Request Data ... - request.AddParameter (XParam.XActionToken.GetStringValue (), actionToken); - request.AddFileBytes ( - XParam.XFile.GetStringValue (), - file.ToByteArray (), - file.FileName, - file.ContentType - ); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Finish Registrationn Proccess - /// - /// an instance of XActionRequest class which provider requirement for action - /// - public async Task FinishRegistration (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - // Create Http Client ... - var client = GetRestClient (); - - // - // Create Request ... - var request = GetRestRequet (XApiAccountEndpoint.FinishRegistration); - - // - // Prepare Request Data ... - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - } - - /// - /// Check User is Confirmed Email or not - /// - /// Authentication Tokens - /// an string value which reperesent a user - /// a boolean value - public async Task IsConfirmedEmail ( - XTokenResponse tokens, - string userSelectByParam - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty ( - tokens.AccessToken, - userSelectByParam) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.IsConfirmedEmail); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Check User is Confirmed Mobile or not - /// - /// Authentication Tokens - /// an string value which reperesent a user - /// a boolean value - public async Task IsConfirmedMobile ( - XTokenResponse tokens, - string userSelectByParam - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (tokens) - .AddNotEmpty ( - tokens.AccessToken, - userSelectByParam) - .ValidateGroupAsync (); - - // - var client = GetRestClient (tokens); - - // - var request = GetRestRequet (XApiAccountEndpoint.IsConfirmedMobile); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.GET - ); - return response; - } - - /// - /// Request Registration Confirm - /// - /// an instance of XActionRequest class which provider requirement for action - /// - public async Task RequestConfirmRegistration (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = model.GetUserSelectByParam (); - validationProvider.NotEmpty (userSelectByParam); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.RequestConfirmRegistration); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - } - - /// - /// Confirm Registration - /// - /// an instance of XActionRequest class which provider requirement for action - /// - public async Task ConfirmRegistration ( - XActionRequest model - ) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.ReturnUrl - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.ConfirmRegistration); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - } - - /// - /// Request For Mobile Number Change/Confirm - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task RequestConfirmMobile (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Password, - model.MobileNumber - ) - .AddNotNull (model.Device) - .AddMobileNumber (model.MobileNumber) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.RequestConfirmMobile); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Confirm Requested Mobile Number - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task ConfirmMobileNumber (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.MobileVerificationCode - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.ConfirmMobileNumber); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Request For Email Address Change/Confirm - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task RequestConfirmEmail (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.Email, - model.Password) - .AddNotNull (model.Device) - .AddEmailAddress (model.Email) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.RequestConfirmEmail); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Confirm Requested Email Address - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task ConfirmEmailAddress (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.EmailVerificationCode - ) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.ConfirmEmailAddress); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Request Reset Password Action - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - public async Task RequestResetPassword (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotEmpty ( - model.Lang, - model.ReturnUrl) - .AddNotNull (model.Device) - .AddUrl (model.ReturnUrl) - .ValidateGroupAsync (); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam ( - model, - excludes : new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.RequestResetPassword); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - return response; - } - - /// - /// Reset a User's Password - /// - /// an instance of XActionRequest class which provider requirement for action - /// - public async Task ResetPassword (XActionRequest model) { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder () - .AddNotNull (model) - .AddNotEmpty ( - model.Lang, - model.ActionToken, - model.NewPassword, - model.ReturnUrl) - .AddNotNull (model.Device) - .ValidateGroupAsync (); - - // - var client = GetRestClient (); - - // - var request = GetRestRequet (XApiAccountEndpoint.ResetPassword); - request.AddJsonBody (model); - - // - var response = await RunRestRequest ( - client, - request, - XHttpMethod.POST - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Partial\XIdentityProvider+Search.cs - -using xModels.Dtos; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xHttpService.Extensions; -using xIdentityService.Constants; - -namespace xIdentityService.Providers -{ - public partial class XIdentityProvider - { - // - #region Actions ... - /// - /// Query Open To Search User Profiles ... - /// - /// requested user's identifiers - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryOpenToSearchUsers( - XTokenResponse tokens, - XQuery query - ) - { - // - // Validate Args ... - await validationProvider - .GroupValidationBuilder() - .AddNotNull(tokens, query) - .AddNotEmpty(tokens.AccessToken) - .ValidateGroupAsync(); - - // - var client = GetRestClient(tokens); - - // - var request = GetRestRequet(XApiAccountEndpoint.QueryOpenToSearchProfiles); - - // - // Attach XQuery to Request ... - request = request.AttachXQuery(query); - - // - var response = await RunRestRequest>( - client, - request, - XHttpMethod.GET - ); - return response; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XBaseIdentityHttpProvider.cs - -using System; -using System.IO; -using RestSharp; -using System.Linq; -using System.Net.Http; -using System.Threading; -using xCommons.Constants; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xIdentityService.Models; -using RestSharp.Authenticators; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityService.Constants; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xIdentityService.Providers -{ - /// - /// an abstraction Implementation for Identity Provided Http Based Services ... - /// - public abstract class XBaseIdentityHttpProvider : IXBaseIdentityHttpProvider - { - /// - /// Client Base Url ... - /// - /// - public string BaseUrl { get; } - - /// - /// Logger ... - /// - /// - public ILogger Logger { get; } - - /// - /// Powered Value ... - /// - /// - public string XPoweredValue { get; } - - /// - /// Default Client Timeout ... - /// - /// - public int DefaultClientTimeout { get; } - - /// - /// Default Buffering Chunk Size ... - /// - /// - public int DefaultBufferingChunckSize { get; } - - /// - /// Validation Provider ... - /// - /// - public XValidationProvider ValidationProvider { get; } - - /// - /// Token Provider ... - /// - private readonly IXTokenProvider tokenProvider; - - /// - /// Identity Provider ... - /// - private readonly IXIdentityProvider identityProvider; - - public XBaseIdentityHttpProvider( - string baseUrl, - ILogger logger, - string poweredValue, - int defaultClientTimeout, - IXTokenProvider tokenProvider, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - int defaultBufferingChunckSize = 8192 - ) - { - // - Logger = logger; - BaseUrl = baseUrl; - XPoweredValue = poweredValue; - this.tokenProvider = tokenProvider; - ValidationProvider = validationProvider; - this.identityProvider = identityProvider; - DefaultClientTimeout = defaultClientTimeout; - DefaultBufferingChunckSize = defaultBufferingChunckSize; - } - - // - #region Tools ... - /// - /// Get an Instance of Http Client - /// - /// - public HttpClient GetHttpClient(XTokenResponse tokens = null) - { - // - HttpClient httpClient = null; - - // - // httpClient = new HttpClient (); - var httpClientHandler = new HttpClientHandler() - { - ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => - { - // - Logger.LogInformation( - $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" - ); - - // - return true; - }, - ClientCertificateOptions = ClientCertificateOption.Manual, - }; - httpClient = new HttpClient(httpClientHandler); - - // - // Set Authenticator ... - if (!tokens.IsNull() && - !tokens.AccessToken.IsNullOrEmpty()) - { - // - httpClient.DefaultRequestHeaders - .Add( - XAuthorization.Header, - $"{XAuthentication.BEARER} {tokens.AccessToken}"); - } - - // - // Refresh Token ... - if (!tokens.IsNull() && - !tokens.RefreshToken.IsNullOrEmpty()) - { - // - httpClient.DefaultRequestHeaders - .Add( - XAuthorization.RefreshToken, - tokens.RefreshToken); - } - - // - // ExpiresAt ... - if (!tokens.IsNull() && - tokens.ExpiresAt > 0) - { - // - httpClient.DefaultRequestHeaders - .Add( - XAuthorization.ExpiresAt, - tokens.ExpiresAt.AsHttpParamString()); - } - - // - // Set Default Timeout ... - httpClient.Timeout = TimeSpan.FromSeconds(DefaultClientTimeout == -1 ? 10000 : DefaultClientTimeout); - - // - return httpClient; - } - public HttpClient GetHttpClient(XUserClaimsInfoDto userInfo = null) - { - // - XTokenResponse tokens = ToTokenResponse(userInfo); - - // - return GetHttpClient(tokens); - } - - /// - /// Get an Instance of RestClient - /// - /// - public RestClient GetRestClient(XTokenResponse tokens = null) - { - // - var client = new RestClient(BaseUrl); - - // - // Set Authenticator ... - if (!tokens.IsNull() && - !tokens.AccessToken.IsNullOrEmpty()) - { - client.Authenticator = new JwtAuthenticator(tokens.AccessToken); - } - - // - // Refresh Token ... - if (!tokens.IsNull() && - !tokens.RefreshToken.IsNullOrEmpty()) - { - client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken); - } - - // - // ExpiresAt ... - if (!tokens.IsNull() && - tokens.ExpiresAt > 0) - { - client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString()); - } - - // - // Set Default Timeout ... - client.Timeout = DefaultClientTimeout; - - // - // SSL Validation Handler ... - client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => - { - // - Logger.LogInformation( - $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" - ); - - // - return true; - }; - - // - return client; - } - public RestClient GetRestClient(XUserClaimsInfoDto userInfo = null) - { - // - XTokenResponse tokens = ToTokenResponse(userInfo); - - // - return GetRestClient(tokens); - } - - /// - /// Get an Instance of RestRequest - /// - /// - /// - /// - /// - /// - /// - public RestRequest GetRestRequet( - Enum endpoint, - bool addXPoweredValue = true, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null - ) - { - // - var url = PrepareUrl( - @params: @params, - endpoint: endpoint, - queryStrings: queryStrings - ); - - // - // Create request ... - var request = new RestRequest(url, DataFormat.Json); - - // - if (addXPoweredValue) - { - request.AddHeader(XAuthorization.XPoweredBy, XPoweredValue); - } - - // - // Add Headers to request ... - if (!headers.IsNull() && headers.Count > 0) - { - // - var enumerator = headers.GetEnumerator(); - while (enumerator.MoveNext()) - { - // - var item = enumerator.Current; - request.AddHeader(item.Key, item.Value); - } - } - - // - return request; - } - - /// - /// Handle Call Specific Request and retrieve Response - /// - /// - /// - /// - /// - /// - /// - /// - public async Task RunRestRequest( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true, - CancellationToken cancellationToken = default - ) - { - // - var response = await Task.Run(async () => - { - // - IRestResponse resp = null; - - // - // Call Endpoint Service using Specified Method ... - switch (method) - { - // - // Get ... - case XHttpMethod.GET: - resp = client.Get(request); - break; - - // - // Put ... - case XHttpMethod.PUT: - resp = client.Put(request); - break; - - // - // Post ... - case XHttpMethod.POST: - resp = client.Post(request); - break; - - // - // Delete ... - case XHttpMethod.DELETE: - resp = client.Delete(request); - break; - } - - // - if (!resp.IsSuccessful) - { - // - // Log Exception ... - Logger.LogError($"Error: {resp.ErrorMessage}"); - Logger.LogError($"Exception: {resp.ErrorException.ToJSON()}"); - if (!resp.ErrorMessage.IsNullOrEmpty() && - resp.ErrorMessage.Contains("timed out")) - { - XException.Timeout.Throw(); - } - - // - // TODO: Check UnAuthorized Status here for - // Refresh Tokens or Issue Correct Exception ... - if (supportRefreshingTokens && - resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) - { - // - var isRefreshed = request.Parameters.Any(rp => - rp.Name == XParam.XIsRefreshed.GetStringValue() && - rp.Value.ToString().ToNormalString() == true.ToJSON()); - - // - Logger.LogInformation($"isRefreshed: {isRefreshed}"); - - // - // Get Access Token ... - XTokenResponse tokens = null; - var accessToken = request.Parameters.FirstOrDefault(rp => - rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString(); - if (!accessToken.IsNullOrEmpty()) - { - // - accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, ""); - - // - if (!accessToken.IsNullOrEmpty()) - { - tokens = await tokenProvider.RetrieveToken(accessToken); - } - } - - // - // Refresh Token and then re do request ... - if (!isRefreshed && - !accessToken.IsNullOrEmpty() && - !tokens.IsNull() && - tokens.IsRefreshable()) - { - // - request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON()); - - // - // Refreshe Tokens ... - var refreshedTokens = await identityProvider - .RefreshTokens(tokens); - - // - // Renew Rest Client with Refreshed Tokens ... - var timeout = client.Timeout; - client = GetRestClient(refreshedTokens); - client.Timeout = Timeout.Infinite; - - // - // Do Request Again using renew Client ... - return await RunRestRequest( - client: client, - request: request, - method: method); - } - } - - // - var ex = resp.Content.ToXError(); - if (!ex.IsNull()) - { - throw ex.ToException(); - } - - // - // UnAuthorized ... - if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) - { - XException.NotAuthorized.Throw(); - } - - // - // NotFound ... - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) - { - XException.NotFound.Throw(); - } - - // - XException.ActionFailed.Throw(); - } - - // - var result = resp.Content.FromJSON(); - return result; - }, - cancellationToken: cancellationToken); - - // - return response; - } - - /// - /// Access a Get Request Stream as AsyncEnumerable ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task StreamData( - Enum endpoint, - int bufferLength = 8194, - bool addXPoweredValue = true, - XTokenResponse tokens = null, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null, - [System.Runtime.CompilerServices.EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - var url = PrepareUrl( - @params: @params, - endpoint: endpoint, - attachBaseUrl: true, - queryStrings: queryStrings - ); - var client = GetHttpClient(tokens); - if (addXPoweredValue) - { - // - client.DefaultRequestHeaders - .Add( - XAuthorization.XPoweredBy, - XPoweredValue - ); - } - - // - // For SSE, you might want to set the Accept header, though not strictly necessary for just streaming - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept - .Add( - new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/event-stream")); - - // - var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - response.EnsureSuccessStatusCode(); - - // - var stream = await response.Content.ReadAsStreamAsync(); - - // - return stream; - - // using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) - // { - // // - // int readedBuffers = 0; - // response.EnsureSuccessStatusCode(); - // var buffer = new byte[bufferLength]; - // var stream = await response.Content.ReadAsStreamAsync(); - - // // - // while ((readedBuffers = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) - // { - // // - // var content = buffer.FromBytes(); - // Console.WriteLine(content); - // } - - // // await foreach (var message in stream) { - // // Console.WriteLine(message); - // // } - - // // await foreach (var item in stream.ToAsyncEnumerable(cancellationToken: cancellationToken)) - // // { - // // // - // // Console.WriteLine(item); - - // // // T value = item.IsNull() - // // // ? default(T) - // // // : item.FromBytes().FromJSON(); - - // // // // - // // // yield return value; - // // } - // } - - /// - /// - /// - /// - - // - // var eventSource = new EventSource(url); - // // eventSource. - - // // var client = GetHttpClient(tokens); - // // if (addXPoweredValue) - // // { - // // // - // // client.DefaultRequestHeaders - // // .Add( - // // XAuthorization.XPoweredBy, - // // XPoweredValue); - // // } - - // // // - // // // For SSE, you might want to set the Accept header, though not strictly necessary for just streaming - // // client.DefaultRequestHeaders.Accept.Clear(); - // // client.DefaultRequestHeaders.Accept - // // .Add( - // // new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/event-stream")); - - // // // - // // using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) - // // { - // // // - // // response.EnsureSuccessStatusCode(); - // // var stream = await response.Content.ReadAsStreamAsync(); - // // await foreach (var item in stream.ToAsyncEnumerable(cancellationToken: cancellationToken)) - // // { - // // // - // // T value = item.IsNull() - // // ? default(T) - // // : item.FromBytes().FromJSON(); - - // // // - // // yield return value; - // // } - // // } - } - - /// - /// Handle Call Specified Request and Retrieve XBaseRestResponse ... - /// - /// - /// - /// - /// - /// - /// - /// an instance of XBaseRestResponse - public async Task> RunRestRequestByResponse( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true, - CancellationToken cancellationToken = default - ) - { - // - var response = await Task.Run(async () => - { - // - IRestResponse resp = null; - - // - // Call Endpoint Service using Specified Method ... - switch (method) - { - // - // Get ... - case XHttpMethod.GET: - resp = client.Get(request); - break; - - // - // Put ... - case XHttpMethod.PUT: - resp = client.Put(request); - break; - - // - // Post ... - case XHttpMethod.POST: - resp = client.Post(request); - break; - - // - // Delete ... - case XHttpMethod.DELETE: - resp = client.Delete(request); - break; - } - - // - if (!resp.IsSuccessful) - { - // - // Log Exception ... - Logger.LogError($"Error: {resp.ErrorMessage}"); - Logger.LogError($"Exception: {resp.ErrorException.ToJSON()}"); - if (!resp.ErrorMessage.IsNullOrEmpty() && - resp.ErrorMessage.Contains("timed out")) - { - XException.Timeout.Throw(); - } - - // - // TODO: Check UnAuthorized Status here for - // Refresh Tokens or Issue Correct Exception ... - if (supportRefreshingTokens && - resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) - { - // - var isRefreshed = request.Parameters.Any(rp => - rp.Name == XParam.XIsRefreshed.GetStringValue() && - rp.Value.ToString().ToNormalString() == true.ToJSON()); - - // - Logger.LogInformation($"isRefreshed: {isRefreshed}"); - - // - // Get Access Token ... - XTokenResponse tokens = null; - var accessToken = request.Parameters.FirstOrDefault(rp => - rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString(); - if (!accessToken.IsNullOrEmpty()) - { - // - accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, ""); - - // - if (!accessToken.IsNullOrEmpty()) - { - tokens = await tokenProvider.RetrieveToken(accessToken); - } - } - - // - // Refresh Token and then re do request ... - if (!isRefreshed && - !accessToken.IsNullOrEmpty() && - !tokens.IsNull() && - tokens.IsRefreshable()) - { - // - request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON()); - - // - // Refreshe Tokens ... - var refreshedTokens = await identityProvider - .RefreshTokens(tokens); - - // - // Renew Rest Client with Refreshed Tokens ... - var timeout = client.Timeout; - client = GetRestClient(refreshedTokens); - client.Timeout = Timeout.Infinite; - - // - // Do Request Again using renew Client ... - return await RunRestRequestByResponse( - client: client, - request: request, - method: method - ); - } - } - - // - var ex = resp.Content.ToXError(); - if (!ex.IsNull()) - { - throw ex.ToException(); - } - - // - // UnAuthorized ... - if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) - { - XException.NotAuthorized.Throw(); - } - - // - // NotFound ... - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) - { - XException.NotFound.Throw(); - } - - // - XException.ActionFailed.Throw(); - } - - // - var result = new XBaseRestResponse - { - Response = resp, - Model = resp.Content.FromJSON() - }; - - // - return result; - }, - cancellationToken: cancellationToken); - - // - return response; - } - - /// - /// Get User SelectBy Param - /// - /// - /// - /// - /// - public string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(model); - - // - var id = model.UserId; - var userName = model.UserName; - var email = model.Email; - var phoneNumber = model.MobileNumber; - - // - if (excludes != null) - { - // - if (excludes.Contains(XUserSelectBy.ID)) - { - id = null; - } - if (excludes.Contains(XUserSelectBy.Email)) - { - email = null; - } - if (excludes.Contains(XUserSelectBy.MobileNumber)) - { - phoneNumber = null; - } - if (excludes.Contains(XUserSelectBy.Username)) - { - userName = null; - } - } - - var selectByParam = - id.IsNullOrEmpty() ? - userName.IsNullOrEmpty() ? - email.IsNullOrEmpty() ? - phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; - - // - // Check result ... - if (forceNotNull && - selectByParam.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - return selectByParam; - } - - /// - /// Prepare Url Address of Specified Enum by Filling Params - /// and Query Strings Attach ... - /// - /// - /// - /// - /// - /// - public string PrepareUrl( - Enum endpoint, - bool attachBaseUrl = false, - IDictionary @params = null, - IDictionary queryStrings = null - ) - { - // - // Retrieving Url Template ... - var url = endpoint.GetStringValue(); - - // - // Filling Parmas and Query Strings of Url ... - url = PrepareUrl( - url: url, - @params: @params, - queryStrings: queryStrings, - attachBaseUrl: attachBaseUrl - ); - - // - return url; - } - - /// - /// Prepare Url Address by Filling Params - /// and Query Strings Attach ... - /// - /// - /// - /// - /// - /// - public string PrepareUrl( - string url, - bool attachBaseUrl = false, - IDictionary @params = null, - IDictionary queryStrings = null - ) - { - // - if (attachBaseUrl) - { - // - var baseUrl = BaseUrl; - if (!baseUrl.EndsWith("/")) - { - baseUrl = $"{baseUrl}/"; - } - - // - url = $"{baseUrl}{url}"; - } - - // - // Add Route Payloads ... - if (!@params.IsNull() && @params.Count > 0) - { - // - var enumerator = @params.GetEnumerator(); - while (enumerator.MoveNext()) - { - // - var item = enumerator.Current; - - // - url = url.Replace(item.Key, item.Value.ToUrlEncoded()); - } - } - - // - // Add Query Strings ... - if (!queryStrings.IsNull() && queryStrings.Count > 0) - { - // - url = $"{url}?"; - var enumerator = queryStrings.GetEnumerator(); - while (enumerator.MoveNext()) - { - // - var item = enumerator.Current; - - // - url += $"{item.Key}={item.Value.ToUrlEncoded()}&"; - } - - // - // remove lates & ... - if (url.EndsWith("&")) - { - url = url.Substring(0, url.Length - 1); - } - } - - // - return url; - } - - /// - /// Converts UserInfo to TokenResponse model ... - /// - /// - /// - public XTokenResponse ToTokenResponse(XUserClaimsInfoDto userInfo = null) - { - // - XTokenResponse result = null; - - // - if (!userInfo.IsNull()) - { - // - result = new XTokenResponse - { - AccessToken = userInfo.AccessToken.IsNullOrEmpty() - ? "" - : userInfo.AccessToken, - RefreshToken = userInfo.RefreshToken.IsNullOrEmpty() - ? "" - : userInfo.RefreshToken, - ExpiresAt = userInfo.ExpiresAt, - }; - - // - if (userInfo.AccessToken.IsNullOrEmpty()) - { - result = null; - } - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XIdentityProvider.cs - -using System; -using RestSharp; -using System.Linq; -using System.Net.Http; -using Newtonsoft.Json; -using System.Threading; -using xCommons.Constants; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xHttpService.Constants; -using xIdentityModels.Models; -using xIdentityService.Models; -using RestSharp.Authenticators; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityService.Constants; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Serialization; -using xIdentityService.Configuration; - -namespace xIdentityService.Providers { - public partial class XIdentityProvider : IXIdentityProvider { - private readonly IXTokenProvider tokenProvider; - private readonly IHostingEnvironment environment; - private JsonSerializerSettings jsonSerializerSettings; - private readonly XValidationProvider validationProvider; - private readonly XIdentityServiceConfiguration identityConfiguration; - - public ILogger Logger { get; } - public IXSecurityProvider SecurityProvider { get; } - - public string BaseUrl { get; } - public string RevisionSecretKey { get; } - public bool ReadResponseAsString { get; set; } - - public XIdentityProvider ( - IXTokenProvider tokenProvider, - IHostingEnvironment environment, - ILogger logger, - IXSecurityProvider securityProvider, - XIdentityServiceConfiguration identityConfiguration, - XValidationProvider validationProvider - ) { - // - BaseUrl = identityConfiguration.Authority; - RevisionSecretKey = identityConfiguration.XRevisionSecretKey; - - // - this.environment = environment; - Logger = logger; - SecurityProvider = securityProvider; - - // - this.identityConfiguration = identityConfiguration; - this.validationProvider = validationProvider; - this.jsonSerializerSettings = new JsonSerializerSettings { - ContractResolver = new CamelCasePropertyNamesContractResolver () - }; - - // - this.tokenProvider = tokenProvider; - } - - // - #region Tools ... - /// - /// Get an Instance of Http Client - /// - /// - public HttpClient GetHttpClient () { - // - HttpClient httpClient = null; - - // - // httpClient = new HttpClient (); - var httpClientHandler = new HttpClientHandler () { - ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { - // - Logger.LogInformation ( - $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" - ); - - // - return true; - }, - ClientCertificateOptions = ClientCertificateOption.Manual, - }; - httpClient = new HttpClient (httpClientHandler); - - // - // Set Timeout ... - // TODO: Fix this ... - // httpClient.Timeout = TimeSpan - // .FromSeconds (identityConfiguration.DefaultClientTimeout); - - // - return httpClient; - } - - /// - /// Get an Instance of RestClient - /// - /// - public RestClient GetRestClient (XTokenResponse tokens = null) { - // - var client = new RestClient (BaseUrl); - - // - // Set Authenticator ... - if (!tokens.IsNull () && - !tokens.AccessToken.IsNullOrEmpty ()) { - client.Authenticator = new JwtAuthenticator (tokens.AccessToken); - } - - // - // Refresh Token ... - if (!tokens.IsNull () && - !tokens.RefreshToken.IsNullOrEmpty ()) { - client.AddDefaultHeader (XAuthorization.RefreshToken, tokens.RefreshToken); - } - - // - // ExpiresAt ... - if (!tokens.IsNull () && - tokens.ExpiresAt > 0) { - client.AddDefaultHeader (XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString ()); - } - - // - // Set Default Timeout ... - client.Timeout = identityConfiguration.DefaultClientTimeout; - - // - // SSL Validation Handler ... - client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => { - // - Logger.LogInformation ( - $"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" - ); - - // - return true; - }; - - // - return client; - } - - /// - /// Get an Instance of RestRequest - /// - public RestRequest GetRestRequet ( - XApiAccountEndpoint endpoint, - bool addXPoweredValue = true, - IDictionary @params = null, - IDictionary headers = null, - IDictionary queryStrings = null - ) { - // - var url = endpoint.GetStringValue (); - - // - // Add Route Payloads ... - if (!@params.IsNull () && @params.Count > 0) { - // - var enumerator = @params.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - - // - url = url.Replace (item.Key, item.Value.ToUrlEncoded ()); - } - } - - // - // Add Query Strings ... - if (!queryStrings.IsNull () && queryStrings.Count > 0) { - // - url = $"{url}?"; - var enumerator = queryStrings.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - - // - url += $"{item.Key}={item.Value.ToUrlEncoded ()}&"; - } - - // - // remove lates & ... - if (url.EndsWith ("&")) { - url = url.Substring (0, url.Length - 1); - } - } - - // - // Create request ... - var request = new RestRequest (url, DataFormat.Json); - - // - if (addXPoweredValue) { - request.AddHeader (XAuthorization.XPoweredBy, identityConfiguration.XPoweredValue); - } - - // - // Add Headers to request ... - if (!headers.IsNull () && headers.Count > 0) { - // - var enumerator = headers.GetEnumerator (); - while (enumerator.MoveNext ()) { - // - var item = enumerator.Current; - request.AddHeader (item.Key, item.Value); - } - } - - // - return request; - } - - /// - /// Handle Call Specific Request and retrieve Response - /// - /// - /// - /// - /// - /// - /// - public async Task RunRestRequest ( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true - ) { - // - var response = await Task.Run (async () => { - // - IRestResponse resp = null; - - // - // Call Endpoint Service using Specified Method ... - switch (method) { - // - // Get ... - case XHttpMethod.GET: - resp = client.Get (request); - break; - - // - // Put ... - case XHttpMethod.PUT: - resp = client.Put (request); - break; - - // - // Post ... - case XHttpMethod.POST: - resp = client.Post (request); - break; - - // - // Delete ... - case XHttpMethod.DELETE: - resp = client.Delete (request); - break; - } - - // - if (!resp.IsSuccessful) { - // - // Log Exception ... - Logger.LogError ($"Error: {resp.ErrorMessage}"); - Logger.LogError ($"Exception: {resp.ErrorException.ToJSON()}"); - if (!resp.ErrorMessage.IsNullOrEmpty () && - resp.ErrorMessage.Contains ("timed out")) { - XException.Timeout.Throw (); - } - - // - // TODO: Check UnAuthorized Status here for - // Refresh Tokens or Issue Correct Exception ... - if (supportRefreshingTokens && - resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { - // - var isRefreshed = request.Parameters.Any (rp => - rp.Name == XParam.XIsRefreshed.GetStringValue () && - rp.Value.ToString ().ToNormalString () == true.ToJSON ()); - - // - Logger.LogInformation ($"isRefreshed: {isRefreshed}"); - - // - // Get Access Token ... - XTokenResponse tokens = null; - var accessToken = request.Parameters.FirstOrDefault (rp => - rp.Name.ToNormalString () == XAuthorization.Header.ToNormalString ()).Value.ToString (); - if (!accessToken.IsNullOrEmpty ()) { - // - accessToken = accessToken.Replace (XAuthorization.TokenIdentifier, ""); - - // - if (!accessToken.IsNullOrEmpty ()) { - tokens = await tokenProvider.RetrieveToken (accessToken); - } - } - - // - // Refresh Token and then re do request ... - if (!isRefreshed && - !accessToken.IsNullOrEmpty () && - !tokens.IsNull () && - tokens.IsRefreshable ()) { - // - request.AddHeader (XParam.XIsRefreshed.GetStringValue (), true.ToJSON ()); - - // - // Refreshe Tokens ... - var refreshedTokens = await RefreshTokens (tokens); - - // - // Renew Rest Client with Refreshed Tokens ... - var timeout = client.Timeout; - client = GetRestClient (refreshedTokens); - client.Timeout = Timeout.Infinite; - - // - // Do Request Again using renew Client ... - return await RunRestRequest ( - client: client, - request: request, - method: method); - } - } - - // - var ex = resp.Content.ToXError (); - if (!ex.IsNull ()) { - throw ex.ToException (); - } - - // - // UnAuthorized ... - if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { - XException.NotAuthorized.Throw (); - } - - // - // NotFound ... - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) { - XException.NotFound.Throw (); - } - - // - XException.ActionFailed.Throw (); - } - - // - var result = resp.Content.FromJSON (); - return result; - }); - - // - return response; - } - public async Task> RunRestRequestByResponse ( - RestClient client, - RestRequest request, - XHttpMethod method, - bool supportRefreshingTokens = true - ) { - // - var response = await Task.Run (async () => { - // - IRestResponse resp = null; - - // - // Call Endpoint Service using Specified Method ... - switch (method) { - // - // Get ... - case XHttpMethod.GET: - resp = client.Get (request); - break; - - // - // Put ... - case XHttpMethod.PUT: - resp = client.Put (request); - break; - - // - // Post ... - case XHttpMethod.POST: - resp = client.Post (request); - break; - - // - // Delete ... - case XHttpMethod.DELETE: - resp = client.Delete (request); - break; - } - - // - if (!resp.IsSuccessful) { - // - // Log Exception ... - Logger.LogError ($"Error: {resp.ErrorMessage}"); - Logger.LogError ($"Exception: {resp.ErrorException.ToJSON()}"); - if (!resp.ErrorMessage.IsNullOrEmpty () && - resp.ErrorMessage.Contains ("timed out")) { - XException.Timeout.Throw (); - } - - // - // TODO: Check UnAuthorized Status here for - // Refresh Tokens or Issue Correct Exception ... - if (supportRefreshingTokens && - resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { - // - var isRefreshed = request.Parameters.Any (rp => - rp.Name == XParam.XIsRefreshed.GetStringValue () && - rp.Value.ToString ().ToNormalString () == true.ToJSON ()); - - // - Logger.LogInformation ($"isRefreshed: {isRefreshed}"); - - // - // Get Access Token ... - XTokenResponse tokens = null; - var accessToken = request.Parameters.FirstOrDefault (rp => - rp.Name.ToNormalString () == XAuthorization.Header.ToNormalString ()).Value.ToString (); - if (!accessToken.IsNullOrEmpty ()) { - // - accessToken = accessToken.Replace (XAuthorization.TokenIdentifier, ""); - - // - if (!accessToken.IsNullOrEmpty ()) { - tokens = await tokenProvider.RetrieveToken (accessToken); - } - } - - // - // Refresh Token and then re do request ... - if (!isRefreshed && - !accessToken.IsNullOrEmpty () && - !tokens.IsNull () && - tokens.IsRefreshable ()) { - // - request.AddHeader (XParam.XIsRefreshed.GetStringValue (), true.ToJSON ()); - - // - // Refreshe Tokens ... - var refreshedTokens = await RefreshTokens (tokens); - - // - // Renew Rest Client with Refreshed Tokens ... - var timeout = client.Timeout; - client = GetRestClient (refreshedTokens); - client.Timeout = Timeout.Infinite; - - // - // Do Request Again using renew Client ... - return await RunRestRequestByResponse ( - client: client, - request: request, - method: method - ); - } - } - - // - var ex = resp.Content.ToXError (); - if (!ex.IsNull ()) { - throw ex.ToException (); - } - - // - // UnAuthorized ... - if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { - XException.NotAuthorized.Throw (); - } - - // - // NotFound ... - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) { - XException.NotFound.Throw (); - } - - // - XException.ActionFailed.Throw (); - } - - // - var result = new XBaseRestResponse - { - Response = resp, - Model = resp.Content.FromJSON () - }; - - // - return result; - }); - - // - return response; - } - - /// - /// Get User SelectBy Param - /// - /// - /// - /// - /// - public string GetUserSelectByParam ( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ) { - // - // Validate Args ... - validationProvider.NotNull (model); - - // - var id = model.UserId; - var userName = model.UserName; - var email = model.Email; - var phoneNumber = model.MobileNumber; - - // - if (excludes != null) { - // - if (excludes.Contains (XUserSelectBy.ID)) { - id = null; - } - if (excludes.Contains (XUserSelectBy.Email)) { - email = null; - } - if (excludes.Contains (XUserSelectBy.MobileNumber)) { - phoneNumber = null; - } - if (excludes.Contains (XUserSelectBy.Username)) { - userName = null; - } - } - - var selectByParam = - id.IsNullOrEmpty () ? - userName.IsNullOrEmpty () ? - email.IsNullOrEmpty () ? - phoneNumber.IsNullOrEmpty () ? null : phoneNumber : email : userName : id; - - // - // Check result ... - if (forceNotNull && - selectByParam.IsNullOrEmpty ()) { - XException.InvalidData.Throw (); - } - - // - return selectByParam; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XInMemoryTokenProvider.cs - -using System.Linq; -using xCommons.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; -using xIdentityService.Interfaces; - -namespace xIdentityService.Providers { - public partial class XInMemoryTokenProvider : IXTokenProvider { - private IDictionary DbContext; - - public XInMemoryTokenProvider () { - // - this.DbContext = new Dictionary (); - } - - public async Task IsTokenExists (string accessToken) { - // - // Validate Args ... - if (accessToken.IsNullOrEmpty ()) { - return false; - } - - // - // Process Result ... - var result = DbContext.Keys.Any (k => k == accessToken); - return await Task.FromResult (result); - } - - public async Task IsTokenExists (XTokenResponse tokens) { - // - // Validate Args ... - if (tokens.IsNull () || - tokens.AccessToken.IsNullOrEmpty () || - !await IsTokenExists (tokens.AccessToken)) { - return false; - }; - - // - // Process Result ... - var result = await IsTokenExists (tokens.AccessToken); - return result; - } - - public async Task RemoveToken (string accessToken) { - // - // Validate Args ... - if (accessToken.IsNullOrEmpty ()) { - return false; - } - - // - // Process Result ... - var result = DbContext.Remove (accessToken); - return await Task.FromResult (result); - } - - public async Task RemoveToken (XTokenResponse tokens) { - // - // Validate Args ... - if (tokens.IsNull () || - tokens.AccessToken.IsNullOrEmpty () || - !await IsTokenExists (tokens.AccessToken)) { - return false; - }; - - // - // Process Result ... - var result = await RemoveToken (tokens.AccessToken); - return result; - } - - public async Task RetrieveToken (string accessToken) { - // - // Validate Args ... - if (accessToken.IsNullOrEmpty () || - !await IsTokenExists (accessToken)) { - return null; - } - - // - // Process Result ... - var result = DbContext[accessToken]; - return result; - } - - public async Task AddToken (XTokenResponse tokens) { - // - // Validate Args ... - if (tokens.IsNull () || - tokens.AccessToken.IsNullOrEmpty () || - await IsTokenExists (tokens.AccessToken)) { - return false; - }; - - // - // Process Result ... - try { - // - DbContext.Add (tokens.AccessToken, tokens); - return true; - } catch { - return false; - } - } - - public async Task UpdateToken (XTokenResponse tokens) { - // - // Validate Args ... - if (tokens.IsNull () || - tokens.AccessToken.IsNullOrEmpty () || - !await IsTokenExists (tokens.AccessToken)) { - return false; - }; - - // - // Process Result ... - try { - // - DbContext[tokens.AccessToken] = tokens; - return true; - } catch { - return false; - } - } - - public async Task AddOrUpdateToken (XTokenResponse tokens) { - // - // Validate Args ... - if (tokens.IsNull () || - tokens.AccessToken.IsNullOrEmpty () - ) { - return false; - }; - - // - // Process Result ... - try { - // - var isExists = await IsTokenExists (tokens); - if (isExists) { - return await UpdateToken (tokens); - } else { - return await AddToken (tokens); - } - } catch { - return false; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XPersonService.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityService.Extensions; -using xIdentityService.Interfaces; -using System.Collections.Concurrent; - -namespace xIdentityService.Providers -{ - public class XPersonService : IXPersonService - { - // - private readonly IXIdentityProvider identityProvider; - private readonly ConcurrentDictionary persons = new ConcurrentDictionary(); - - public XPersonService( - IXIdentityProvider identityProvider - ) - { - this.identityProvider = identityProvider; - } - - public async Task GetPerson(string userId) - { - // - // Validate ... - if (userId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - XPersonDto result = null; - - // - // if Persons has Child, Check it ... - if (persons.HasChild()) - { - // - var personEntry = persons - .FirstOrDefault(p => p.Key.Equals(userId, StringComparison.InvariantCultureIgnoreCase)); - if (!personEntry.IsNull()) - { - result = personEntry.Value; - } - } - - // - // Check if Person not Exists ... - if (result.IsNullOrDefault()) - { - // - // Prepare Device ... - var device = identityProvider.GetDevice(); - - // - // Retrieve User Info in OpenAction ... - var userInfo = await identityProvider - .GetUserInfo( - device: device, - userSelectByParam: userId - ); - - // - // Converts to Person Dto ... - result = userInfo.ToXPersonDto(); - - // - // Update Persons Dictionary ... - if (!result.IsNullOrDefault()) - { - persons[userId] = result; - } - } - - // - Cleanup(); - - // - return result; - } - - public void Cleanup() - { - // - // TODO: Implement Cleanup Pesons ... - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XPolicyHandler.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.EntityFrameworkCore.Internal; - -namespace xIdentityService.Providers -{ - public class XPolicyHandler : IXPolicyHandler - { - private readonly static Dictionary> policies = []; - - /// - /// Add Specified Role ... - /// - /// - /// - /// - public bool AddPolicy( - string policy, - IEnumerable requiredRoles - ) - { - // - // Validate ... - if (policy.IsNullOrEmpty() || - !requiredRoles.HasChild() - ) - { - XException.InvalidArgs.Throw(); - } - - // - var result = !HasPolicy(policy); - if (!result) - { - return result; - } - - // - policies[policy] = requiredRoles; - - // - return result; - } - - /// - /// Check Specified Role Exists or not ... - /// - /// - /// - public bool HasPolicy(string policy) - { - // - var result = - policies.HasChild() && - !policy.IsNullOrEmpty() && - policies.Keys.Any(p => p - .Equals(policy, StringComparison.InvariantCultureIgnoreCase)); - - // - return result; - } - - /// - /// Remove Specified Role ... - /// - /// - /// - public bool RemovePolicy(string policy) - { - // - // Validate ... - if (policy.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = HasPolicy(policy); - if (!result) - { - return result; - } - - // - result = policies.Remove(policy); - - // - return result; - } - - /// - /// Check Specified Policy passed or not ... - /// - /// - /// - /// - public bool IsPolicyPassed( - string policy, - IEnumerable roles - ) - { - // - // Validate ... - if (!roles.HasChild() || - policy.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - policy = policy.ToNormalString(); - - // - var result = HasPolicy(policy); - if (!result) - { - return result; - } - - // - var requiredRoles = policies[policy]; - result = - requiredRoles.HasChild() && - roles.All(r => requiredRoles - .Any(rq => r.Equals(rq, StringComparison.InvariantCultureIgnoreCase))); - - // - return result; - } - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Providers\XProxyHelper.cs - -using System; -using System.Web; -using System.Linq; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Linq.Expressions; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using xIdentityService.Configuration; - -namespace xIdentityService.Providers { - public class XProxyHelper : IXProxyHelper { - // - #region Props ... - public XProxyConfiguration Configuration { get; } - #endregion - - // - #region Constructor ... - public XProxyHelper (XProxyConfiguration configuration) { - this.Configuration = configuration; - } - #endregion - - // - #region Actions ... - /// - /// Validate XProxy Configuration for Client ... - /// - /// - public bool ValidateConfiguration () { - // - var result = !Configuration.IsNull () && - !Configuration.Host.IsNullOrEmpty () && - Configuration.Host.IsValidUrl () && - Configuration.Routes.HasChild (); - - // - return result; - } - - /// - /// retrie Normalize Host ... - /// - /// - public string NormalizeHost () { - // - var result = string.Empty; - - // - if (!Configuration.IsNull () && - !Configuration.Host.IsNullOrEmpty () && - Configuration.Host.IsValidUrl () - ) { - // - result = Configuration.Host - .ToNormalString (); - - // - if (result.EndsWith ("/")) { - result = result.Substring (0, result.Length - 1); - } - } - - // - return result; - } - - /// - /// retrieve all registred Routes ... - /// - /// - public IEnumerable GetRoutes () { - // - // Validate Args ... - if (Configuration.IsNull ()) { - return null; - } - - // - return Configuration.Routes; - } - - /// - /// Retrieve all Prepared url of Routes ... - /// - /// - public IEnumerable GetRouteUrls () { - // - var normalHost = NormalizeHost (); - if (normalHost.IsNullOrEmpty ()) { - return null; - } - - // - var result = GetRoutes () - .Select (r => $"{normalHost}{r.Route}"); - - // - return result; - } - - /// - /// Find an Specific Route ... - /// - /// - /// - public XProxyRouteDescriptor FindRoute (Expression> whereClause) { - // - // Validate Arg ... - if (whereClause.IsNull ()) { - return null; - } - - // - var whereFunc = whereClause - .Compile (); - - // - var result = GetRoutes () - .FirstOrDefault (whereFunc); - - // - return result; - } - - /// - /// Prepare a request url for a Proxy Route ... - /// - /// - /// - /// - public string PrepareActionUrlForXProxyRoute ( - string url, - XProxyRouteDescriptor descriptor - ) { - // - if (!url.IsValidUrl () || - url.IsNullOrEmpty () || - !ValidateConfiguration () - ) { - throw XException.InvalidArgs.ToException (); - } - - // - // find Route ... - var routeDescriptor = GetRoutes () - .FirstOrDefault (r => r - .IsSameContent (descriptor) - ); - - // - // Validate Route Descriptor ... - if ( - routeDescriptor.IsNull () || - routeDescriptor.Route.IsNullOrEmpty () - ) { - throw XException.InvalidArgs.ToException (); - } - - // - // Retrieve and Validate Host Address ... - var host = NormalizeHost (); - if (!host.IsValidUrl () || - host.IsNullOrEmpty () - ) { - throw XException.InvalidArgs.ToException (); - } - - // - url = $"{host}{routeDescriptor.Route}/{HttpUtility.UrlEncode(url)}"; - - // - return url; - } - - /// - /// Prepare a request url for a Selected Proxy Route ... - /// - /// - /// - /// - public string PrepareActionUrlForXProxyRoute ( - string url, - Expression> whereClause - ) { - // - if (!url.IsValidUrl () || - url.IsNullOrEmpty () || - whereClause.IsNull () || - !ValidateConfiguration () - ) { - throw XException.InvalidArgs.ToException (); - } - - // - var descriptor = FindRoute (whereClause); - - // - // find Route ... - var result = PrepareActionUrlForXProxyRoute ( - url: url, - descriptor: descriptor - ); - - // - return result; - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xIdentityService\Security\XSecurityProvider.cs - -using System; -using System.IO; -using System.Text; -using xCommons.Providers; -using xCommons.Extensions; -using xIdentityService.Interfaces; -using System.Security.Cryptography; -using xIdentityService.Configuration; - -namespace xIdentityService.Security { - public partial class XSecurityProvider : IXSecurityProvider { - private readonly string secretKey; - private readonly byte[] iv; - private readonly byte[] key; - private readonly XValidationProvider validationProvider; - - public XSecurityProvider ( - XIdentityServiceConfiguration identityConfiguration, - XValidationProvider validationProvider - ) { - // - this.secretKey = identityConfiguration.XRevisionSecretKey.ToMd5String (); - this.validationProvider = validationProvider; - - // - var ivBytes = new byte[16]; - var keyBytes = new byte[32]; - var secretBytes = Encoding.UTF8.GetBytes (this.secretKey); - - // - Array.Copy ( - secretBytes, - ivBytes, - secretBytes.Length < ivBytes.Length ? - secretBytes.Length : - ivBytes.Length - ); - this.iv = ivBytes; - - // - Array.Copy ( - secretBytes, - keyBytes, - secretBytes.Length < keyBytes.Length ? - secretBytes.Length : - keyBytes.Length - ); - this.key = keyBytes; - - // Encoding.UTF8.GetBytes (this.secretKey); - } - - public string Encrypt (string plainText) { - // - validationProvider.NotEmpty (plainText); - - // - var textBytes = Encoding.UTF8.GetBytes (plainText); - var result = EncryptFromBytes (textBytes); - - // - return result; - } - - public string Decrypt (string cipherText) { - // - validationProvider.NotEmpty (cipherText); - - // - var cipherBytes = Convert.FromBase64String (cipherText); - var result = DecryptFromBytes (cipherBytes); - - // - return result; - } - - public string EncryptFromBytes (byte[] textBytes) { - // - // Validate Args ... - validationProvider.NotNull (textBytes); - - // Declare the string used to hold - // the decrypted text. - byte[] encryptedBytes = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged ()) { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // - using (var encryptor = rijAlg.CreateEncryptor (rijAlg.Key, rijAlg.IV)) { - encryptedBytes = encryptor.TransformFinalBlock (textBytes, 0, textBytes.Length); - } - } - - // - return Convert.ToBase64String (encryptedBytes); - } - - public string DecryptFromBytes (byte[] cipherBytes) { - // - // Validate Args ... - validationProvider.NotNull (cipherBytes); - - // Declare the string used to hold - // the decrypted text. - string plaintext = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged ()) { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // Create a decrytor to perform the stream transform. - var decryptor = rijAlg.CreateDecryptor (rijAlg.Key, rijAlg.IV); - - // Create the streams used for decryption. - using (var msDecrypt = new MemoryStream (cipherBytes)) { - using (var csDecrypt = new CryptoStream (msDecrypt, decryptor, CryptoStreamMode.Read)) { - using (var srDecrypt = new StreamReader (csDecrypt)) { - // Read the decrypted bytes from the decrypting stream - // and place them in a string. - plaintext = srDecrypt.ReadToEnd (); - } - } - } - } - - // - return plaintext; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xIds-20261109_152616.txt b/Documents/GeneratedContext/xDashboard-xIds-20261109_152616.txt deleted file mode 100644 index 9efb7e3..0000000 --- a/Documents/GeneratedContext/xDashboard-xIds-20261109_152616.txt +++ /dev/null @@ -1,29682 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Program.cs - -using xLoggingService.DI; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace xIds -{ - public class Program - { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - // - var result = Host.CreateDefaultBuilder(args) - .ConfigureLogging(logging => - logging.AddXTelemetryLogger()) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .AddXTelemetry(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Startup.cs - -using System; -using xIds.DI; -using System.IO; -using xIds.Constants; -using xIds.Providers; -using Newtonsoft.Json; -using xIds.Interfaces; -using System.Reflection; -using xLoggingService.DI; -using xStorageService.DI; -using xCommons.Extensions; -using xCommons.Configurations; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xIds -{ - public class Startup - { - public IConfiguration Configuration { get; } - - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public void ConfigureServices(IServiceCollection services) - { - // - // Register Validation Provider and all XCommons Module Services ... - services.AddXCommons(Configuration); - - // - // Register App Configuration ... - services.AddXAppConfiguration(Configuration); - var appConfiguration = services.GetRegisteredService(); - - // - // Register Logging Service ... - services.AddXLoggingService(Configuration); - - // - // Register XDataService Configuration ... - services.AddXDataServiceConfiguration(Configuration, ConnectionStringNames.IDENTITY_CONNECTION_NAME); - - // - // Register Allowed Origins ... - services.AddXCors(appConfiguration.AllowedOrigins); - - // - // Register Swagger ... - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - services.AddXSwagger(Configuration, xmlFilePath: xmlPath); - - // - // Register IdentityServer to DI ... - // services.AddInMemoryXIdentityServer (Configuration); - services.AddEfSupportXIdentityServer(Configuration); - - // - // Services Application and Api Key Management Services ... - services.AddXApplicationProvider(Configuration); - - // - services.AddControllers() - .AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); - - // - // Register Authentication ... - services.AddXIdentityServerAuthentication(Configuration); - - // - // Register Authorization ... - services.AddXAuthorization(); - - // - // Register Security Provider ... - services.AddSingleton(); - } - - public void Configure( - IApplicationBuilder app, - IWebHostEnvironment env, - ILogger logger - ) - { - // - var isDevelopmentEnvironment = env.IsDevelopment(); - if (isDevelopmentEnvironment) - { - app.UseDeveloperExceptionPage(); - } - - // - // Use Swagger Middleware ... - app.UseXSwagger(); - - // - app.UseHttpsRedirection(); - app.UseXForwardOptions(); - - // - // Using Cors ... - app.UseXCors(); - - // - // Force App to Use IdentityServer ... - app.UseXIdentityServer(logger); - - // - // Force app to Use Storage Service ... - app.UseXStorageService(); - - // - app.UseRouting(); - - // - // Using Request Logging ... - if (!isDevelopmentEnvironment) - { - app.UseXRequestLogger(); - } - - // - app.UseAuthentication(); - app.UseAuthorization(); - - // - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - } - } -} - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Configurations\CertificatesConfigurations.cs - -namespace xIds.Configurations -{ - public class CertificatesConfigurations - { - public struct CertificateNames - { - public const string IdentityServerSigning = "IdentityServerSigning"; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Configurations\XApiKeyConfiguration.cs - -namespace xIds.Configurations -{ - /// - /// Configuration settings for API Key management, including expiration, rate limiting, and audit logging. - /// - public class XApiKeyConfiguration - { - /// - /// Generated Api Keys Prefix ... - /// - public string ApiKeyPrefix { get; set; } - - /// - /// Default expiration in minutes (e.g., 43200 = 30 days) - /// - public int DefaultExpirationMinutes { get; set; } = 43200; - - /// - /// Maximum allowed expiration in minutes (e.g., 525600 = 1 year) - /// - public int MaxExpirationMinutes { get; set; } = 525600; - - /// - /// Maximum ApiKeys per Application - /// - public int MaxKeysPerApplication { get; set; } = 10; - - /// - /// Enable audit logging - /// - public bool EnableAuditLog { get; set; } = false; - - /// - /// Default rate limit (requests per minute) - /// - public int DefaultRateLimit { get; set; } = 60; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Configurations\XDataServiceConfiguration.cs - -using xIds.Constants; - -namespace xIds.Configurations -{ - /// - /// Represent Configurations of DataService Module ... - /// - public partial class XDataServiceConfiguration - { - /// - /// Provider Type ... - /// - /// - public XDbProviders Provider { get; set; } - - /// - /// Connection String which provide Requires Data to Connect to Db Provider ... - /// - /// - public string ConnectionString { get; set; } - - /// - /// Enable Tracking of Entities ... - /// Only Used on EFCore ... - /// - /// - public bool EnableTracking { get; set; } = false; - - /// - /// Enable Logging Details of Errors ... - /// Only Used on EFCore ... - /// - /// - public bool EnableDetailedErrors { get; set; } = false; - - /// - /// Enable Logging Sensitive Data ... - /// Only Used on EFCore ... - /// - /// - public bool EnableSensitiveDataLogging { get; set; } = false; - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - /// - public PagingConfiguration PagingConfiguration { get; set; } = new PagingConfiguration(); - } - - /// - /// this is a way to provide Default Pagination Data on XQuery based requests ... - /// - public partial class PagingConfiguration - { - /// - /// Default Page Size ... - /// - /// - public int DefaultPageSize { get; set; } = XDataServiceConstants.DEFAULT_PAGE_SIZE; - - /// - /// restrict Maximum Page Size ... - /// - /// - public int MaxAvailablePageSize { get; set; } = XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE; - - /// - /// restrice Minimum Page Size ... - /// - /// - public int MinAvailablePageSize { get; set; } = XDataServiceConstants.MIN_AVAILABLE_PAGE_SIZE; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Configurations\XIdentityResourceConfiguration.cs - -namespace xIds.Configurations -{ - /// - /// determines a resource and it's connection info - /// - public partial class XIdentityResourceConfiguration - { - public string Authority { get; set; } - public string ApiName { get; set; } - public string ApiSecret { get; set; } - - public string ClientId { get; set; } - public string ClientSecret { get; set; } - - public string XPoweredValue { get; set; } - public string XRevisionSecretKey { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\ConfigurationNodeNames.cs - -namespace xIds.Constants -{ - public struct ConfigurationNodeNames - { - public const string DB_SEED_NODE_NAME = "DbSeeder"; - public const string PROVIDER_NODE_NAME = "DbProvider"; - public const string APIKEY_NODE_NAME = "ApiKeyConfiguration"; - public const string IDENTITY_NODE_NAME = "IdentityConfiguration"; - public const string DATA_SERVICE_NODE_NAME = "DataServiceConfiguration"; - public const string IDENTITY_RESOURCE_NODE_NAME = "IdentityResourceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\ConnectionStringNames.cs - -namespace xIds.Constants -{ - public struct ConnectionStringNames - { - public const string IDENTITY_CONNECTION_NAME = "IdentityDb"; - public const string CONFIGURATION_CONNECTION_NAME = "ConfigurationDb"; - public const string PRESISTED_GRANTS_CONNECTION_NAME = "PersistedGrantDb"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\IdentityMessagesKeys.cs - -namespace xIds.Constants -{ - public struct IdentityMessagesKeys - { - public const string Terms = "terms"; - public const string InviteMsg = "user_invite_msg"; - public const string RegistrationApproveMsg = "registration_approve_msg"; - public const string RegisteredMsg = "registered_msg"; - public const string VerificationCodeMsg = "verification_code_msg"; - public const string ChangePasswordMsg = "change_password_msg"; - public const string PasswordChangedMsg = "password_changed_msg"; - public const string NewDeviceLoggedInMsg = "new_device_logged_in_msg"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\XDataServiceConstants.cs - -namespace xIds.Constants -{ - /// - /// /// Default Pagination Values ... - /// - public partial struct XDataServiceConstants - { - public static int DEFAULT_PAGE_SIZE = 50; - public static int MAX_AVAILABLE_PAGE_SIZE = 500; - public static int MIN_AVAILABLE_PAGE_SIZE = 20; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\XDbProviderConfigurations.cs - -namespace xIds.Constants -{ - public partial class XDbProviderConfigurations - { - /// - /// Default ConnectionString Name ... - /// - public const string DEFAULT_CONNECTION_NAME = "DataConnection"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Constants\XDbProviders.cs - -namespace xIds.Constants -{ - /// - /// /// Represent Supported DBMS for Managing Data ... - /// - public enum XDbProviders - { - None, - MySQL, - SQLite, - SQLServer, - } - - /// - /// Represent Supported DBMS for Managing Data ... - /// - public partial struct ProviderType - { - public const string MySQL = "MYSQL"; - public const string SQLite = "SQLITE"; - public const string SQLServer = "SQLSERVER"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\AccountController.cs - -using xIds.Interfaces; -using xCommons.Providers; -using xIds.Controllers.Base; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; - -namespace xIds.Controllers -{ - /// - /// Provide all available tools for manipulating users and accounts - /// - [ApiController] - public partial class AccountController : XIBaseController - { - - public AccountController( - IXIdentityManager identityManager, - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - identityManager, - validationProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\ApplicationsController.cs - -using xIds.Interfaces; -using xCommons.Providers; -using xIds.Configurations; -using xIds.Controllers.Base; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; - -namespace xIds.Controllers -{ - /// - /// Provide all available tools for manipulating users and accounts - /// - [ApiController] - public partial class ApplicationsController : XIBaseController - { - private readonly IXApplicationProvider provider; - private readonly IXSecurityProvider securityProvider; - private readonly XApiKeyConfiguration apiKeyConfiguration; - - public ApplicationsController( - IXApplicationProvider provider, - IXIdentityManager identityManager, - XAppConfiguration appConfiguration, - IXSecurityProvider securityProvider, - ILogger logger, - XValidationProvider validationProvider, - XApiKeyConfiguration apiKeyConfiguration - ) : base( - logger, - appConfiguration, - identityManager, - validationProvider - ) - { - // - this.provider = provider; - this.securityProvider = securityProvider; - this.apiKeyConfiguration = apiKeyConfiguration; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\StartupController.cs - -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using xCommons.Configurations; -using xCommons.Controllers; -using xCommons.Providers; - -namespace xIds.Controllers -{ - /// - /// Startup and Running Controller - /// - [Route("")] - [AllowAnonymous] - public class StartupController : XBaseController - { - public StartupController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { } - - /// - /// Show Configured Welcome Message - /// - /// an string message - [HttpGet("")] - [AllowAnonymous] - public virtual ActionResult Index() - { - // - var controllerName = GetControllerName(); - var message = $"{AppConfiguration.WelcomeMessage}"; - - // - return Ok(message); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Admin.cs - -using System; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - #region Admin Actions ... - /// - /// Ban Specific Users - /// - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of banned users identifiers - [RequireXPowered] - [HttpPost("Ban")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task>> Ban( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotZeroChilds(model.Ids) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .Ban( - User.Identity.Name, - model - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// UnBann Specific Users - /// - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a list of unbanned users identifiers - [RequireXPowered] - [HttpPost("UnBan")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task>> UnBan( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotZeroChilds(model.Ids) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .UnBan( - User.Identity.Name, - model - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Check Specific User is Banned or not - /// - /// specified user's identifier - /// a boolean value which represent user banned or not - [RequireXPowered] - [Authorize(Policy = LocalApi.PolicyName)] - [HttpGet("IsBanned/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [Authorize(Policy = XPolicies.EnabledAgent)] - public async Task> IsBanned( - [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - var result = await IdentityManager - .IsBanned( - User.Identity.Name, - userSelectByParam - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Authentication.cs - -using System; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using IdentityModel.Client; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using static xIdentityHelper.XApiScopeHelper; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - #region Authentication Actions ... - /// - /// Retrieve OAuth Discovery Document - /// - /// an instance of DiscoveryDocumentResponse - [AllowAnonymous] - [RequireXPowered] - [HttpGet("DiscoveryDocument")] - public async Task> GetDiscoveryDocument() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .RequestDiscoveryDocument(); - - // - // Ceck Response Result ... - if (result.IsError) - { - XException.InvalidConfiguration.Throw(); - } - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Request AccessToken for Specific XApiScope - /// - /// a member of XApiScope - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestScopeAccessToken")] - public async Task> RequestScopeAccessToken( - [FromHeader] XApiScope scope - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - var scopeName = string.Empty; - try - { - scopeName = scope.GetStringValue(); - } - catch { } - ValidationProvider.NotEmpty(scopeName); - - // - var result = await IdentityManager - .RequestScopeAccessToken(scopeName); - - // - // Ceck Response Result ... - if (result.IsError) - { - XException.InvalidConfiguration.Throw(); - } - - // - return Ok(result - .CreateXTokenResponse() - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Authenticate User - /// - /// - /// Sample request: - /// - /// { - /// "password": "", - /// "userSelectBy": "", - /// } - /// - /// - /// an instance of XLoginRequest class which represent Authentication requirements - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("Authenticate")] - public async Task> Authenticate( - [FromBody] XLoginRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .Authenticate(model); - - // - // Check Result ... - if (result.IsError) - { - throw result.GetException(); - } - - // - // Return Result ... - return Ok(result - .CreateXTokenResponse() - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Authenticate User - /// - /// - /// Sample request: - /// - /// { - /// "language": "fa-IR" - /// "password": "", - /// "userSelectBy": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XLoginRequest class which represent Authentication requirements - /// an instance of XLoginResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("Login")] - public async Task> Login( - [FromBody] XLoginRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull( - model, - model.Device) - .AddNotEmpty( - model.Language, - model.UserSelectBy, - model.Password - ) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .Login(model); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Refresh Expired Tokens - /// - /// - /// in addition to AccessToken, you had to pass RefreshToken due to Headers - /// - /// an instance of XTokenResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RefreshTokens")] - public async Task> RefreshTokens() - { - // - // Do Action ... - try - { - // - // Retrieve Toke Response ... - var model = await RetrieveTokensAsXTokenResponse(); - - // - // Validate Args ... - ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.AccessToken, - model.RefreshToken) - .ValidateGroup(); - - // - var result = await IdentityManager - .RefreshTokens(model); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Password Actions ... - /// - /// Change a User's Password ... - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - NewPassword: user's new password to change. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "" - /// "newPassword": "", - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [RequireXPowered] - [HttpPost("ChangePassword")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = XPolicies.EnabledUser)] - [Authorize(Policy = LocalApi.PolicyName)] - public async Task ChangePassword( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull( - model, - model.Device - ) - .AddNotEmpty( - model.Lang, - model.Password, - model.NewPassword, - model.ReturnUrl - ) - .ValidateGroupAsync(); - - // - // Get User Select By ... - var userSelectByParam = GetUserSelectByParam( - model, - forceNotNull: false - ); - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Get Request ... - await IdentityManager - .ChangePassword( - model.Lang, - model.Device, - userSelectByParam, - model.Password, - model.NewPassword, - model.ReturnUrl - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Friendship.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Navigations; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - #region Friendship Actions ... - // - #region Actions ... - /// - /// Follow a User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [RequireXPowered] - [HttpPost("Friendship/{destUser}/Follow")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> Follow( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .Follow( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Cancel Following - /// - /// a user identifier which represent destination user - /// a boolean value - [HttpPost("Friendship/{destUser}/Cancel")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> Cancel( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .Cancel( - User.Identity.Name, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Unfollow a Follower - /// - /// a user identifier which represent destination user - /// - [HttpPost("Friendship/{destUser}/UnFollowFollower")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task UnFollowFollower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - await IdentityManager - .UnFollowFollower( - User.Identity.Name, - destUser - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Unfollow Following - /// - /// a user identifier which represent destination user - /// - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/UnFollowFollowing")] - public async Task UnFollowFollowing( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - await IdentityManager - .UnFollowFollowing( - User.Identity.Name, - destUser - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Block a Follower - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [HttpPost("Friendship/{destUser}/Block")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> Block( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .Block( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - - /// - /// Unblock a Blocked User - /// - /// an instance of XFriendshipFollowing - /// an instance of XFriendshipFollowing - [HttpPost("Friendship/{destUser}/UnBlock")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> UnBlock( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .UnBlock( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Request Handlers ... - /// - /// Accept a Following Request - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/AcceptRequest")] - public async Task> AcceptRequest( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .AcceptRequest( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Reject a Following Request - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Friendship/{destUser}/RejectRequest")] - public async Task> RejectRequest( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .RejectRequest( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Getters ... - /// - /// Check a User IsFollower of Requested User - /// - /// a user identifier which represent destination user - /// a boolean value - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/IsFollower")] - public async Task> IsFollower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .IsFollower( - User.Identity.Name, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Follower State of a User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipState - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/FollowerState")] - public async Task> FollowerState( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .GetFollowerState( - User.Identity.Name, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Specific Follower - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollower - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/Follower")] - public async Task> Follower( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .GetFollower( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Followers List Of Current User - /// - /// a collection of XFriendshipFollower - [HttpGet("Friendship/Followers")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> Followers() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetFollowers(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - - /// - /// Get All Followers List Includes Blocked, Requested and etc - /// of Current User - /// - /// a collection of XFriendshipFollower - [HttpGet("Friendship/AllFollowers")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> AllFollowers() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetAllFollowers(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Followers List Includes Blocked, Requested and etc - /// of Current User based On Query Model ... - /// - /// a Query Result of XFriendDto - [HttpGet("Friendship/QueryFollowers")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryFollowers( - [FromQuery] XQuery query, - [FromQuery] string destUser - ) - { - // - // Do Action ... - try - { - // - // Normalizing Dest User ... - var userInfo = await GetUserInfo(); - bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN); - if (destUser.IsNullOrEmpty()) - { - destUser = userInfo.UserName; - } - bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName; - if (!isDestUserValid) - { - XException.NotAllowed.Throw(); - } - - // - var result = await IdentityManager - .QueryFollowers( - query: query, - userSelectByParam: destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Check a User is in Followings of Current User - /// - /// a user identifier which represent destination user - /// a boolean value - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/IsFollowing")] - public async Task> IsFollowing( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .IsFollowing( - User.Identity.Name, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Following State Relation between Specific User - /// and Current User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipState - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/FollowingState")] - public async Task> FollowingState( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .GetFollowingState( - User.Identity.Name, - destUser - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Specific Following Model - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipFollowing - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("Friendship/{destUser}/Following")] - public async Task> Following( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotEmpty(destUser); - - // - var result = await IdentityManager - .GetFollowing( - User.Identity.Name, - destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Followings of Current User - /// - /// a collection of XFriendshipFollowing - [HttpGet("Friendship/Followings")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> Followings() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetFollowings(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Following List Includes Blocked, Requested and etc - /// of Current User - /// - /// a collection of XFriendshipFollowing - [HttpGet("Friendship/AllFollowings")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> AllFollowings() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetAllFollowings(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get All Following List Includes Blocked, Requested and etc - /// of Current User based On Query Model ... - /// - /// a Query Result of XFriendDto - [HttpGet("Friendship/QueryFollowings")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryFollowings( - [FromQuery] XQuery query, - [FromQuery] string destUser - ) - { - // - // Do Action ... - try - { - // - // Normalizing Dest User ... - var userInfo = await GetUserInfo(); - bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN); - if (destUser.IsNullOrEmpty()) - { - destUser = userInfo.UserName; - } - bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName; - if (!isDestUserValid) - { - XException.NotAllowed.Throw(); - } - - // - var result = await IdentityManager - .QueryFollowings( - query: query, - userSelectByParam: destUser - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Others ... - /// - /// Return Following UserName's List of Current User - /// - /// a collection of UserNames - [HttpGet("Friendship/FollowingsList")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> FollowingsList() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetFollowingList(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Return Followers UserName's List of Current User - /// - /// a collection of UserNames - [HttpGet("Friendship/FollowersList")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> FollowersList() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetFollowersList(User.Identity.Name); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Get Friendship Info Model between Specific User and Current User - /// - /// a user identifier which represent destination user - /// an instance of XFriendshipInfoDto - [HttpGet("Friendship/{destUser}/FriendshipInfo")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> FriendshipInfo( - [FromRoute] string destUser - ) - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .GetFriendshipInfo(User.Identity.Name, destUser); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Open.cs - -using System; -using xCommons.Constants; -using xCommons.Attributes; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Authorization; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - // Implememnt all Open Actions here ... - - // - #region Open Actions ... - /// - /// Get Open Action ... - /// - /// - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpGet("Open")] - public async Task> Get( - [FromHeader] string token, - [FromQuery] string request - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(token) - .AddNotEmpty(request) - .ValidateGroupAsync(); - - // - // Prepare Inner Dto Model ... - var dto = new XOpenActionInnerDto - { - Token = token, - Payload = request - }; - - // - // Do Action ... - var resultDto = await IdentityManager.OpenGet(dto); - Response.Headers.Add(XAuthentication.TOKEN, resultDto.Token); - - // - // Return Result - return Ok(resultDto.Payload); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Private ... - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Profile.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - #region Retrieve Actions ... - /// - /// Retrieve User Names based on UserIds - /// - /// a comma seperated list of UserIds - /// a collection of UserNames - [HttpGet("Profile/{ids}/GetNames")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetNames( - [FromRoute] string ids - ) - { - // - // Do Action ... - try - { - // - ValidationProvider.NotEmpty(ids); - - // - var xIdList = ids.ParseListString(); - var result = await IdentityManager.GetUserNamesAsync( - xIdList - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// get user ids and retrieve corresponding user names - /// - /// an instance of XUserNameIdRequest which represent required UserIds collection - /// a collection of XUserNameIdResponse instance - [HttpPost("Profile/GetNameIds")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetNameIds( - [FromBody] XUserNameIdRequest model - ) - { - // - // Do Action ... - try - { - // - ValidationProvider.NotNull(model); - - // - var result = await IdentityManager.GetUserNameIdsAsync( - model - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Profile Object of Specific User - /// - /// specifies which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [HttpGet("Profile/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> GetProfile( - [FromRoute] string userSelectByParam = "" - ) - { - // - // Do Action ... - try - { - // - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - - // - var result = await IdentityManager - .GetUserProfileAsync( - userSelectByParam, - User.Identity.Name - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Users - /// for specifiy users role for query user 'role: string' and 'forceRole: boolean' in header - /// - /// how to filter results based on XQuery structure - /// an string which represent user role - /// if it's true the user must has exact role, otherwise top level users also listed - /// an instance of XQueryResult of XUserProfileDto - [RequireXPowered] - [HttpGet("Profile/Query")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [Authorize(Policy = XPolicies.EnabledAgent)] - public async Task>> QueryProfiles( - [FromQuery] XQuery query, [FromHeader] string role, [FromHeader] bool forceRole = false - ) - { - // - // Do Action ... - try - { - // - var userId = User.Identity.Name; - - // - var result = new XQueryResult(); - if (role.IsNullOrEmpty()) - { - // - result = await IdentityManager.QueryUsers( - userId, - query - ); - } - else - { - // - result = await IdentityManager.QueryInRoleUsers( - userId, - role, - query, - forceRole - ); - } - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - - /// - /// Query Specified User's Profile Images - /// - /// determine's which user profile must be retrieved - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XProfileImage - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [HttpGet("Profile/Avatars/Query/{userSelectByParam?}")] - public async Task>> QueryAvatars( - [FromQuery] XQuery query, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - - // - var result = await IdentityManager.QueryAvatars( - userSelectByParam, - query - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - - // - #region Update Actions ... - /// - /// Update User Profile based on XProfileUpdateRequest (FirstName/LastName/DateOfBirth) - /// - /// user update info, an instance of XProfileUpdateRequest - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("Profile/Update/{userSelectByParam?}")] - public async Task> UpdateProfile( - [FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - - // - var result = await IdentityManager.ProfileUpdateAsync( - userSelectByParam, - User.Identity.Name, - model - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a User Profile based on XProfileUpdateRequest Full - /// - /// user update info, an instance of XProfileUpdateRequest - /// determine's which user profile must be retrieved - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = LocalApi.PolicyName)] - [HttpPost("Profile/{userSelectByParam?}")] - [Authorize(Policy = XPolicies.EnabledAdminOrAgent)] - public async Task> FullUpdateProfile( - [FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null - ) - { - // - // Do Action ... - try - { - // - if (userSelectByParam.IsNullOrEmpty()) - { - userSelectByParam = User.Identity.Name; - } - - // - var result = await IdentityManager.FullProfileUpdateAsync( - userSelectByParam, - User.Identity.Name, - model - ); - - // - // Return Result - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Avatar Actions ... - /// - /// Add a New Profile Image - /// - /// an specific File to upload, IFormFile - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatar")] - [RequestSizeLimit(966_367_641)] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> AddAvatar( - [FromForm] IFormFile file - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotNull(file); - - // - // Get Request ... - var result = await IdentityManager - .AddAvatar( - User.Identity.Name, - file - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Add a New Collection of Profile Images - /// - /// a collection of Files to upload, IFormFileCollection - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatars")] - [RequestSizeLimit(966_367_641)] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> AddAvatars( - [FromForm] IFormFileCollection files - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - ValidationProvider.NotZeroChilds(files); - - // - // Get Request ... - var result = await IdentityManager.AddAvatars( - User.Identity.Name, - files - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Remove Profile Images - /// - /// a comma seperated list of avatarIds to remove - /// an instance of XUserProfileDto - [RequireXPowered] - [Authorize(Policy = XPolicies.User)] - [HttpDelete("Profile/Avatars/{ids}")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> RemoveAvatars( - [FromRoute] string ids - ) - { - // - // Do Action ... - try - { - // - ValidationProvider.NotEmpty(ids); - var idList = ids.Split(","); - var idCollection = new Collection(); - - // - foreach (var s in idList) - { - idCollection.Add(int.Parse(s)); - } - - // - // Get Request ... - var result = await IdentityManager - .RemoveAvatar( - User.Identity.Name, - idCollection.ToArray() - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// set Specified Profile Image as Avatar - /// - /// an integer which reperesent AvatarId to set as current Avatar - /// an instance of XUserProfileDto - [RequireXPowered] - [HttpPost("Profile/Avatars/{id:int}/Set")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> SetAvatar( - [FromRoute] int id - ) - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .SetAvatar( - User.Identity.Name, - id - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Query.cs - -using System; -using xModels.Dtos; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - /// - /// Query Users - /// for specifiy users role for query user 'role: string' and 'forceRole: boolean' in header - /// - /// how to filter results based on XQuery structure - /// an string which represent user role - /// if it's true the user must has exact role, otherwise top level users also listed - /// an instance of XQueryResult of XUserProfileDto - [RequireXPowered] - [HttpGet("Users/Query")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryUsers( - [FromQuery] XQuery query, - [FromHeader] string role, - [FromHeader] bool forceRole = false - ) - { - // - // Do Actions ... - try - { - // - // Retrieve User Info ... - var userInfo = await GetUserInfo(); - - // - // Retrieve Result Based on Provided Query ... - var result = await IdentityManager.QueryUsers( - role: role, - query: query, - forceRole: forceRole, - requestedUserSelectByParam: userInfo.UserId - ); - - // - // Return result ... - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Registration.cs - -using System; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - // - #region CanRegister ... - /// - /// Check a UserName is Available For Registration or not - /// - /// an string value which represent desired username - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet("CanRegisterUserName/{userName?}")] - public async Task> CanRegisterUserName( - [FromRoute] string userName - ) - { - // - // Validate Args ... - if (userName.IsNullOrEmpty()) - { - return BadRequest( - XException.InvalidArgs - .ToXError() - ); - } - - // - // Do Action ... - try - { - // - var result = await IdentityManager - .CanRegister(userName); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - - // - return result; - } - } - - /// - /// Check a Mobile Number is Available For Registration or not - /// - /// an string value which represent desired mobile number - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet("CanRegisterMobileNumber/{mobileNumber?}")] - public async Task> CanRegisterMobileNumber( - [FromRoute] string mobileNumber - ) - { - // - // Validate Args ... - if (mobileNumber.IsNullOrEmpty()) - { - return BadRequest( - XException.InvalidArgs - .ToXError() - ); - } - if (!mobileNumber.IsValidMobileNumber()) - { - return BadRequest( - XException.InvalidMobileNumber - .ToXError() - ); - } - - // - // Do Action ... - try - { - // - var result = await IdentityManager - .CanRegister(mobileNumber); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - - // - return result; - } - } - - /// - /// Check a Email Address is Available For Registration or not - /// - /// an string value which represent desired email address - /// a boolean value - [AllowAnonymous] - [RequireXPowered] - [HttpGet("CanRegisterEmail/{email?}")] - public async Task> CanRegisterEmail( - [FromRoute] string email - ) - { - // - // Validate Args ... - if (email.IsNullOrEmpty()) - { - return BadRequest( - XException.InvalidArgs - .ToXError() - ); - } - if (!email.IsValidEmail()) - { - return BadRequest( - XException.InvalidEmailAddress - .ToXError() - ); - } - - // - // Do Action ... - try - { - // - var result = await IdentityManager - .CanRegister(email); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - - // - return result; - } - } - #endregion - - // - #region Confirmations ... - /// - /// Check User is Confirmed Email or not - /// - /// a boolean value - [RequireXPowered] - [HttpGet("IsConfirmedEmail")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - public async Task> IsConfirmedEmail() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .IsConfirmedEmail(User.Identity.Name); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - - // - return result; - } - } - - /// - /// Check User is Confirmed Mobile or not - /// - /// a boolean value - [RequireXPowered] - [HttpGet("IsConfirmedMobile")] - [Authorize(Policy = XPolicies.User)] - [Authorize(Policy = LocalApi.PolicyName)] - public async Task> IsConfirmedMobile() - { - // - // Do Action ... - try - { - // - var result = await IdentityManager - .IsConfirmedMobile(User.Identity.Name); - - // - // Return Result - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - - // - return result; - } - } - - /// - /// Confirm Registration - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost("ConfirmRegistration")] - public async Task ConfirmRegistration( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ActionToken, - model.ReturnUrl - ) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Get Request ... - await IdentityManager - .ConfirmRegistration( - model.Lang, - model.Device, - model.ActionToken, - model.ReturnUrl - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Confirm Requested Mobile Number - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - MobileVerificationCode: a verification code which produced due Request Action. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "mobileVerificationCode": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("ConfirmMobileNumber")] - public async Task> ConfirmMobileNumber( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ActionToken, - model.MobileVerificationCode - ) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Get Request ... - var result = await IdentityManager - .ConfirmMobileNumber( - model.Lang, - model.Device, - model.ActionToken, - model.MobileVerificationCode - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Confirm Requested Email Address - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Device: user's client device which is an instance of XDevice. - /// - EmailVerificationCode: a verification code which produced due Request Action. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "" - /// "emailVerificationCode": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("ConfirmEmailAddress")] - public async Task> ConfirmEmailAddress( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ActionToken, - model.EmailVerificationCode - ) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Get Request ... - var result = await IdentityManager - .ConfirmEmailAddress( - model.Lang, - model.Device, - model.ActionToken, - model.EmailVerificationCode - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Request for Actions ... - /// - /// Request For Mobile Number Change/Confirm - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - MobileNumber: which phone number is going to confirm. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "", - /// "mobileNumber": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestConfirmMobile")] - public async Task> RequestConfirmMobile( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.Password, - model.MobileNumber - ) - .AddNotNull(model.Device) - .AddMobileNumber(model.MobileNumber) - .ValidateGroupAsync(); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam( - model, - excludes: new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // Get Request ... - var result = await IdentityManager - .RequestConfirmMobile( - model.Lang, - model.Device, - userSelectByParam, - model.Password, - model.MobileNumber - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Request For Email Address Change/Confirm - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - Email: which email address is going to confirm. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "password": "", - /// "email": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestConfirmEmail")] - public async Task> RequestConfirmEmail( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.Email, - model.Password) - .AddNotNull(model.Device) - .AddEmailAddress(model.Email) - .ValidateGroupAsync(); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam( - model, - excludes: new List { - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // Get Request ... - var result = await IdentityManager - .RequestConfirmEmail( - model.Lang, - model.Device, - userSelectByParam, - model.Password, - model.Email - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Request Reset Password Action - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application ResetPassword URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "returnUrl": "http://localhost/reset-password", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestResetPassword")] - public async Task> RequestResetPassword( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ReturnUrl) - .AddNotNull(model.Device) - .AddUrl(model.ReturnUrl) - .ValidateGroupAsync(); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam(model); - - // - // Get Request ... - var result = await IdentityManager - .RequestResetPassword( - model.Lang, - model.Device, - userSelectByParam, - model.ReturnUrl - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Reset a User's Password - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - NewPassword: user's new password to change. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "actionToken": "", - /// "newPassword": "", - /// "returnUrl": "http://localhost/login", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost("ResetPassword")] - public async Task ResetPassword( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ActionToken, - model.NewPassword, - model.ReturnUrl) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Get Request ... - await IdentityManager - .ResetPassword( - model.Lang, - model.Device, - model.ActionToken, - model.NewPassword, - model.ReturnUrl - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Request Registration Confirm - /// - /// - /// for this action you have to provide: - /// - a UserSelectedBy identifier which represet User. - /// - Lang: client device currently used locale, such as: en-US. - /// - Password: user's current active password. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Confirm Registration URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userId": "" - /// "password": "", - /// "returnUrl": "http://localhost/confirm", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestConfirmRegistration")] - public async Task RequestConfirmRegistration( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull(model.Device) - .AddUrl(model.ReturnUrl) - .ValidateGroupAsync(); - - // - // Get UserSelect By Param ... - var userSelectByParam = GetUserSelectByParam(model); - - // - // Get Request ... - await IdentityManager - .RequestConfirmRegistration( - model.Lang, - model.Device, - userSelectByParam, - model.Password, - model.ReturnUrl - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - #endregion - - // - #region Registration ... - /// - /// Invite a User to Register on Dashboard - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - Email: which email address is going to invite. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Registration URL. - /// notice in this step you had to provide all this informations as FormData - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "email": "", - /// "returnUrl": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [RequireXPowered] - [HttpPost("InviteUser")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - [Authorize(Policy = XPolicies.EnabledAgent)] - public async Task> InviteUser( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.Email, - model.ReturnUrl) - .AddEmailAddress(model.Email) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .InviteUser( - model.Lang, - model.Device, - model.Email, - model.ReturnUrl); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Recieve some Basic Informations and Start Registration Proccess - /// if they Valid - /// - /// Registration Proccess Starts with Invoking this Action - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - FirstName: user's FirstName. - /// - LastName: user's LastName. - /// - DateOfBirth: user's dob date. - /// - MobileNumber: user's MobileNumber optional. - /// - Email: user's Email optional. - /// - ActionToken: user's requested action token for this action (if user invited). - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "firstName": "", - /// "lastName": "", - /// "dateOfBirth": "", - /// "email": "", - /// "mobileNumber": "", - /// "actionToken": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("RequestRegistration")] - public async Task> RequestRegistration( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.FirstName, - model.LastName) - .AddNotNull( - model.Device, - model.DateOfBirth) - .ValidateGroupAsync(); - - // - // Check Date Of Birth ... - if (!model.DateOfBirth.HasValue) - { - XException.InvalidArgs.Throw(); ; - } - - // - // Validate Mobile Number if Exists ... - if (!model.MobileNumber.IsNullOrEmpty()) - { - ValidationProvider.MobileNumber(model.MobileNumber); - } - - // - // Validate Email Address if Exists ... - if (!model.Email.IsNullOrEmpty()) - { - ValidationProvider.EmailAddress(model.Email); - } - - // - // Get Request ... - var result = await IdentityManager - .RequestRegistration( - model.Lang, - model.Device, - model.ActionToken, - model.FirstName, - model.LastName, - model.DateOfBirth.GetValueOrDefault(), - model.MobileNumber, - model.Email - ); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - - /// - /// Add User Account Informations - /// - /// - /// for this action you have to provide: - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - UserName: user name. - /// - Password: assigne password. - /// - Device: user's client device which is an instance of XDevice. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userName": "", - /// "password": "", - /// "actionToken": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("AddAccountInfo")] - public async Task> AddAccountInfo( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.ActionToken, - model.UserName, - model.Password) - .AddNotNull(model.Device) - .ValidateGroupAsync(); - - // - // Get Request ... - var result = await IdentityManager - .AddAcountInfo( - model.Lang, - model.Device, - model.ActionToken, - model.UserName, - model.Password); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Upload and Attach a Profile Image for User. this is an Optional Step - /// - /// user's requested action token - /// an instance of IFormFile for user's Avatar - /// an instance of XActionResponse - [AllowAnonymous] - [RequireXPowered] - [HttpPost("AttachProfileImage")] - public async Task> AttachProfileImage( - [FromForm] string actionToken, [FromForm] IFormFile file - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(actionToken) - .AddNotNull(file) - .ValidateGroupAsync(); - - // - var result = await IdentityManager - .AttachProfileImage(actionToken, file); - - // - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - return exResult; - } - } - - /// - /// Finish Registrationn Proccess - /// - /// - /// for this action you have to provide: - /// - a proper User Identifier such as: (UserId, UserName, Email or MobileNumber). - /// - Lang: client device currently used locale, such as: en-US. - /// - ActionToken: user's requested action token for this action. - /// - Password: assigne password. - /// - Device: user's client device which is an instance of XDevice. - /// - ReturnUrl: client application Login URL. - /// - /// Sample request: - /// - /// { - /// "lang": "fa-IR", - /// "userName": "", - /// "password": "", - /// "returnUrl": "", - /// "device": { - /// "os":"Mac", - /// "browser":"Chrome", - /// "osVersion":"mac-os-x-15", - /// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36", - /// "deviceType":3, - /// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]", - /// "token":"96f400dd9aa5c57a8cec9d6f4775bad3" - /// } - /// } - /// - /// - /// an instance of XActionRequest class which provider requirement for action - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost("FinishRegistration")] - public async Task FinishRegistration( - [FromBody] XActionRequest model - ) - { - // - // Do Action ... - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - model.Lang, - model.Password, - model.ReturnUrl) - .AddNotNull(model.Device) - .AddUrl(model.ReturnUrl) - .ValidateGroupAsync(); - - // - var userSelectByParam = IdentityManager - .GetUserSelectByParam(model); - ValidationProvider - .NotEmpty(userSelectByParam); - - // - // Get Request ... - await IdentityManager - .FinishRegistration( - model.Lang, - model.Device, - userSelectByParam, - model.Password, - model.ReturnUrl - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var exResult = GetExceptionActionResult(ex); - - // - return exResult; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Search.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - /// - /// Actions which related to Search and Suggest Users for - /// Friendship or Detecting ... - /// - public partial class AccountController - { - // - #region Actions of Search ... - /// - /// Query Open To Search Users Profiles ... - /// Query all Users Which their Profiles is Open To Search ... - /// - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - [RequireXPowered] - [HttpGet("OpenToSearch/Query")] - [Authorize(Policy = LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryOpenToSearchProfiles( - [FromQuery] XQuery query) - { - // - // Do Action ... - try - { - // - var userId = User.Identity.Name; - - // - var result = await IdentityManager.QueryOpenToSearchUsers( - userId, - query - ); - - return Ok(result - .ToDynamicObject()); - } - catch (Exception ex) - { - // - var exception = GetExceptionActionResult(ex); - return exception; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Account\AccountController+Test.cs - -using System.Linq; -using xIds.Providers; -using xIdentityHelper; -using xCommons.Attributes; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class AccountController - { - - // - #region Test Actions ... - /// - /// API Read Scope ... - /// - /// string message - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/PassReadAccess")] - [Authorize(Policy = XPolicies.ReadAccess)] - public ActionResult PassReadAccess() - { - return Ok("Read Access Passed ..."); - } - - /// - /// API Write Scope ... - /// - /// string message - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/PassWriteAccess")] - [Authorize(Policy = XPolicies.WriteAccess)] - public ActionResult PassWriteAccess() - { - return Ok("Write Access Passed ..."); - } - - /// - /// API Admin Scope ... - /// - /// string message - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/PassAdminAccess")] - [Authorize(Policy = XPolicies.AdminAccess)] - public ActionResult PassAdminAccess() - { - return Ok("Admin Access Passed ..."); - } - - /// - /// API Manage Scop ... - /// - /// string message - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/PassManageAccess")] - [Authorize(Policy = XPolicies.ManageAccess)] - public ActionResult PassManageAccess() - { - return Ok("Manage Access Passed ..."); - } - - /// - /// a simple Action which returns a List of Authenticated User Claims ... - /// - /// string message which represent current user's claims - [RequireXPowered] - [HttpGet("Test/HiClaims")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.User)] - public ActionResult HiClaims() - { - // - var result = new - { - name = User.Identity.Name, - claims = User.Claims.Select(c => new - { - c.Type, - c.Value - }) - }; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("Test/HiUser")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.User)] - public ActionResult HiUser() - { - // - var result = $"Hi User: {User.Identity.Name} ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("Test/HiEnabledUser")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public ActionResult HiEnabledUser() - { - // - var result = $"Hi User: {User.Identity.Name} is Enabled ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("Test/HiAdmin")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.Admin)] - public ActionResult HiAdmin() - { - // - var result = $"Hi Admin: {User.Identity.Name} ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello User for Checking Authentication and Policy ... - /// - /// string message which contains authenticated user name - [RequireXPowered] - [HttpGet("Test/HiEnabledAdmin")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public ActionResult HiEnabledAdmin() - { - // - var result = $"Hi Admin: {User.Identity.Name} is Enabled ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Authorization ... - /// - /// - [XApiKeyAccess] - [AllowAnonymous] - [RequireXPowered] - [HttpGet("Test/HiApiKeyAccess")] - [Authorize(LocalApi.PolicyName)] - public ActionResult HiApiKeyAccess() - { - // - var result = $"Hi ApiKey Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Read Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/HiApiKeyReadAccess")] - [XApiKeyAccess(Scopes = [XApiKeyScope.Read])] - public ActionResult HiApiKeyReadAccess() - { - // - var result = $"Hi ApiKey Read Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Write Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/HiApiKeyWriteAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Write])] - public ActionResult HiApiKeyWriteAccess() - { - // - var result = $"Hi ApiKey Write Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Manage Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/HiApiKeyManageAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Manage])] - public ActionResult HiApiKManageAccess() - { - // - var result = $"Hi ApiKey Manage Access, is Passed ..."; - - // - return Ok(result); - } - - /// - /// a simple Hello for Accessing ApiKey Admin Access ... - /// - /// - [AllowAnonymous] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("Test/HiApiKeyAdminAccess")] - [XApiKeyAccess(scopes: [XApiKeyScope.Admin])] - public ActionResult HiApiKeyAdminAccess() - { - // - var result = $"Hi ApiKey Admin Access, is Passed ..."; - - // - return Ok(result); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Applications\ApplicationsController+ApiKey.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class ApplicationsController - { - // - #region ApiKey ... - /// - /// Get Specified ApiKey ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("ApiKeys/{id}")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> GetApiKey( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetApiKeyAsync( - id: id, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified ApiKey ... - /// - /// - /// - /// - [RequireXPowered] - [HttpDelete("ApiKeys/{id}")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> RemoveApiKey( - [FromRoute] Guid id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.RemoveApiKeyAsync( - id: id, - softDelete: false, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update Specified ApiKey ... - /// - /// - /// - /// - /// - [RequireXPowered] - [HttpPut("ApiKeys/{id}")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> UpdateApiKey( - [FromRoute] Guid id, - [FromBody] XApiKeyDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - id.IsDefaultGuid() || - !item.IsValidForAdd() - ) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.UpdateApiKeyAsync( - id: id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Specified ApiKeys ... - /// - /// - /// - [RequireXPowered] - [HttpGet("ApiKeys")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetAllApiKeys( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetAllApiKeyAsync( - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query ApiKeys ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("ApiKeys/Query")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryApiKeys( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryApiKeyAsync( - query: query, - predicate: null, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Applications\ApplicationsController+ApiKeyUsage.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class ApplicationsController - { - // - #region ApiKeyUsage ... - /// - /// Add Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [HttpPost("ApiKeys/Usages")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> AddApiKeyUsage( - [FromBody] XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (item.IsValidForAdd()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.AddApiKeyUsageAsync( - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("ApiKeys/Usages/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> GetApiKeyUsage( - [FromRoute] long id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetApiKeyUsageAsync( - id: id, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Api Key Usage ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpDelete("ApiKeys/Usages/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> RemoveApiKeyUsage( - [FromRoute] long id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.RemoveApiKeyUsageAsync( - id: id, - softDelete: false, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update Specified Api Key Usage ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpPut("ApiKeys/Usages/{id}")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> UpdateApiKeyUsage( - [FromRoute] long id, - [FromBody] XApiKeyUsageDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - id <= 0 || - !item.IsValidForAdd() - ) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.UpdateApiKeyUsageAsync( - id: id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Api Key Usages ... - /// - /// - /// - [RequireXPowered] - [HttpGet("ApiKeys/Usages")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetAllApiKeyUsages( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetAllApiKeyUsageAsync( - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.RequestedOn) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Api Key Usages ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("ApiKeys/Usages/Query")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryApiKeyUsages( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryApiKeyUsageAsync( - query: query, - predicate: null, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.RequestedOn) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Applications\ApplicationsController+Application.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIdentityHelper; -using System.Threading; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Extensions; -using System.Collections.Generic; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class ApplicationsController - { - // - #region Application ... - /// - /// Create Application ... - /// - /// - /// Sample request: - /// - /// { - /// "type": 0, - /// "name": "string", - /// "description": "string", - /// } - /// - /// - /// - /// - /// - [HttpPost("")] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> CreateApplication( - [FromBody] XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!item.IsValidForAdd()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.AddApplicationAsync( - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update Specified Application ... - /// - /// - /// Sample request: - /// - /// { - /// "id": 0, - /// "type": 0, - /// "name": "string", - /// "description": "string", - /// } - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> UpdateApplication( - [FromRoute] int id, - [FromBody] XApplicationDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!id.IsValidIntId() || - !item.IsValidForAdd() || - id != item.Id - ) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.UpdateApplicationAsync( - id: id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Application ... - /// - /// - /// - /// - [RequireXPowered] - [HttpDelete("{id}")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> RemoveApplication( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.RemoveApplicationAsync( - id: id, - softDelete: false, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Application ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("{id}")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task> GetApplication( - [FromRoute] int id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!id.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetApplicationAsync( - id: id, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Application ... - /// - /// - /// - [HttpGet("")] - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetAllApplications( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.GetAllApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Query Applications ... - /// - /// - /// - /// - [RequireXPowered] - [HttpGet("Query")] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> QueryApplications( - [FromRoute] XQuery query, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryApplicationAsync( - query: query, - predicate: null, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Applications\ApplicationsController+Custom.cs - -using System; -using System.Linq; -using xIdentityHelper; -using System.Threading; -using xCommons.Attributes; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using xIdentityModels.Models; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.AspNetCore.Authorization; -using static IdentityServer4.IdentityServerConstants; - -namespace xIds.Controllers -{ - public partial class ApplicationsController - { - // - #region Custom ... - /// - /// Show Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("{applicationId}/ApiKeys/{apiKeyId}/Show")] - public async Task> ShowApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.ShowApiKey( - userInfo: userInfo, - apiKeyId: apiKeyId, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Create Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("{applicationId}/ApiKeys/Create")] - public async Task> CreateApiKey( - [FromRoute] int applicationId, - [FromBody] XCreateApiKeyRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - !request.IsValid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Noramlize TimeSpan ... - var expirationTimeSpan = TimeSpan - .FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes); - if ( - request.ExpirationMinutes.HasValue && - request.ExpirationMinutes.Value > 0 - ) - { - // - // Normalize Expiration Minutes ... - int minutes = request.ExpirationMinutes.Value; - if (minutes > apiKeyConfiguration.MaxExpirationMinutes) - { - minutes = apiKeyConfiguration.MaxExpirationMinutes; - } - - // - expirationTimeSpan = TimeSpan.FromMinutes(minutes); - } - - // - var result = await provider.CreateApiKey( - userInfo: userInfo, - scopes: request.Scopes, - applicationId: applicationId, - rateLimit: request.RateLimit, - allowedIPs: request.AllowedIPs, - expiration: expirationTimeSpan, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpDelete("{applicationId}/ApiKeys/{apiKeyId}")] - public async Task> RemoveApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await provider.RemoveApiKeyAsync( - id: apiKeyId, - softDelete: false, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Rotate Specified Api Key ... - /// - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("{applicationId}/ApiKeys/{apiKeyId}")] - public async Task> RotateApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - [FromBody] XRotateApiKeyRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if ( - request.IsNullOrDefault() || - request.NewExpirationMinutes.IsNull() || - !request.NewExpirationMinutes.HasValue - ) - { - // - request = new XRotateApiKeyRequest - { - NewExpirationMinutes = apiKeyConfiguration.DefaultExpirationMinutes - }; - } - - // - var userInfo = await GetUserInfo(); - var timeSpan = TimeSpan.FromMinutes(request.NewExpirationMinutes.Value); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await provider.RotateApiKey( - apiKeyId: apiKeyId, - userInfo: userInfo, - newExpiration: timeSpan, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpPost("{applicationId}/ApiKeys/{apiKeyId}/Revoke")] - public async Task> RevokeApiKey( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await provider.RevokeApiKey( - apiKeyId: apiKeyId, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Specified Application's Api Keys ... - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [HttpGet("{applicationId}/ApiKeys")] - [Authorize(Policy = XPolicies.EnabledUser)] - public async Task>> GetApiKeys( - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await provider.GetApplicationApiKeys( - userInfo: userInfo, - applicationId: applicationId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Specified Api Keys Usages ... - /// - /// - /// - /// - /// - [RequireXPowered] - [Authorize(LocalApi.PolicyName)] - [Authorize(Policy = XPolicies.EnabledUser)] - [HttpGet("{applicationId}/ApiKeys/{apiKeyId}/Usages")] - public async Task>> GetApiKeyUsages( - [FromRoute] Guid apiKeyId, - [FromRoute] int applicationId, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - !applicationId.IsValidIntId()) - { - XException.InvalidArgs.Throw(); - } - - // - var userInfo = await GetUserInfo(); - - // - // Retrieve Application for Validating ... - var application = await provider.GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Retrieve ApiKey for Validating ... - var apiKey = await provider.GetApiKeyAsync( - id: apiKeyId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await provider.FindManyApiKeyUsageAsync( - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.ApiKeyId == apiKeyId, - orderBuilder: x => x.OrderBy(y => y.RequestedOn) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Validate Specifed Api Key ... - /// - /// - /// - /// - [AllowAnonymous] - [RequireXPowered] - [HttpPost("ApiKeys/Validate")] - [Authorize(LocalApi.PolicyName)] - public async Task> ValidateApiKey( - [FromBody] XApiKeyValidationRequest request, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(request) - .AddNotEmpty(request.ApiKey) - .AddNotEmpty(request.ClientIP) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var checksum = GetRequestChecksum(); - if (checksum.IsNullOrEmpty()) - { - XException.NotAuthorized.Throw(); - } - - // - // Validate Checksum ... - var requestChecksum = securityProvider.Encrypt(request.ToJSON()).ToMd5String(); - if (checksum.ToNormalString() != requestChecksum.ToNormalString()) - { - XException.NotAuthorized.Throw(); - } - - // - var result = await provider.ValidateApiKey( - userInfo: userInfo, - apiKey: request.ApiKey, - clientIP: request.ClientIP, - requiredScope: request.RequiredScope, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Controllers\Base\XIBaseController.cs - -using System; -using xIds.Interfaces; -using xCommons.Providers; -using xCommons.Constants; -using xCommons.Extensions; -using xCommons.Controllers; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityService.Constants; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authentication; - -namespace xIds.Controllers.Base -{ - public abstract class XIBaseController : XBaseController - { - public IXIdentityManager IdentityManager { get; } - - protected XIBaseController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityManager identityManager, - XValidationProvider validationProvider - ) : base( - logger, - appConfiguration, - validationProvider - ) - { - IdentityManager = identityManager; - } - - // - #region User Handlers NonActions ... - /// - /// Retrieve User Identifier Base on XActionRequest - /// - /// - /// - /// - /// - [NonAction] - public string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null) - { - // - // Validate Args ... - ValidationProvider.NotNull(model); - - // - var result = IdentityManager.GetUserSelectByParam( - model, - forceNotNull, - excludes); - - // - return result; - } - - /// - /// Retrieve Access Token - /// - /// - [NonAction] - public async Task GetAccessToken() - { - // - var accessToken = Request.Headers[XAuthorization.Header].ToString(); - if (accessToken.IsNullOrEmpty()) - { - accessToken = await HttpContext.GetTokenAsync(XAuthorization.AccessToken); - } - - // - if (accessToken - .ToNormalString() - .Contains(XAuthorization.TokenIdentifier.ToNormalString())) - { - accessToken = accessToken.Remove(0, XAuthorization.TokenIdentifier.Length); - } - - // - Logger.LogInformation($"Token: {accessToken}"); - return accessToken; - } - - /// - /// Retrieve Refresh Token - /// - /// - [NonAction] - public async Task GetRefreshToken() - { - // - var refreshToken = Request.Headers[XAuthorization.RefreshToken].ToString(); - if (refreshToken.IsNullOrEmpty()) - { - refreshToken = await HttpContext.GetTokenAsync(XAuthorization.RefreshToken); - } - - // - Logger.LogInformation($"Refresh Token: {refreshToken}"); - return refreshToken; - } - - /// - /// Retrieve Access Token Expiration Date - /// - /// - [NonAction] - public async Task GetTokenExpiresAt() - { - // - var expiresAtStr = Request.Headers[XAuthorization.ExpiresAt].ToString(); - if (expiresAtStr.IsNullOrEmpty()) - { - expiresAtStr = await HttpContext.GetTokenAsync(XAuthorization.ExpiresAt); - } - - // - var expiresAt = expiresAtStr.ConvertTo(); - - // - Logger.LogInformation($"Token ExpiresAt: {expiresAtStr}"); - return expiresAt; - } - - /// - /// Retrieve All Required Tokens - /// - /// - [NonAction] - public async Task RetrieveTokensAsXLoginResponse() - { - // - var accessToken = await GetAccessToken(); - var refreshToken = await GetRefreshToken(); - var expiresAt = await GetTokenExpiresAt(); - - // - return new XLoginResponse - { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrieve All Required Tokens - /// - /// - [NonAction] - public async Task RetrieveTokensAsXTokenResponse() - { - // - var accessToken = await GetAccessToken(); - var refreshToken = await GetRefreshToken(); - var expiresAt = await GetTokenExpiresAt(); - - // - return new XTokenResponse - { - AccessToken = accessToken, - RefreshToken = refreshToken, - ExpiresAt = expiresAt - }; - } - - /// - /// Retrive UserInfo - /// - /// - [NonAction] - public async Task GetUserInfo() - { - // - var claims = User.Claims ?? null; - if (!claims.HasChild()) - { - return null; - } - - var xTokens = await RetrieveTokensAsXTokenResponse(); - var result = new XUserClaimsInfoDto( - xTokens.AccessToken, - xTokens.RefreshToken, - xTokens.ExpiresAt, - User.Claims - ); - - // - return result; - } - - /// - /// Validate User Authenticated and Retrieve User Info - /// - /// - [NonAction] - public async Task ValidateAndGetUserInfo() - { - // - if (!User.Identity.IsAuthenticated) - { - XException.NotAuthorized.Throw(); - } - - // - var result = await GetUserInfo(); - if (result.IsNull()) - { - XException.NotAuthorized.Throw(); - } - - // - return result; - } - #endregion - - // - #region NonActions ... - /// - /// Extract Checksum From Headers ... - /// - /// - [NonAction] - public string GetRequestChecksum() - { - // - var result = string.Empty; - - // - var headerKey = XHeader.ChecksumDigest.GetStringValue(); - - // - // Check if Connection ID is Provided ... - if (Request.Headers.ContainsKey(headerKey)) - { - result = Request.Headers[headerKey]; - } - - // - return result; - } - - /// - /// Extract ApiKey From Headers ... - /// - /// - [NonAction] - public string GetRequestApiKey() - { - // - var result = string.Empty; - - // - var headerKey = XHeader.ApiKey.GetStringValue(); - - // - // Check if Connection ID is Provided ... - if (Request.Headers.ContainsKey(headerKey)) - { - result = Request.Headers[headerKey]; - } - - // - return result; - } - - /// - /// Convert an Exception to Propper Error Result - /// - /// - /// - [NonAction] - public new ActionResult GetExceptionActionResult(Exception ex) - { - // - var exception = GetExceptionResult(ex); - var error = ex.Message.ToXError(); - - // - Logger.LogError($"exception: {exception}, error: {error}"); - - // - try - { - var xError = exception.Message.ToXError(); - var xException = (XException)xError.Id; - - // - switch (xException) - { - // - case XException.NotFound: - return NotFound(error); - - // - case XException.NotAuthorized: - return Unauthorized(error); - } - } - catch { } - - // - return BadRequest(error); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\DbContext\XIdentityDbContext.cs - -using xIdentityModels; -using xIdentityModels.Models; -using xIdentityModels.Navigations; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; - -namespace xIds.DbContext -{ - public class XIdentityDbContext : IdentityDbContext - { - // - #region Props/DbSets ... - public DbSet Tokens { get; set; } - public DbSet Devices { get; set; } - public DbSet ApiKeys { get; set; } - public DbSet Avatars { get; set; } - public DbSet ApiKeyUsages { get; set; } - public DbSet Applications { get; set; } - public DbSet BannedDevices { get; set; } - public DbSet Followers { get; set; } - public DbSet Followings { get; set; } - public DbSet VerificationRequests { get; set; } - #endregion - - public XIdentityDbContext(DbContextOptions options) : base(options) - { - // - try - { - Database.EnsureCreated(); - Database.Migrate(); - } - catch { } - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - // - base.OnModelCreating(modelBuilder); - - // - // Fix XUser GUID Generator on Add ... - modelBuilder - .Entity() - .Property(e => e.Id) - .ValueGeneratedOnAdd(); - - // - // Handle Role List ... - modelBuilder.Entity(u => - { - u.HasMany(x => x.Roles) - .WithOne() - .HasForeignKey(ur => ur.UserId) - .IsRequired(); - }); - - // - // Configure XApplication ... - modelBuilder.Entity(e => - { - e.HasIndex(a => a.Name).IsUnique(); - e.HasMany(a => a.ApiKeys) - .WithOne(k => k.Application) - .HasForeignKey(k => k.ApplicationId); - }); - - // - // Configure XApiKey ... - modelBuilder.Entity(e => - { - e.HasIndex(k => k.KeyHash).IsUnique(); - e.HasIndex(k => k.ExpiresAt); - }); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\DI\XDIHelperExtension.cs - -using System.Linq; -using xIds.Helpers; -using xIds.Constants; -using xIds.DbContext; -using xIds.Providers; -using xIdentityHelper; -using xIdentityModels; -using xIds.Extensions; -using xIds.Interfaces; -using xIds.Validators; -using IdentityServer4; -using xCommons.Constants; -using xMessageService.DI; -using xStorageService.DI; -using xCommons.Extensions; -using xIds.Configurations; -using xExceptions.Constants; -using xCommons.Authorization; -using System.Collections.Generic; -using xMessageService.Interfaces; -using xStorageService.Interfaces; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Identity; -using xIdentityModels.Configurations; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xIds.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Application DataProvider - /// - /// - /// - public static void AddXDataProvider( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - // Retrieve DbInfo ... - var dbInfo = configuration.GetXDbInfo(); - var identityDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.IDENTITY_CONNECTION_NAME); - - // - // Register Db Context for EF ... - services.AddDbContext(builder => - { - // - builder.PrepareXDbContextOptionsBuilder( - dbInfo, - identityDbConnectionString - ); - }); - } - - /// - /// Extract Connection String From IConfiguration - /// - /// - /// - /// - public static string GetXConnectionString( - this IConfiguration config, - string connectionName = null - ) - { - // - if (connectionName.IsNullOrEmpty()) - { - connectionName = XDbProviderConfigurations.DEFAULT_CONNECTION_NAME; - } - - // - return config.GetConnectionString(connectionName); - } - - /// - /// Retrive XDataService Configurations ... - /// - /// - /// - /// - public static XDataServiceConfiguration GetXDataServiceConfiguration( - this IConfiguration source, - string connectionName = null - ) - { - // - var xDataServiceConfigSection = source - .GetSection(Constants.ConfigurationNodeNames.DATA_SERVICE_NODE_NAME); - var result = xDataServiceConfigSection.Get(); - if (result.IsNull()) - { - result = new XDataServiceConfiguration(); - } - - // - result.Provider = source.GetXDbProviderType(); - result.ConnectionString = source.GetXConnectionString(connectionName); - - // - return result; - } - - /// - /// Retrieve XApiKeyConfiguration Configurations ... - /// - /// - /// - public static XApiKeyConfiguration GetXApiKeyConfiguration(this IConfiguration source) - { - // - var section = source - .GetSection(Constants.ConfigurationNodeNames.APIKEY_NODE_NAME); - var result = section.Get(); - if (result.IsNull()) - { - result = new XApiKeyConfiguration(); - } - - // - return result; - } - - /// - /// Register XDataService Configuration - /// - /// - /// - /// - public static void AddXDataServiceConfiguration( - this IServiceCollection services, - IConfiguration configuration, - string connectionName = null - ) - { - // - var dataServiceConfiguration = configuration - .GetXDataServiceConfiguration(connectionName); - - // - services.AddSingleton(dataServiceConfiguration); - } - - /// - /// Add Specified ApiKey Configurations Instance ... - /// - /// - /// - public static void AddXApiKeyConfiguration( - this IServiceCollection source, - XApiKeyConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - return; - } - - // - source.AddSingleton(configuration); - } - - /// - /// Extract APpi KLey Configurations from app settings - /// and Register in Services ... - /// - /// - /// - public static void AddXApiKeyConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXApiKeyConfiguration(); - if (config.IsNull()) - { - return; - } - - // - source.AddXApiKeyConfiguration(config); - } - - /// - /// Register Application Provider ... - /// Managing Applications/ApiKeys/ApiKeyUsages ... - /// - /// - /// - public static void AddXApplicationProvider( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - source.AddXApiKeyConfiguration(configuration); - - // - source.AddMemoryCache(); - source.AddScoped(); - } - - /// - /// Register All Requirements For XIdentityServer Usage - /// - /// - /// - public static void AddXIdentityServerRequirements( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - services.AddXDataProvider(configuration); - - // - // Register XIdentityMessageProvider ... - services.AddXIdentityMessageProvider(); - - // - // Register IdentityManager Service ... - var xIdentityManager = services.GetRegisteredService(); - if (xIdentityManager.IsNull()) - { - services.AddXIdentityManager(); - } - - // - // Check XMessage Service Registered or not and Register it if not ... - var xMessageProvider = services.GetRegisteredService(); - if (xMessageProvider.IsNull()) - { - services.AddXMessageService(configuration); - } - - // - // Check Storage Service Registered or not and Register it if not ... - var xStorageProvider = services.GetRegisteredService(); - if (xStorageProvider.IsNull()) - { - services.AddXStorageService(configuration); - } - - // - // Register XIdentityConfiguration ... - var xIdentityConfiguration = configuration.GetXIdentityConfiguration(); - services.AddSingleton(xIdentityConfiguration); - - // - // Register XIdentityHelper ... - services.AddSingleton(); - var xIdentityHelper = services.GetRegisteredService(); - - // - // Register Asp.net Identity ... - services.AddXIdentity(); - } - - /// - /// Add IdentityServer with Support of Ef - /// - /// - /// - public static void AddEfSupportXIdentityServer( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - // Register All Requirements ... - services.AddXIdentityServerRequirements(configuration); - - // - // add DbSeeder Config ... - services.AddXDebSeederDescriptor(configuration); - - // - // Retrieve Certificate ... - var identityServerSigningCertificate = configuration.GetCertificate(CertificatesConfigurations.CertificateNames.IdentityServerSigning); - - // - // Retrieve DbInfo ... - var dbInfo = configuration.GetXDbInfo(); - - // - // Retrieve Connection String Names ... - var configDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.CONFIGURATION_CONNECTION_NAME); - var persistedGrantDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.PRESISTED_GRANTS_CONNECTION_NAME); - - // - // Register IdentityServer ... - services.AddIdentityServer(options => - { - // - options.Discovery.CustomEntries.Add("account_api", "~/account"); - - // - // options.Events.RaiseErrorEvents = true; - // options.Events.RaiseFailureEvents = true; - // options.Events.RaiseSuccessEvents = true; - // options.Events.RaiseInformationEvents = true; - }) - .LoadSigningCredentialFrom(identityServerSigningCertificate) - .AddXDbProvider(configuration) - .AddAspNetIdentity() - .AddProfileService() - .AddResourceOwnerValidator(); - } - - /// - /// force app to use IdentityServer - /// - /// - /// - public static void UseXIdentityServer( - this IApplicationBuilder app, - ILogger logger - ) - { - // - // Update XIdentityServer Configurations before Use Identity Server ... - app.SeedData(logger) - .GetAwaiter() - .GetResult(); - - // - // Use Identity Server ... - app.UseIdentityServer(); - } - - /// - /// Register Asp.net Identity as User Store - /// - /// - public static void AddXIdentity(this IServiceCollection services) - { - // - var xIdentityConfiguration = services.GetRegisteredService(); - if (xIdentityConfiguration.IsNull()) - { - XException.InvalidConfiguration.Throw(); - } - - // - var xIdentityHelper = services.GetRegisteredService(); - if (xIdentityHelper.IsNull()) - { - XException.InvalidConfiguration.Throw(); - } - - // - // Add Identity for User Persists ... - services.AddIdentity(options => - { - // - var mLockoutSpan = xIdentityHelper.GetLockoutTimeSpan(); - - // - // Lockout Setting ... - options.Lockout.DefaultLockoutTimeSpan = mLockoutSpan; - options.Lockout.MaxFailedAccessAttempts = xIdentityConfiguration.Policy.Lockout.MaxFailedAccessAttempts; - options.Lockout.AllowedForNewUsers = xIdentityConfiguration.Policy.Lockout.AllowedForNewUsers; - - // - // Password settings ... - options.Password.RequireDigit = xIdentityConfiguration.Policy.Password.RequireDigit; - options.Password.RequireLowercase = xIdentityConfiguration.Policy.Password.RequireLowercase; - options.Password.RequireNonAlphanumeric = xIdentityConfiguration.Policy.Password.RequireNonAlphanumeric; - options.Password.RequireUppercase = xIdentityConfiguration.Policy.Password.RequireUppercase; - options.Password.RequiredLength = xIdentityConfiguration.Policy.Password.RequiredLength; - options.Password.RequiredUniqueChars = xIdentityConfiguration.Policy.Password.RequiredUniqueChars; - - // - // SignIn settings ... - options.SignIn.RequireConfirmedEmail = xIdentityConfiguration.Policy.SignIn.RequireConfirmedEmail; - options.SignIn.RequireConfirmedPhoneNumber = xIdentityConfiguration.Policy.SignIn.RequireConfirmedPhoneNumber; - - // - // User settings ... - options.User.AllowedUserNameCharacters = xIdentityConfiguration.Policy.User.AllowedUserNameCharacters; - options.User.RequireUniqueEmail = xIdentityConfiguration.Policy.User.RequireUniqueEmail; - }) - .AddEntityFrameworkStores() - .AddDefaultTokenProviders(); - } - - /// - /// Register IdentityServer Based Authentication - /// - /// - /// - public static void AddXIdentityServerAuthentication( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - // Adding Requirements ... - services.AddXIdentityResourceConfiguration(configuration); - - // - // Create Authentication Builder ... - var authBuilder = services.AddAuthentication(); - - // - // Add JwtBearer by Smart Schema ForwardDefaultSelector ... - authBuilder.AddJwtBearer(options => - { - // - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; - }) - .AddLocalApi(); - } - - /// - /// Register Authorization Policies - /// - /// - /// - public static void AddXAuthorization( - this IServiceCollection services, - IDictionary policies = null - ) - { - // - var policyHandler = services.GetRegisteredService(); - services.AddAuthorization(options => - { - // - if (!policies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = policies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - var policyDescriptor = policiesEnumerator.Current; - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - - // - var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); - if (!xPolicies.IsNull()) - { - // - // Fill Policies ... - using (var policiesEnumerator = xPolicies.GetEnumerator()) - { - while (policiesEnumerator.MoveNext()) - { - // - var policyDescriptor = policiesEnumerator.Current; - - // - // Add Policy to Authorization ... - options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); - - // - // Add Policy to Policy Handler ... - if (!policyHandler.IsNull()) - { - // - // Check Policy is RequiredRole Policy ... - var roleRequirements = policyDescriptor.Value.Requirements - .OfType() - .FirstOrDefault(); - if (!roleRequirements.IsNull() && - roleRequirements.Roles.HasChild()) - { - // - policyHandler.AddPolicy( - policy: policyDescriptor.Key.ToNormalString(), - requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) - ); - } - } - } - } - } - - // - // Add Local APi Policy ... - options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy => - { - // - policy.AddAuthenticationSchemes( - [ - // XAuthenticationScheme.XApiKey.GetStringValue(), - IdentityServerConstants.LocalApi.AuthenticationScheme - ]); - - // - policy.RequireAuthenticatedUser(); - }); - }); - - // - services.AddSingleton(); - } - - /// - /// Use Forward Headers Options for resolving behind a proxy issues ... - /// - /// - /// - public static void UseXForwardOptions(this IApplicationBuilder source) - { - // - var forwardOptions = new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, - RequireHeaderSymmetry = false - }; - - // - forwardOptions.KnownNetworks.Clear(); - forwardOptions.KnownProxies.Clear(); - - // - // ref: https://github.com/aspnet/Docs/issues/2384 - source.UseForwardedHeaders(forwardOptions); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Extensions\DbExtensions.cs - -using System; -using xIds.Models; -using xIds.Constants; -using System.Reflection; -using xIds.Configurations; -using xCommons.Extensions; -using Microsoft.EntityFrameworkCore; -using xIdentityModels.Configurations; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using MySql.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace xIds.Extensions -{ - public static class DbExtensions - { - /// - /// Retrieve Data Provider Type from Configurations - /// - /// - /// - public static XDbProviders GetXDbProviderType(this IConfiguration source) - { - // - var dbProvider = (source[$"{ConfigurationNodeNames.PROVIDER_NODE_NAME}"]) - .ToNormalString(); - - // - return dbProvider == ProviderType.SQLServer.ToNormalString() ? - XDbProviders.SQLServer : - dbProvider == ProviderType.SQLite.ToNormalString() ? - XDbProviders.SQLite : - dbProvider == ProviderType.MySQL.ToNormalString() ? - XDbProviders.MySQL : - XDbProviders.None; - } - - /// - /// Retrieve AspNet Identity Configurations - /// - /// - /// - public static XIdentityConfiguration GetXIdentityConfiguration(this IConfiguration source) - { - // - var xIdentityConfigSection = source - .GetSection(ConfigurationNodeNames.IDENTITY_NODE_NAME); - return xIdentityConfigSection.Get(); - } - - /// - /// Retrieve XIdentityResource Configuration from AppSettings - /// - /// - /// - public static XIdentityResourceConfiguration GetXIdentityResourceConfiguration(this IConfiguration configuration) - { - // - var xIdentityResourceSection = configuration.GetSection(ConfigurationNodeNames.IDENTITY_RESOURCE_NODE_NAME); - return xIdentityResourceSection.Get(); - } - - /// - /// Register XIdentityResourceConfiguration - /// - /// - /// - public static void AddXIdentityResourceConfiguration( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - var xIdentityResourceConfiguration = configuration.GetXIdentityResourceConfiguration(); - if (!xIdentityResourceConfiguration.IsNull()) - { - services.AddSingleton(xIdentityResourceConfiguration); - } - } - - /// - /// Converts DbInfo Options Builder for MySql Usage - /// - /// - /// - public static Action GetMySqlOptionsBuilder(this XDbInfo source) - { - return ((Action)source.OptionsBuilder); - } - - /// - /// Converts DbInfo Options Builder for SQLite Usage - /// - /// - /// - public static Action GetSQLiteOptionsBuilder(this XDbInfo source) - { - return ((Action)source.OptionsBuilder); - } - - /// - /// Converts DbInfo Options Builder for SQLServer Usage - /// - /// - /// - public static Action GetSQLServerOptionsBuilder(this XDbInfo source) - { - return ((Action)source.OptionsBuilder); - } - - /// - /// Retrieve Required Informations to Register DbContexts into Di as XDbInfo instance - /// - /// - /// - public static XDbInfo GetXDbInfo(this IConfiguration configuration) - { - return new XDbInfo - { - ProviderType = configuration.GetXDbProviderType(), - MigrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name - }; - } - - /// - /// Prepare DbContextOptionsBuilder with Propper data to Support Configured DbProvider - /// - /// - /// - /// - public static void PrepareXDbContextOptionsBuilder( - this DbContextOptionsBuilder source, - XDbInfo dbInfo, - string connectionString - ) - { - // - if (dbInfo.ProviderType == XDbProviders.MySQL) - { - // - // Add Support for MySql ... - source.UseMySQL( - connectionString, - dbInfo.GetMySqlOptionsBuilder() - ); - } - else if (dbInfo.ProviderType == XDbProviders.SQLite) - { - // - // Add Support for SQLite ... - source.UseSqlite( - connectionString, - dbInfo.GetSQLiteOptionsBuilder() - ); - } - else if (dbInfo.ProviderType == XDbProviders.SQLServer) - { - // - // Add Support for SQLServer ... - source.UseSqlServer( - connectionString, - dbInfo.GetSQLServerOptionsBuilder() - ); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Extensions\IdentityExtensions.cs - -using xIds.Providers; -using xIds.Interfaces; -using Microsoft.Extensions.DependencyInjection; - -namespace xIds.Extensions -{ - public static class IdentityExtensions - { - /// - /// Register IdentityManager - /// - /// - public static void AddXIdentityManager(this IServiceCollection source) - { - source.AddScoped(); - } - - /// - /// Register IdentityMessage Provider - /// - /// - public static void AddXIdentityMessageProvider( - this IServiceCollection source - ) - { - source.AddScoped(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Extensions\IIdentityServerBuilderExtensions.cs - -using xIds.Constants; -using xCommons.Models; -using System.Reflection; -using xCommons.Extensions; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System.Security.Cryptography.X509Certificates; - -namespace xIds.Extensions -{ - public static class IIdentityServerBuilderExtensions - { - /// - /// Add Support for Configured XDbProvider to IdentityServer - /// - /// - /// - /// - public static IIdentityServerBuilder AddXDbProvider( - this IIdentityServerBuilder source, - IConfiguration configuration - ) - { - // - // Retrieve DB Info ... - var dbInfo = configuration.GetXDbInfo(); - dbInfo.OptionsBuilder = (optionsBuilder) => - { - optionsBuilder.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); - optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); - }; - - // - // Retrieve Connection String Names ... - var identityDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.IDENTITY_CONNECTION_NAME); - var configDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.CONFIGURATION_CONNECTION_NAME); - var persistedGrantDbConnectionString = configuration.GetConnectionString(ConnectionStringNames.PRESISTED_GRANTS_CONNECTION_NAME); - - // - // Add Operational Store ... - source.AddOperationalStore(opt => - { - opt.ConfigureDbContext = - builder => - { - // - builder.PrepareXDbContextOptionsBuilder( - dbInfo, - persistedGrantDbConnectionString - ); - - // - builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); - }; - - // - // this enables automatic token cleanup. this is optional. - opt.EnableTokenCleanup = true; - opt.TokenCleanupInterval = 3600; - }); - - // - // Add Configuration Store ... - source.AddConfigurationStore(opt => - { - opt.ConfigureDbContext = - builder => - { - // - builder.PrepareXDbContextOptionsBuilder( - dbInfo, - configDbConnectionString - ); - }; - }); - - // - return source; - } - - /// - /// Set Configured Certificate File to IdentityServer - /// - /// - /// - /// - public static IIdentityServerBuilder LoadSigningCredentialFrom( - this IIdentityServerBuilder builder, - XCertificate certificate - ) - { - // - if (!certificate.IsNull() && - !certificate.Path.IsNullOrEmpty() && - !certificate.Secret.IsNullOrEmpty() - ) - { - try - { - builder.AddSigningCredential(new X509Certificate2(certificate.Path, certificate.Secret)); - } - catch - { - builder.AddDeveloperSigningCredential(); - } - } - else - { - builder.AddDeveloperSigningCredential(); - } - - // - return builder; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Extensions\XDbSeederExtensions.cs - -using System; -using System.Linq; -using xIds.Models; -using xIds.Constants; -using xIds.Interfaces; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityModels.Descriptors; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using IdentityServer4.EntityFramework.Mappers; -using Microsoft.Extensions.DependencyInjection; -using IdentityServer4.EntityFramework.DbContexts; - -namespace xIds.Extensions -{ - public static class XDbSeeder - { - /// - /// Retrieve DbSeedDescriptor from appSetting Configuration - /// - /// - /// - public static XDbSeedDescriptor GetXDbSeedDescriptor(this IConfiguration configuration) - { - // - var dbSeedSection = configuration.GetSection(ConfigurationNodeNames.DB_SEED_NODE_NAME); - return dbSeedSection.Get(); - } - - /// - /// Register XDbSeedDescriptor as Singleton Service - /// - /// - /// - public static void AddXDebSeederDescriptor( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - var dbSeedDescriptor = configuration.GetXDbSeedDescriptor(); - if (!dbSeedDescriptor.IsNull()) - { - services.AddSingleton(dbSeedDescriptor); - } - else - { - Console.WriteLine("Error: DbSeeder Configuration not found in AppSetting ..."); - } - } - - /// - /// Add Base Required Data to XIdentitySer DbContexts - /// - /// - /// - /// - public static async Task SeedData( - this IApplicationBuilder app, - ILogger logger - ) - { - // - logger.LogInformation($"Start Add/Update XIdentityServer Descriptors ..."); - - // - // Create Scope ... - using (var scope = app.ApplicationServices.CreateScope()) - { - // - // Retrieve Required Configurations ... - var dbSeedDescriptor = scope.ServiceProvider.GetService(); - if (dbSeedDescriptor.IsNull()) - { - // - Console.WriteLine("DbSeeder is Null ..."); - return; - } - logger.LogInformation($"Update Exists Descriptors: {dbSeedDescriptor.UpdateExists.ToString()}"); - - // - // Retrieve Required Services ... - var identityProvider = scope.ServiceProvider.GetService(); - - // - // Retrieve DbContexts ... - var grantDbContext = scope.ServiceProvider.GetService(); - var configDbContext = scope.ServiceProvider.GetService(); - - // - #region Clients ... - // - logger.LogInformation($"Start Seeding Clients ..."); - - // - var dClients = dbSeedDescriptor.Clients; - var hasClient = configDbContext.Clients.Any(); - if ((!hasClient || - (hasClient && dbSeedDescriptor.UpdateExists)) && - dClients.HasChild()) - { - // - var clientEntities = dClients.Select(dc => dc.ToEntity()); - - // - foreach (var client in clientEntities) - { - // - logger.LogInformation($"Add/Update: {client.ClientId}"); - - // - // Retrieve Exists Client ... - var existsClient = configDbContext.Clients - .Include(c => c.AllowedCorsOrigins) - .Include(c => c.AllowedGrantTypes) - .Include(c => c.AllowedScopes) - .Include(c => c.Claims) - .Include(c => c.ClientSecrets) - .FirstOrDefault(cl => cl.ClientId == client.ClientId); - - // - var isExistsClient = !existsClient.IsNull(); - var isSameContent = isExistsClient && - existsClient.IsSameContent(client, propertyBlackList: new[] { nameof(existsClient.Id) }); - - // - if (isExistsClient) - { - // - if (!isSameContent) - { - // - logger.LogInformation($"Update Client: {existsClient.ClientId}"); - - // - existsClient = existsClient.UpdateData(client, propertyBlackList: new[] { nameof(existsClient.Id) }); - configDbContext.Clients.Update(existsClient); - } - } - else - { - // - logger.LogInformation($"Add Client: {client.ClientId}"); - - // - await configDbContext.Clients.AddAsync(client); - } - } - - // - // Save Changes on Config Db Context ... - await configDbContext.SaveChangesAsync(); - } - - // - logger.LogInformation($"Finish Seeding Clients ..."); - #endregion - - // - #region IdentityResources ... - // - logger.LogInformation($"Start Seeding Identity Resources ..."); - - // - var dIdentityResources = dbSeedDescriptor.IdentityResources; - var hasIdentityResources = configDbContext.IdentityResources.Any(); - if ((!hasIdentityResources || - (hasIdentityResources && dbSeedDescriptor.UpdateExists)) && - dIdentityResources.HasChild()) - { - // - var identityResourceEntities = dIdentityResources.Select(di => di.ToEntity()); - - // - foreach (var identityResource in identityResourceEntities) - { - // - logger.LogInformation($"Add/Update: {identityResource.DisplayName}"); - - // - // Retrieve Exists IdentityResource ... - var existsIdentityResource = configDbContext.IdentityResources - .AsNoTracking() - .FirstOrDefault(ir => ir.Name == identityResource.Name); - - // - var isExistsResource = !existsIdentityResource.IsNull(); - var isSameContent = isExistsResource && - existsIdentityResource.IsSameContent(identityResource, propertyBlackList: new[] { nameof(existsIdentityResource.Id) }); - - // - if (isExistsResource && - dbSeedDescriptor.UpdateExists) - { - // - if (!isSameContent) - { - // - logger.LogInformation($"Update IdentityResource: {identityResource.DisplayName}"); - - // - existsIdentityResource = existsIdentityResource.UpdateData(identityResource, propertyBlackList: new[] { nameof(existsIdentityResource.Id) }); - configDbContext.IdentityResources.Update(existsIdentityResource); - } - } - else - { - // - logger.LogInformation($"Add IdentityResource: {identityResource.DisplayName}"); - - // - await configDbContext.IdentityResources.AddAsync(identityResource); - } - } - - // - // Save Changes on Config Db Context ... - // await configDbContext.SaveChangesAsync(); - } - - // - logger.LogInformation($"Finish Seeding Identity Resources ..."); - #endregion - - // - #region Api Resources ... - // - logger.LogInformation($"Start Seeding Api Resources ..."); - - // - var dApiResources = dbSeedDescriptor.ApiResources; - var hasApiResources = configDbContext.ApiResources.Any(); - if ((!hasApiResources || - (hasApiResources && dbSeedDescriptor.UpdateExists)) && - dApiResources.HasChild()) - { - // - var apiResourceEntities = dApiResources.Select(da => da.ToEntity()); - - // - foreach (var apiResource in apiResourceEntities) - { - // - logger.LogInformation($"Add/Update: {apiResource.DisplayName}"); - - // - // Retrieve Exists ApiResource ... - var existsApiResource = configDbContext.ApiResources - .Include(r => r.Secrets) - .Include(r => r.Scopes) - .FirstOrDefault(ar => ar.Name == apiResource.Name); - - // - var isExistsResource = !existsApiResource.IsNull(); - var isSameContent = isExistsResource && - existsApiResource.IsSameContent(apiResource, propertyBlackList: new[] { nameof(existsApiResource.Id) }); - - // - if (isExistsResource && - dbSeedDescriptor.UpdateExists) - { - // - if (!isSameContent) - { - // - logger.LogInformation($"Update ApiResource: {existsApiResource.DisplayName}"); - - // - existsApiResource = existsApiResource.UpdateData(apiResource, propertyBlackList: new[] { nameof(existsApiResource.Id) }); - configDbContext.ApiResources.Update(existsApiResource); - } - } - else - { - // - logger.LogInformation($"Add ApiResource: {apiResource.DisplayName}"); - - // - await configDbContext.ApiResources.AddAsync(apiResource); - } - } - - // - // Save Changes on Config Db Context ... - // await configDbContext.SaveChangesAsync(); - } - - // - logger.LogInformation($"Finish Seeding Api Resources ..."); - #endregion - - // - #region Api Scopes ... - // - logger.LogInformation($"Start Seeding Scopes ..."); - - // - var dScopes = dbSeedDescriptor.ApiScopes; - var hasScope = configDbContext.ApiScopes.Any(); - if ((!hasScope || - (hasScope && dbSeedDescriptor.UpdateExists)) && - dScopes.HasChild()) - { - // - var apiScopeEntities = dScopes.Select(dc => dc.ToEntity()); - - // - foreach (var apiScope in apiScopeEntities) - { - // - logger.LogInformation($"Add/Update: {apiScope.DisplayName}"); - - // - // Retrieve Exists Client ... - var existsScope = configDbContext.ApiScopes - .FirstOrDefault(sc => sc.Name == apiScope.Name); - - // - var isExistsScope = !existsScope.IsNull(); - var isSameContent = isExistsScope && - existsScope.IsSameContent(apiScope, propertyBlackList: new[] { nameof(existsScope.Id) }); - - // - if (isExistsScope && - dbSeedDescriptor.UpdateExists) - { - // - if (!isSameContent) - { - // - logger.LogInformation($"Update ApiScope: {existsScope.Name}"); - - // - existsScope = existsScope.UpdateData(apiScope, propertyBlackList: new[] { nameof(existsScope.Id) }); - configDbContext.ApiScopes.Update(existsScope); - } - } - else - { - // - logger.LogInformation($"Add ApiScope: {apiScope.Name}"); - - // - await configDbContext.ApiScopes.AddAsync(apiScope); - } - } - - // - // Save Changes on Config Db Context ... - await configDbContext.SaveChangesAsync(); - } - - // - logger.LogInformation($"Finish Seeding Scopes ..."); - #endregion - - // - #region Users ... - // - logger.LogInformation($"Start Seeding Users ..."); - - // - var configUsers = dbSeedDescriptor.Users; - var hasUser = identityProvider.GetUsersDbSet().Any(); - if ((!hasUser || - (hasUser && dbSeedDescriptor.UpdateExists)) && - configUsers.HasChild()) - { - foreach (var user in configUsers) - { - // - logger.LogInformation($"Add/Update User: {user.UserName}"); - - // - var isUserExists = await identityProvider.IsUserExistsAsync(user.UserName); - if (isUserExists && - dbSeedDescriptor.UpdateExists) - { - // - var existsUser = await identityProvider.GetUserAsync(user.UserName); - var isSame = existsUser.IsSameAs(user); - if (!isSame) - { - // - // Update Entity ... - existsUser = existsUser.UpdateData(user, propertyWhiteList: new[] { - nameof (XIdentityUserDescriptor.FirstName), - nameof (XIdentityUserDescriptor.LastName), - nameof (XIdentityUserDescriptor.UserName), - nameof (XIdentityUserDescriptor.Email), - nameof (XIdentityUserDescriptor.EmailConfirmed), - nameof (XIdentityUserDescriptor.PhoneNumber), - nameof (XIdentityUserDescriptor.PhoneNumberConfirmed), - nameof (XIdentityUserDescriptor.IsEnable), - nameof (XIdentityUserDescriptor.IsBanned), - nameof (XIdentityUserDescriptor.DateOfBirth) - }, propertyValueProviders: new[] { - new KeyValuePair> ( - nameof (XIdentityUserDescriptor.DateOfBirth), - (user) => DateTime.Parse (user.DateOfBirth)) - }); - - // - await identityProvider.UpdateUserAsync(existsUser, false, false); - } - } - else - { - await identityProvider.CreateUserAsync(user); - } - } - } - - // - logger.LogInformation($"Finish Seeding Users ..."); - #endregion - } - - // - logger.LogInformation($"Finish Add/Update XIdentityServer Descriptors ..."); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Extensions\XModelExtensions.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xIds.Extensions -{ - public static class XModelExtensions - { - /// - /// Determine a banned time is passed or not - /// - /// - /// - /// - public static bool IsDelayTimePassed( - this XBannedDevice source, - int delaySeconds - ) - { - // - var passedTime = source.BannedOn.AddSeconds(delaySeconds); - - // - var result = DateTime.UtcNow >= passedTime; - - // - return result; - } - - /// - /// Applying Filter to IQueryable - /// /// - /// - public static async Task> ApplyFilterAsync( - this IQueryable source, - string filter - ) where T : class - { - // - // Apply Filter ... - if (!filter.IsNullOrEmpty()) - { - // - var items = source.AsAsyncEnumerable(); - var filteredItems = new List(); - await - foreach (var item in items) - { - // - if (item.GetPropValues() - .ToNormalString() - .Contains(filter - .ToNormalString())) - { - // - filteredItems.Add(item); - } - } - - // - return filteredItems.AsQueryable(); - } - - // - return source; - } - - public static XDataServiceConfiguration ToXDataServiceConfig(this Configurations.XDataServiceConfiguration config) - { - // - var result = new XDataServiceConfiguration(); - - // - if (!config.IsNullOrDefault()) - { - // - result.PagingConfiguration.DefaultPageSize = config.PagingConfiguration.DefaultPageSize; - result.PagingConfiguration.MaxAvailablePageSize = config.PagingConfiguration.MaxAvailablePageSize; - result.PagingConfiguration.MinAvailablePageSize = config.PagingConfiguration.MinAvailablePageSize; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Helpers\XApiKeyHelper.cs - -using System; -using System.Text; -using System.Security.Cryptography; -using xIdentityModels.Constants; -using xIdentityHelper; - -namespace xIds.Helpers -{ - /// - /// Api Key Generating Helper Class ... - /// - public static class XApiKeyHelper - { - /// - /// Compute Hash of Specified Content using SHA256 ... - /// - /// - /// - public static string ComputeHash(string plain) - { - // - using var sha256 = SHA256.Create(); - var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plain)); - var result = BitConverter.ToString(hashBytes) - .Replace("-", "") - .ToLower(); - - // - return result; - } - - /// - /// Generate an Api Key ... - /// - /// - public static (string plainKey, string hash, string prefix) Generate(string keyPrefix) - { - // - // Generate 32 bytes of cryptographically secure random data - var randomBytes = new byte[32]; - using (var rng = RandomNumberGenerator.Create()) - { - rng.GetBytes(randomBytes); - } - - // - // Format: xapp_{base64url} - var plainKey = $"{keyPrefix}_{Convert.ToBase64String(randomBytes) - .Replace("+", "-").Replace("/", "_").TrimEnd('=')}"; - - // - // Compute Hash ... - var hash = ComputeHash(plainKey); - - // - // Prefix for quick identification (first 12 chars) - var prefix = plainKey.Substring(0, 16) + "..."; - - // - return (plainKey, hash, prefix); - } - - /// - /// Verify Generating Api Key ... - /// - /// - /// - /// - public static bool Verify( - string plainKey, - string storedHash - ) - { - // - var hash = ComputeHash(plainKey); - return hash == storedHash; - } - - /// - /// Retrieve All ApiKey Scopes ... - /// - /// - public static XApiKeyScope[] GetXApiKeyScopes() - { - // - return [ - XApiKeyScope.Read, - XApiKeyScope.Write, - XApiKeyScope.Manage, - XApiKeyScope.Admin, - ]; - } - - /// - /// Retrieve All ApiKey Policies ... - /// - /// - public static string[] GetXApiKeyPolicies() - { - return [ - XPolicies.ApiKeyAccess, - XPolicies.ApiKeyReadAccess, - XPolicies.ApiKeyWriteAccess, - XPolicies.ApiKeyAdminAccess, - XPolicies.ApiKeyManageAccess, - ]; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Helpers\XIdentityHelper.cs - -using System; -using xIds.Interfaces; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Models; -using xIdentityModels.Extensions; -using Microsoft.IdentityModel.Tokens; -using xIdentityModels.Configurations; -using System.IdentityModel.Tokens.Jwt; - -namespace xIds.Helpers -{ - public class XIdentityHelper : IXIdentityHelper - { - private readonly XIdentityConfiguration configurations; - private readonly JwtSecurityTokenHandler tokenHandler; - private readonly XValidationProvider dataValidationHelper; - - public XIdentityHelper( - XIdentityConfiguration configurations, - XValidationProvider dataValidationHelper - ) - { - // - this.configurations = configurations; - this.tokenHandler = new JwtSecurityTokenHandler(); - this.dataValidationHelper = dataValidationHelper; - } - - // - #region Configuration Parser ... - /// - /// Generate a Key for Signing JWT Tokens - /// - /// - public SymmetricSecurityKey GetTokenSecretKey() - { - // - dataValidationHelper - .NotEmpty(configurations.IdentitySecretKey); - - // - var result = new SymmetricSecurityKey(configurations - .IdentitySecretKey.ToBytes()); - - // - return result; - } - - /// - /// Generate Security Token Signing Key - /// - /// - public SigningCredentials GetTokenSigningCredentials() - { - // - var key = GetTokenSecretKey(); - dataValidationHelper - .NotNull(key); - - // - var result = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); - - // - return result; - } - - /// - /// Get Token Validation Parameters - /// - /// - public TokenValidationParameters GetTokenValidationParams() - { - // - var key = GetTokenSecretKey(); - var issuer = configurations.IdentityIssuer; - var audience = configurations.IdentityAudience; - - // - dataValidationHelper - .NotNull(key); - dataValidationHelper - .NotEmpty(issuer, audience); - - // - var result = new TokenValidationParameters - { - ValidIssuer = issuer, - IssuerSigningKey = key, - ValidateLifetime = true, - ValidAudience = audience, - }; - - // - return result; - } - - /// - /// Get Account Lockout Time Span after Max Fail Reached - /// - /// - public TimeSpan GetLockoutTimeSpan() - { - // - dataValidationHelper - .NotNull(configurations.Policy, configurations.Policy.Lockout); - - // - var timeSpanString = configurations.Policy.Lockout.LockoutTimeSpanProvider; - dataValidationHelper - .NotEmpty(timeSpanString); - - // - var mExpireValue = 0; - var mExpireValueStr = timeSpanString.GetDigits(); - var mExpireUnit = timeSpanString.Replace(mExpireValueStr, ""); - dataValidationHelper - .NotEmpty(mExpireUnit); - dataValidationHelper - .NotEmpty(mExpireValueStr); - - // - var isParsed = int.TryParse(mExpireValueStr, out mExpireValue); - - // - switch (mExpireUnit) - { - case "d": - return TimeSpan.FromDays(mExpireValue); - - case "h": - return TimeSpan.FromHours(mExpireValue); - - case "m": - return TimeSpan.FromMinutes(mExpireValue); - - case "s": - return TimeSpan.FromSeconds(mExpireValue); - - case "ms": - default: - return TimeSpan.FromMilliseconds(mExpireValue); - } - } - - /// - /// Generate Security Token Descriptor for Tokenize another - /// - /// - public SecurityTokenDescriptor GetActionTokenDescriptor() - { - // - dataValidationHelper - .NotNull(configurations); - - // - var issuer = configurations.IdentityIssuer; - var audience = configurations.IdentityAudience; - dataValidationHelper - .NotEmpty(issuer, audience); - - // - var expDate = GetActionTokenExpirationDate(); - var signingCreds = GetTokenSigningCredentials(); - dataValidationHelper - .NotNull(expDate, signingCreds); - - // - var descriptor = new SecurityTokenDescriptor - { - Issuer = issuer, - Audience = audience, - Expires = expDate, - SigningCredentials = signingCreds - }; - - // - return descriptor; - } - - /// - /// Get Action Token Expiration Date - /// - /// - public DateTime GetActionTokenExpirationDate() - { - // - dataValidationHelper - .NotNull(configurations); - - // - var expDateProvider = configurations - .ActionTokenExpirationDateProvider; - dataValidationHelper - .NotEmpty(expDateProvider); - - // - var result = GetExpirationTime(expDateProvider); - dataValidationHelper - .NotNull(result); - - // - return result; - } - #endregion - - // - #region Action Token Handlers ... - public bool ValidateToken(string token) - { - // - // Validate Args ... - dataValidationHelper - .NotEmpty(token); - dataValidationHelper - .NotNull(tokenHandler); - - // - // Prepare Requirements ... - var tokenValidationParams = GetTokenValidationParams(); - dataValidationHelper - .NotNull(tokenValidationParams); - - // - var result = token - .ValidateToken(tokenHandler, tokenValidationParams); - - // - return result; - } - - /// - /// Converts a Token string to SecurityToken instance - /// - /// - /// - public SecurityToken ToSecurityToken(string token) - { - // - dataValidationHelper - .NotEmpty(token); - - // - // Validate token ... - var isTokenValid = ValidateToken(token); - if (!isTokenValid) - { - XException.InvalidToken.Throw(); - } - - // - // Prepare and Validate Requirements ... - var tokenValidationParams = GetTokenValidationParams(); - dataValidationHelper - .NotNull(tokenHandler, tokenValidationParams); - - // - var result = token - .ToSecurityToken(tokenHandler, tokenValidationParams); - dataValidationHelper - .NotNull(result); - - // - return result; - } - - /// - /// Convert an ActionRequest to Token Object - /// - /// - /// - public SecurityToken ToSecurityToken(XActionRequestToken request) - { - // - var tokenDescriptor = GetActionTokenDescriptor(); - - // - dataValidationHelper.NotNull(request, tokenHandler, tokenDescriptor); - - // - var result = request.ToJwtToken(tokenHandler, tokenDescriptor); - - // - return result; - } - - /// - /// Retrieve a Token Exiration Date - /// - /// - /// - public DateTime GetTokenExpirationDate(string token) - { - // - var tokenObj = ToSecurityToken(token); - dataValidationHelper.NotNull(tokenObj); - - // - var result = tokenObj.ValidTo; - - // - return result; - } - - public XActionRequestToken ParseActionRequestToken(string token) - { - // - dataValidationHelper - .NotEmpty(token); - - // - // Validate token ... - var isTokenValid = ValidateToken(token); - if (!isTokenValid) - { - XException.InvalidToken.Throw(); - } - - // - // Prepare and Validate Requirements ... - var tokenValidationParams = GetTokenValidationParams(); - dataValidationHelper - .NotNull(tokenHandler, tokenValidationParams); - - // - var result = token - .ParseActionRequestToken(tokenHandler, tokenValidationParams); - dataValidationHelper - .NotNull(result); - - // - return result; - } - - /// - /// Convert a JWT Security Token Object to - /// it's String Representation - /// - /// - /// - public string ToTokenString(JwtSecurityToken token) - { - // - dataValidationHelper.NotNull(token); - - // - var result = tokenHandler - .WriteToken(token); - - // - return result; - } - - /// - /// Convert an Action Token Object to it's String Representation - /// - /// - /// - public string ToTokenString(SecurityToken token) - { - // - // Validate Args ... - dataValidationHelper - .NotNull(token, tokenHandler); - - // - // Generate and return Result ... - var result = token.ToTokenString(tokenHandler); - dataValidationHelper - .NotEmpty(result); - - // - return result; - } - #endregion - - // - #region Private Actions ... - /// - /// Calculating Date Difference Provider String - /// and Generate Date based on UTC Time - /// - /// - /// - private DateTime GetExpirationTime(string expirationProvider) - { - // - dataValidationHelper - .NotEmpty(expirationProvider); - - // - var mExpireValue = 0; - var mExpireValueStr = expirationProvider.GetDigits(); - var mExpireUnit = expirationProvider.Replace(mExpireValueStr, ""); - dataValidationHelper - .NotEmpty(mExpireUnit); - dataValidationHelper - .NotEmpty(mExpireValueStr); - - // - var isParsed = int.TryParse(mExpireValueStr, out mExpireValue); - - // - switch (mExpireUnit) - { - case "d": - return DateTime.UtcNow.AddDays(mExpireValue); - - case "h": - return DateTime.UtcNow.AddHours(mExpireValue); - - case "m": - return DateTime.UtcNow.AddMinutes(mExpireValue); - - case "s": - return DateTime.UtcNow.AddSeconds(mExpireValue); - - case "ms": - default: - return DateTime.UtcNow.AddMilliseconds(mExpireValue); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Interfaces\IXApplicationProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xIds.Interfaces -{ - /// - /// a Service For Manage Security Applications and also Api Key(s) ... - /// - public interface IXApplicationProvider - { - // - #region Application ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - Task AddApplicationAsync( - XApplicationDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - Task UpdateApplicationAsync( - int id, - XApplicationDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - Task RemoveApplicationAsync( - int id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - Task GetApplicationAsync( - int id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - Task> GetAllApplicationAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllApplicationAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task FindOneApplicationAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> FindManyApplicationAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryApplicationAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region ApiKey ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - Task AddApiKeyAsync( - XApiKeyDto item, - string apiKey = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - Task UpdateApiKeyAsync( - Guid id, - XApiKeyDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - Task RemoveApiKeyAsync( - Guid id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - Task GetApiKeyAsync( - Guid id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - Task> GetAllApiKeyAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllApiKeyAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task FindOneApiKeyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> FindManyApiKeyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryApiKeyAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region ApiKeyUsage ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - Task AddApiKeyUsageAsync( - XApiKeyUsageDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - Task UpdateApiKeyUsageAsync( - long id, - XApiKeyUsageDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - Task RemoveApiKeyUsageAsync( - long id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - Task GetApiKeyUsageAsync( - long id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - Task> GetAllApiKeyUsageAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllApiKeyUsageAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task FindOneApiKeyUsageAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> FindManyApiKeyUsageAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryApiKeyUsageAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Custom Actions ... - /// - /// Show Specifid Api Key ... - /// - /// - /// - /// - /// - /// - Task ShowApiKey( - Guid apiKeyId, - int applicationId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Generate a New ApiKey and Add It to DB ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - Task CreateApiKey( - int applicationId, - TimeSpan? expiration = null, - IEnumerable scopes = null, - IEnumerable allowedIPs = null, - int? rateLimit = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - Task RevokeApiKey( - Guid apiKeyId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Renew Specified Api Key ... - /// - /// - /// - /// - /// - /// - Task RotateApiKey( - Guid apiKeyId, - TimeSpan? newExpiration = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve All Api Keys for Specified Application ... - /// - /// - /// - /// - /// - Task> GetApplicationApiKeys( - int applicationId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - - /// - /// Validate Specified Api Key in based on ClientIP ... - /// - /// - /// - /// - /// - /// - /// - Task ValidateApiKey( - string apiKey, - string clientIP, - string requiredScope = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Enrichers ... - /// - /// Enrich Api Key ... - /// - /// - /// - /// - Task EnrichAsync( - XApiKey source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Api Key ... - /// - /// - /// - /// - Task EnrichAsync( - XApiKeyDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Api Key Usage ... - /// - /// - /// - /// - Task EnrichAsync( - XApiKeyUsage source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Application ... - /// - /// - /// - /// - Task EnrichAsync( - XApplication source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Api Key Usage ... - /// - /// - /// - /// - Task EnrichAsync( - XApiKeyUsageDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich Application ... - /// - /// - /// - /// - Task EnrichAsync( - XApplicationDto source, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Api Key(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Api Key(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Api Key Usage(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Application(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Api Key Usage(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - - /// - /// Enrich a Collection of Application(s) ... - /// - /// - /// - /// - Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Interfaces\IXIdentityHelper.cs - -using System; -using System.IdentityModel.Tokens.Jwt; -using Microsoft.IdentityModel.Tokens; -using xIdentityModels.Models; - -namespace xIds.Interfaces -{ - public interface IXIdentityHelper - { - // - #region Configuration Parser ... - SymmetricSecurityKey GetTokenSecretKey(); - SigningCredentials GetTokenSigningCredentials(); - TokenValidationParameters GetTokenValidationParams(); - TimeSpan GetLockoutTimeSpan(); - #endregion - - // - #region Action Token Handlers ... - bool ValidateToken(string token); - SecurityToken ToSecurityToken(string token); - SecurityToken ToSecurityToken(XActionRequestToken request); - string ToTokenString(SecurityToken token); - string ToTokenString(JwtSecurityToken token); - DateTime GetTokenExpirationDate(string token); - XActionRequestToken ParseActionRequestToken(string token); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Interfaces\IXIdentityManager.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIds.DbContext; -using System.Net.Http; -using xIdentityModels; -using System.Threading; -using xCommons.Providers; -using IdentityModel.Client; -using xIdentityModels.Dtos; -using System.Security.Claims; -using System.Threading.Tasks; -using xIdentityModels.Models; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using System.Collections.Generic; -using xIdentityModels.Descriptors; -using xIdentityModels.Navigations; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Identity; - -namespace xIds.Interfaces -{ - public interface IXIdentityManager - { - XIdentityDbContext DbContext { get; } - UserManager UserManager { get; } - ILogger Logger { get; } - SignInManager SignInManager { get; } - IXSecurityProvider SecurityProvider { get; } - RoleManager RoleManager { get; } - XValidationProvider ValidationProvider { get; } - - // - #region Class Getter (s) Methods ... - IQueryable GetUsersDbSet( - bool containsDetail = false - ); - IQueryable GetUsersFullDbSet(bool enableTracking = false); - #endregion - - // - #region Tools ... - string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ); - - Task ValidateUserExistsAndRetrieve( - string userSelectByParam, - bool containsDetail = false, - bool checkCanLoginPolicies = false, - bool checkIsBanned = true, - bool ignoreDisabledUser = false, - bool forceAdmin = false, - Exception exception = null - ); - #endregion - - // - #region Default Identity Preparation Actions ... - Task CreateIdentityRoles(); - Task CreateUserAsync(XIdentityUserDescriptor user); - #endregion - - // - #region Identity Actions ... - HttpClient GetHttpClient(); - Task RequestScopeAccessToken(string scope); - Task RequestDiscoveryDocument(); - Task Authenticate(XLoginRequest model); - Task Login(XLoginRequest model); - Task RefreshTokens(XTokenResponse model); - #endregion - - // - #region Role Handlers ... - Task IsRoleExistsAsync(string roleName); - Task CreateRoleAsync(string roleName); - Task GetRoleAsync(string roleName); - Task AddUserToRoleAsync(XUser user, string roleName); - Task GetRoleNameAsync(string roleId); - Task> GetRoleNamesAsync( - string userSelectByParam, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - Task RemoveFromRoleAsync(XUser user, string roleName); - Task RemoveFromRolesAsync(XUser user, IEnumerable roleNames); - #endregion - - // - #region User Handlers ... - Task CanRegister(string userSelectByParam); - Task IsUserExistsAsync(string userSelectByParam); - Task GetUserAsync( - string userSelectByParam, - bool containsDetail = false); - - Task CreateUserAsync( - XUser user, - string password, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - - Task UpdateUserAsync( - XUser user, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - - Task> GetUserNamesAsync( - IEnumerable userIds - ); - - Task> GetUserNameIdsAsync( - XUserNameIdRequest model - ); - - Task ToJwtClaims( - XUser user, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - - Task CheckPasswordSignInAsync( - XUser user, - string password, - XDevice device, - string language, - bool lockoutOnFailure, - bool isForced = true - ); - #endregion - - // - #region User Profile Handlers ... - Task GetUserProfileAsync( - string userSelectByParam, - string requestedUserSelectByParam, - bool forceCheckRequestedUser = true, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - - Task> QueryUsers( - string requestedUserSelectByParam, - XQuery query - ); - - Task> QueryInRoleUsers( - string requestedUserSelectByParam, - string role, - XQuery query, - bool forceRole = false - ); - - Task> GetUserProfilesAsync( - ICollection ids, - string requestedUserSelectByParam, - bool forceCheckRequestedUser = true, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - - Task> QueryAvatars( - string userSelectByParam, - XQuery query - ); - - Task ProfileUpdateAsync( - string userSelectByParam, - string requestedUserSelectByParam, - XProfileUpdateRequest request - ); - - Task FullProfileUpdateAsync( - string userSelectByParam, - string requestedUserSelectByParam, - XProfileUpdateRequest request - ); - - Task RequestConfirmMobile( - string lang, - XDevice device, - string userSelectByParam, - string password, - string mobileNumber = null - ); - - Task RequestConfirmEmail( - string lang, - XDevice device, - string userSelectByParam, - string password, - string emailAddress = null - ); - - Task RequestResetPassword( - string lang, - XDevice device, - string userSelectByParam, - string returnUrl - ); - - Task RequestConfirmRegistration( - string lang, - XDevice device, - string userSelectByParam, - string password, - string returnUrl - ); - - Task ChangePassword( - string lang, - XDevice device, - string userSelectByParam, - string password, - string newPassword, - string returnUrl - ); - - Task ResetPassword( - string lang, - XDevice device, - string actionHash, - string newPassword, - string returnUrl - ); - - Task AddAvatar( - string userSelectByParam, - IFormFile file - ); - - Task AddAvatars( - string userSelectByParam, - IFormFileCollection files - ); - - Task SetAvatar( - string userSelectByParam, - int profileImageId - ); - - Task RemoveAvatar( - string userSelectByParam, - ICollection profileImageIds - ); - - Task ConfirmRegistration( - string lang, - XDevice device, - string actionHash, - string returnUrl - ); - - Task ConfirmMobileNumber( - string lang, - XDevice device, - string registrationHash, - string verificationCode - ); - - Task ConfirmEmailAddress( - string lang, - XDevice device, - string registrationHash, - string verificationCode - ); - - Task IsConfirmedEmail(string userSelectByParam); - - Task IsConfirmedMobile(string userSelectByParam); - #endregion - - // - #region Registration Handlers ... - Task InviteUser( - string lang, - XDevice device, - string email, - string handlerUrl - ); - - Task RequestRegistration( - string lang, - XDevice device, - string invitationHash, - string firstName, - string lastName, - DateTime dateOfBirth, - string mobileNumber = null, - string emailAddress = null - ); - - Task AddAcountInfo( - string lang, - XDevice device, - string registrationHash, - string userName, - string password - ); - - Task AttachProfileImage( - string tokenHash, - IFormFile file - ); - - Task FinishRegistration( - string lang, - XDevice device, - string userSelectByParam, - string password, - string returnUrl - ); - #endregion - - // - #region Friendship Handlers ... - // - #region Actions ... - Task Follow( - string userSelectByParam, - string destUserSelectByParam - ); - - Task Cancel( - string userSelectByParam, - string destUserSelectByParam - ); - - Task UnFollowFollower( - string userSelectByParam, - string destUserSelectByParam - ); - - Task UnFollowFollowing( - string userSelectByParam, - string destUserSelectByParam - ); - - Task Block( - string userSelectByParam, - string destUserSelectByParam - ); - - Task UnBlock( - string userSelectByParam, - string destUserSelectByParam - ); - #endregion - - // - #region Request Handlers ... - Task AcceptRequest( - string userSelectByParam, - string destUserSelectByParam - ); - - Task RejectRequest( - string userSelectByParam, - string destUserSelectByParam - ); - #endregion - - // - #region Getters ... - Task IsFollower( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ); - - Task GetFollowerState( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ); - - Task GetFollower( - string userSelectByParam, - string destUserSelectByParam - ); - - Task> GetFollowers(string userSelectByParam); - Task> GetAllFollowers(string userSelectByParam); - Task> GetFollowersList(string userSelectByParam); - Task> QueryFollowers( - XQuery query, - string userSelectByParam - ); - - Task IsFollowing( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ); - - Task GetFollowingState( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ); - - Task GetFollowing( - string userSelectByParam, - string destUserSelectByParam - ); - - Task> GetFollowings(string userSelectByParam); - Task> GetAllFollowings(string userSelectByParam); - Task> GetFollowingList(string userSelectByParam); - Task> QueryFollowings( - XQuery query, - string userSelectByParam - ); - #endregion - - // - Task GetFriendshipInfo( - string userSelectByParam, - string destUserSelectByParam, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ); - #endregion - - // - #region Admin Actions ... - Task> Ban( - string userSelectByParam, - XUserNameIdRequest model - ); - - Task> UnBan( - string userSelectByParam, - XUserNameIdRequest model - ); - - Task IsBanned( - string userSelectByParam, - string destUserSelectByParam - ); - #endregion - - // - #region Open Actions ... - // - #region OpenGet ... - Task OpenGet( - XOpenActionInnerDto model - ); - Task OpenGet( - string token, - string actionRequest - ); - #endregion - - Task GetApiKey( - XOpenActionRequestDto dto, - CancellationToken cancellationToken = default - ); - - Task UseApiKey( - XOpenActionRequestDto dto, - CancellationToken cancellationToken = default - ); - - Task GetUserInfo( - XOpenActionRequestDto dto - ); - - Task> GetUserInfos( - XOpenActionRequestDto dto - ); - #endregion - - // - #region Search ... - /// - /// Query Open To Search User Profiles ... - /// - /// requested user's identifier - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - Task> QueryOpenToSearchUsers( - string requestedUserSelectByParam, - XQuery query - ); - #endregion - - // - #region Query Service ... - /// - /// Retrieve Users as Query Model for Query Service ... - /// - /// - /// - /// - /// - /// - public Task> QueryUsers( - string requestedUserSelectByParam, - XQuery query, - string role = null, - bool forceRole = false - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Interfaces\IXIdentityMessageProvider.cs - -namespace xIds.Interfaces -{ - public interface IXIdentityMessageProvider - { - string InviteMsg { get; } - string RegistrationApproveMsg { get; } - string RegisteredMsg { get; } - string VerificationCodeMsg { get; } - string ChangePasswordMsg { get; } - string PasswordChangedMsg { get; } - string NewDeviceLoggedInMsg { get; } - - bool IsReady(); - void PrepareMessages(string lang); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Interfaces\IXSecurityProvider.cs - -namespace xIds.Interfaces -{ - public interface IXSecurityProvider - { - string Encrypt(string plainText); - string Decrypt(string cipherText); - string EncryptFromBytes(byte[] textBytes); - string DecryptFromBytes(byte[] cipherBytes); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\20261010111158_InitialConfigurationMigration.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xIds.Migrations -{ - public partial class InitialConfigurationMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "ApiResources", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Enabled = table.Column(type: "INTEGER", nullable: false), - Name = table.Column(type: "TEXT", maxLength: 200, nullable: false), - DisplayName = table.Column(type: "TEXT", maxLength: 200, nullable: true), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - AllowedAccessTokenSigningAlgorithms = table.Column(type: "TEXT", maxLength: 100, nullable: true), - ShowInDiscoveryDocument = table.Column(type: "INTEGER", nullable: false), - Created = table.Column(type: "TEXT", nullable: false), - Updated = table.Column(type: "TEXT", nullable: true), - LastAccessed = table.Column(type: "TEXT", nullable: true), - NonEditable = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResources", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ApiScopes", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Enabled = table.Column(type: "INTEGER", nullable: false), - Name = table.Column(type: "TEXT", maxLength: 200, nullable: false), - DisplayName = table.Column(type: "TEXT", maxLength: 200, nullable: true), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - Required = table.Column(type: "INTEGER", nullable: false), - Emphasize = table.Column(type: "INTEGER", nullable: false), - ShowInDiscoveryDocument = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiScopes", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Clients", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Enabled = table.Column(type: "INTEGER", nullable: false), - ClientId = table.Column(type: "TEXT", maxLength: 200, nullable: false), - ProtocolType = table.Column(type: "TEXT", maxLength: 200, nullable: false), - RequireClientSecret = table.Column(type: "INTEGER", nullable: false), - ClientName = table.Column(type: "TEXT", maxLength: 200, nullable: true), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - ClientUri = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - LogoUri = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - RequireConsent = table.Column(type: "INTEGER", nullable: false), - AllowRememberConsent = table.Column(type: "INTEGER", nullable: false), - AlwaysIncludeUserClaimsInIdToken = table.Column(type: "INTEGER", nullable: false), - RequirePkce = table.Column(type: "INTEGER", nullable: false), - AllowPlainTextPkce = table.Column(type: "INTEGER", nullable: false), - RequireRequestObject = table.Column(type: "INTEGER", nullable: false), - AllowAccessTokensViaBrowser = table.Column(type: "INTEGER", nullable: false), - FrontChannelLogoutUri = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - FrontChannelLogoutSessionRequired = table.Column(type: "INTEGER", nullable: false), - BackChannelLogoutUri = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - BackChannelLogoutSessionRequired = table.Column(type: "INTEGER", nullable: false), - AllowOfflineAccess = table.Column(type: "INTEGER", nullable: false), - IdentityTokenLifetime = table.Column(type: "INTEGER", nullable: false), - AllowedIdentityTokenSigningAlgorithms = table.Column(type: "TEXT", maxLength: 100, nullable: true), - AccessTokenLifetime = table.Column(type: "INTEGER", nullable: false), - AuthorizationCodeLifetime = table.Column(type: "INTEGER", nullable: false), - ConsentLifetime = table.Column(type: "INTEGER", nullable: true), - AbsoluteRefreshTokenLifetime = table.Column(type: "INTEGER", nullable: false), - SlidingRefreshTokenLifetime = table.Column(type: "INTEGER", nullable: false), - RefreshTokenUsage = table.Column(type: "INTEGER", nullable: false), - UpdateAccessTokenClaimsOnRefresh = table.Column(type: "INTEGER", nullable: false), - RefreshTokenExpiration = table.Column(type: "INTEGER", nullable: false), - AccessTokenType = table.Column(type: "INTEGER", nullable: false), - EnableLocalLogin = table.Column(type: "INTEGER", nullable: false), - IncludeJwtId = table.Column(type: "INTEGER", nullable: false), - AlwaysSendClientClaims = table.Column(type: "INTEGER", nullable: false), - ClientClaimsPrefix = table.Column(type: "TEXT", maxLength: 200, nullable: true), - PairWiseSubjectSalt = table.Column(type: "TEXT", maxLength: 200, nullable: true), - Created = table.Column(type: "TEXT", nullable: false), - Updated = table.Column(type: "TEXT", nullable: true), - LastAccessed = table.Column(type: "TEXT", nullable: true), - UserSsoLifetime = table.Column(type: "INTEGER", nullable: true), - UserCodeType = table.Column(type: "TEXT", maxLength: 100, nullable: true), - DeviceCodeLifetime = table.Column(type: "INTEGER", nullable: false), - NonEditable = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Clients", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "IdentityResources", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Enabled = table.Column(type: "INTEGER", nullable: false), - Name = table.Column(type: "TEXT", maxLength: 200, nullable: false), - DisplayName = table.Column(type: "TEXT", maxLength: 200, nullable: true), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - Required = table.Column(type: "INTEGER", nullable: false), - Emphasize = table.Column(type: "INTEGER", nullable: false), - ShowInDiscoveryDocument = table.Column(type: "INTEGER", nullable: false), - Created = table.Column(type: "TEXT", nullable: false), - Updated = table.Column(type: "TEXT", nullable: true), - NonEditable = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityResources", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ApiResourceClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ApiResourceId = table.Column(type: "INTEGER", nullable: false), - Type = table.Column(type: "TEXT", maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResourceClaims", x => x.Id); - table.ForeignKey( - name: "FK_ApiResourceClaims_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiResourceProperties", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ApiResourceId = table.Column(type: "INTEGER", nullable: false), - Key = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Value = table.Column(type: "TEXT", maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResourceProperties", x => x.Id); - table.ForeignKey( - name: "FK_ApiResourceProperties_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiResourceScopes", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Scope = table.Column(type: "TEXT", maxLength: 200, nullable: false), - ApiResourceId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResourceScopes", x => x.Id); - table.ForeignKey( - name: "FK_ApiResourceScopes_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiResourceSecrets", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ApiResourceId = table.Column(type: "INTEGER", nullable: false), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - Value = table.Column(type: "TEXT", maxLength: 4000, nullable: false), - Expiration = table.Column(type: "TEXT", nullable: true), - Type = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Created = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResourceSecrets", x => x.Id); - table.ForeignKey( - name: "FK_ApiResourceSecrets_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiScopeClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ScopeId = table.Column(type: "INTEGER", nullable: false), - Type = table.Column(type: "TEXT", maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiScopeClaims", x => x.Id); - table.ForeignKey( - name: "FK_ApiScopeClaims_ApiScopes_ScopeId", - column: x => x.ScopeId, - principalTable: "ApiScopes", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiScopeProperties", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ScopeId = table.Column(type: "INTEGER", nullable: false), - Key = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Value = table.Column(type: "TEXT", maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiScopeProperties", x => x.Id); - table.ForeignKey( - name: "FK_ApiScopeProperties_ApiScopes_ScopeId", - column: x => x.ScopeId, - principalTable: "ApiScopes", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Type = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Value = table.Column(type: "TEXT", maxLength: 250, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientClaims", x => x.Id); - table.ForeignKey( - name: "FK_ClientClaims_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientCorsOrigins", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Origin = table.Column(type: "TEXT", maxLength: 150, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientCorsOrigins", x => x.Id); - table.ForeignKey( - name: "FK_ClientCorsOrigins_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientGrantTypes", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - GrantType = table.Column(type: "TEXT", maxLength: 250, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientGrantTypes", x => x.Id); - table.ForeignKey( - name: "FK_ClientGrantTypes_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientIdPRestrictions", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Provider = table.Column(type: "TEXT", maxLength: 200, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientIdPRestrictions", x => x.Id); - table.ForeignKey( - name: "FK_ClientIdPRestrictions_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientPostLogoutRedirectUris", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - PostLogoutRedirectUri = table.Column(type: "TEXT", maxLength: 2000, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientPostLogoutRedirectUris", x => x.Id); - table.ForeignKey( - name: "FK_ClientPostLogoutRedirectUris_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientProperties", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ClientId = table.Column(type: "INTEGER", nullable: false), - Key = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Value = table.Column(type: "TEXT", maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientProperties", x => x.Id); - table.ForeignKey( - name: "FK_ClientProperties_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientRedirectUris", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - RedirectUri = table.Column(type: "TEXT", maxLength: 2000, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientRedirectUris", x => x.Id); - table.ForeignKey( - name: "FK_ClientRedirectUris_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientScopes", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Scope = table.Column(type: "TEXT", maxLength: 200, nullable: false), - ClientId = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientScopes", x => x.Id); - table.ForeignKey( - name: "FK_ClientScopes_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientSecrets", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ClientId = table.Column(type: "INTEGER", nullable: false), - Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - Value = table.Column(type: "TEXT", maxLength: 4000, nullable: false), - Expiration = table.Column(type: "TEXT", nullable: true), - Type = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Created = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientSecrets", x => x.Id); - table.ForeignKey( - name: "FK_ClientSecrets_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "IdentityResourceClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - IdentityResourceId = table.Column(type: "INTEGER", nullable: false), - Type = table.Column(type: "TEXT", maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityResourceClaims", x => x.Id); - table.ForeignKey( - name: "FK_IdentityResourceClaims_IdentityResources_IdentityResourceId", - column: x => x.IdentityResourceId, - principalTable: "IdentityResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "IdentityResourceProperties", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - IdentityResourceId = table.Column(type: "INTEGER", nullable: false), - Key = table.Column(type: "TEXT", maxLength: 250, nullable: false), - Value = table.Column(type: "TEXT", maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityResourceProperties", x => x.Id); - table.ForeignKey( - name: "FK_IdentityResourceProperties_IdentityResources_IdentityResourceId", - column: x => x.IdentityResourceId, - principalTable: "IdentityResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ApiResourceClaims_ApiResourceId", - table: "ApiResourceClaims", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiResourceProperties_ApiResourceId", - table: "ApiResourceProperties", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiResources_Name", - table: "ApiResources", - column: "Name", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ApiResourceScopes_ApiResourceId", - table: "ApiResourceScopes", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiResourceSecrets_ApiResourceId", - table: "ApiResourceSecrets", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopeClaims_ScopeId", - table: "ApiScopeClaims", - column: "ScopeId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopeProperties_ScopeId", - table: "ApiScopeProperties", - column: "ScopeId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopes_Name", - table: "ApiScopes", - column: "Name", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ClientClaims_ClientId", - table: "ClientClaims", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientCorsOrigins_ClientId", - table: "ClientCorsOrigins", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientGrantTypes_ClientId", - table: "ClientGrantTypes", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientIdPRestrictions_ClientId", - table: "ClientIdPRestrictions", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientPostLogoutRedirectUris_ClientId", - table: "ClientPostLogoutRedirectUris", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientProperties_ClientId", - table: "ClientProperties", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientRedirectUris_ClientId", - table: "ClientRedirectUris", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_Clients_ClientId", - table: "Clients", - column: "ClientId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ClientScopes_ClientId", - table: "ClientScopes", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientSecrets_ClientId", - table: "ClientSecrets", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityResourceClaims_IdentityResourceId", - table: "IdentityResourceClaims", - column: "IdentityResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityResourceProperties_IdentityResourceId", - table: "IdentityResourceProperties", - column: "IdentityResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityResources_Name", - table: "IdentityResources", - column: "Name", - unique: true); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ApiResourceClaims"); - - migrationBuilder.DropTable( - name: "ApiResourceProperties"); - - migrationBuilder.DropTable( - name: "ApiResourceScopes"); - - migrationBuilder.DropTable( - name: "ApiResourceSecrets"); - - migrationBuilder.DropTable( - name: "ApiScopeClaims"); - - migrationBuilder.DropTable( - name: "ApiScopeProperties"); - - migrationBuilder.DropTable( - name: "ClientClaims"); - - migrationBuilder.DropTable( - name: "ClientCorsOrigins"); - - migrationBuilder.DropTable( - name: "ClientGrantTypes"); - - migrationBuilder.DropTable( - name: "ClientIdPRestrictions"); - - migrationBuilder.DropTable( - name: "ClientPostLogoutRedirectUris"); - - migrationBuilder.DropTable( - name: "ClientProperties"); - - migrationBuilder.DropTable( - name: "ClientRedirectUris"); - - migrationBuilder.DropTable( - name: "ClientScopes"); - - migrationBuilder.DropTable( - name: "ClientSecrets"); - - migrationBuilder.DropTable( - name: "IdentityResourceClaims"); - - migrationBuilder.DropTable( - name: "IdentityResourceProperties"); - - migrationBuilder.DropTable( - name: "ApiResources"); - - migrationBuilder.DropTable( - name: "ApiScopes"); - - migrationBuilder.DropTable( - name: "Clients"); - - migrationBuilder.DropTable( - name: "IdentityResources"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\20261010111158_InitialConfigurationMigration.Designer.cs - -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace xIds.Migrations -{ - [DbContext(typeof(ConfigurationDbContext))] - [Migration("20261010111158_InitialConfigurationMigration")] - partial class InitialConfigurationMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AllowedAccessTokenSigningAlgorithms") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("LastAccessed") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Emphasize") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Required") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ScopeId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("ScopeId") - .HasColumnType("INTEGER"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ScopeId"); - - b.ToTable("ApiScopeProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AbsoluteRefreshTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("AccessTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("AccessTokenType") - .HasColumnType("INTEGER"); - - b.Property("AllowAccessTokensViaBrowser") - .HasColumnType("INTEGER"); - - b.Property("AllowOfflineAccess") - .HasColumnType("INTEGER"); - - b.Property("AllowPlainTextPkce") - .HasColumnType("INTEGER"); - - b.Property("AllowRememberConsent") - .HasColumnType("INTEGER"); - - b.Property("AllowedIdentityTokenSigningAlgorithms") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("AlwaysIncludeUserClaimsInIdToken") - .HasColumnType("INTEGER"); - - b.Property("AlwaysSendClientClaims") - .HasColumnType("INTEGER"); - - b.Property("AuthorizationCodeLifetime") - .HasColumnType("INTEGER"); - - b.Property("BackChannelLogoutSessionRequired") - .HasColumnType("INTEGER"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("ConsentLifetime") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DeviceCodeLifetime") - .HasColumnType("INTEGER"); - - b.Property("EnableLocalLogin") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("FrontChannelLogoutSessionRequired") - .HasColumnType("INTEGER"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("IdentityTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("IncludeJwtId") - .HasColumnType("INTEGER"); - - b.Property("LastAccessed") - .HasColumnType("TEXT"); - - b.Property("LogoUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("RefreshTokenExpiration") - .HasColumnType("INTEGER"); - - b.Property("RefreshTokenUsage") - .HasColumnType("INTEGER"); - - b.Property("RequireClientSecret") - .HasColumnType("INTEGER"); - - b.Property("RequireConsent") - .HasColumnType("INTEGER"); - - b.Property("RequirePkce") - .HasColumnType("INTEGER"); - - b.Property("RequireRequestObject") - .HasColumnType("INTEGER"); - - b.Property("SlidingRefreshTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("UpdateAccessTokenClaimsOnRefresh") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.Property("UserCodeType") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("UserSsoLifetime") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Emphasize") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("Required") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("IdentityResourceId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityResourceClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("IdentityResourceId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityResourceProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Properties") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") - .WithMany("UserClaims") - .HasForeignKey("ScopeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Scope"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") - .WithMany("Properties") - .HasForeignKey("ScopeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Scope"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("IdentityResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("Properties") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("IdentityResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Navigation("Properties"); - - b.Navigation("Scopes"); - - b.Navigation("Secrets"); - - b.Navigation("UserClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Navigation("Properties"); - - b.Navigation("UserClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Navigation("AllowedCorsOrigins"); - - b.Navigation("AllowedGrantTypes"); - - b.Navigation("AllowedScopes"); - - b.Navigation("Claims"); - - b.Navigation("ClientSecrets"); - - b.Navigation("IdentityProviderRestrictions"); - - b.Navigation("PostLogoutRedirectUris"); - - b.Navigation("Properties"); - - b.Navigation("RedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Navigation("Properties"); - - b.Navigation("UserClaims"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\ConfigurationDbContextModelSnapshot.cs - -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace xIds.Migrations -{ - [DbContext(typeof(ConfigurationDbContext))] - partial class ConfigurationDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AllowedAccessTokenSigningAlgorithms") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("LastAccessed") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiResourceId") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiResourceSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Emphasize") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Required") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ScopeId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("ScopeId") - .HasColumnType("INTEGER"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ScopeId"); - - b.ToTable("ApiScopeProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AbsoluteRefreshTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("AccessTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("AccessTokenType") - .HasColumnType("INTEGER"); - - b.Property("AllowAccessTokensViaBrowser") - .HasColumnType("INTEGER"); - - b.Property("AllowOfflineAccess") - .HasColumnType("INTEGER"); - - b.Property("AllowPlainTextPkce") - .HasColumnType("INTEGER"); - - b.Property("AllowRememberConsent") - .HasColumnType("INTEGER"); - - b.Property("AllowedIdentityTokenSigningAlgorithms") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("AlwaysIncludeUserClaimsInIdToken") - .HasColumnType("INTEGER"); - - b.Property("AlwaysSendClientClaims") - .HasColumnType("INTEGER"); - - b.Property("AuthorizationCodeLifetime") - .HasColumnType("INTEGER"); - - b.Property("BackChannelLogoutSessionRequired") - .HasColumnType("INTEGER"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("ConsentLifetime") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DeviceCodeLifetime") - .HasColumnType("INTEGER"); - - b.Property("EnableLocalLogin") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("FrontChannelLogoutSessionRequired") - .HasColumnType("INTEGER"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("IdentityTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("IncludeJwtId") - .HasColumnType("INTEGER"); - - b.Property("LastAccessed") - .HasColumnType("TEXT"); - - b.Property("LogoUri") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("RefreshTokenExpiration") - .HasColumnType("INTEGER"); - - b.Property("RefreshTokenUsage") - .HasColumnType("INTEGER"); - - b.Property("RequireClientSecret") - .HasColumnType("INTEGER"); - - b.Property("RequireConsent") - .HasColumnType("INTEGER"); - - b.Property("RequirePkce") - .HasColumnType("INTEGER"); - - b.Property("RequireRequestObject") - .HasColumnType("INTEGER"); - - b.Property("SlidingRefreshTokenLifetime") - .HasColumnType("INTEGER"); - - b.Property("UpdateAccessTokenClaimsOnRefresh") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.Property("UserCodeType") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("UserSsoLifetime") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClientId") - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Created") - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("DisplayName") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Emphasize") - .HasColumnType("INTEGER"); - - b.Property("Enabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("NonEditable") - .HasColumnType("INTEGER"); - - b.Property("Required") - .HasColumnType("INTEGER"); - - b.Property("ShowInDiscoveryDocument") - .HasColumnType("INTEGER"); - - b.Property("Updated") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("IdentityResourceId") - .HasColumnType("INTEGER"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityResourceClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("IdentityResourceId") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250) - .HasColumnType("TEXT"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityResourceProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Properties") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("ApiResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") - .WithMany("UserClaims") - .HasForeignKey("ScopeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Scope"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") - .WithMany("Properties") - .HasForeignKey("ScopeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Scope"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Client"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("IdentityResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("Properties") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("IdentityResource"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Navigation("Properties"); - - b.Navigation("Scopes"); - - b.Navigation("Secrets"); - - b.Navigation("UserClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Navigation("Properties"); - - b.Navigation("UserClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Navigation("AllowedCorsOrigins"); - - b.Navigation("AllowedGrantTypes"); - - b.Navigation("AllowedScopes"); - - b.Navigation("Claims"); - - b.Navigation("ClientSecrets"); - - b.Navigation("IdentityProviderRestrictions"); - - b.Navigation("PostLogoutRedirectUris"); - - b.Navigation("Properties"); - - b.Navigation("RedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Navigation("Properties"); - - b.Navigation("UserClaims"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\PersistedGrantDb\20261010111213_InitialPersistedGrantMigration.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xIds.Migrations.PersistedGrantDb -{ - public partial class InitialPersistedGrantMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "DeviceCodes", - columns: table => new - { - UserCode = table.Column(type: "TEXT", maxLength: 200, nullable: false), - DeviceCode = table.Column(type: "TEXT", maxLength: 200, nullable: false), - SubjectId = table.Column(type: "TEXT", maxLength: 200, nullable: true), - SessionId = table.Column(type: "TEXT", maxLength: 100, nullable: true), - ClientId = table.Column(type: "TEXT", maxLength: 200, nullable: false), - Description = table.Column(type: "TEXT", maxLength: 200, nullable: true), - CreationTime = table.Column(type: "TEXT", nullable: false), - Expiration = table.Column(type: "TEXT", nullable: false), - Data = table.Column(type: "TEXT", maxLength: 50000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); - }); - - migrationBuilder.CreateTable( - name: "PersistedGrants", - columns: table => new - { - Key = table.Column(type: "TEXT", maxLength: 200, nullable: false), - Type = table.Column(type: "TEXT", maxLength: 50, nullable: false), - SubjectId = table.Column(type: "TEXT", maxLength: 200, nullable: true), - SessionId = table.Column(type: "TEXT", maxLength: 100, nullable: true), - ClientId = table.Column(type: "TEXT", maxLength: 200, nullable: false), - Description = table.Column(type: "TEXT", maxLength: 200, nullable: true), - CreationTime = table.Column(type: "TEXT", nullable: false), - Expiration = table.Column(type: "TEXT", nullable: true), - ConsumedTime = table.Column(type: "TEXT", nullable: true), - Data = table.Column(type: "TEXT", maxLength: 50000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_PersistedGrants", x => x.Key); - }); - - migrationBuilder.CreateIndex( - name: "IX_DeviceCodes_DeviceCode", - table: "DeviceCodes", - column: "DeviceCode", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_DeviceCodes_Expiration", - table: "DeviceCodes", - column: "Expiration"); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_Expiration", - table: "PersistedGrants", - column: "Expiration"); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type", - table: "PersistedGrants", - columns: new[] { "SubjectId", "ClientId", "Type" }); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_SessionId_Type", - table: "PersistedGrants", - columns: new[] { "SubjectId", "SessionId", "Type" }); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "DeviceCodes"); - - migrationBuilder.DropTable( - name: "PersistedGrants"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\PersistedGrantDb\20261010111213_InitialPersistedGrantMigration.Designer.cs - -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace xIds.Migrations.PersistedGrantDb -{ - [DbContext(typeof(PersistedGrantDbContext))] - [Migration("20261010111213_InitialPersistedGrantMigration")] - partial class InitialPersistedGrantMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => - { - b.Property("UserCode") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("CreationTime") - .HasColumnType("TEXT"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000) - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("DeviceCode") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("SessionId") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("SubjectId") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("UserCode"); - - b.HasIndex("DeviceCode") - .IsUnique(); - - b.HasIndex("Expiration"); - - b.ToTable("DeviceCodes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => - { - b.Property("Key") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ConsumedTime") - .HasColumnType("TEXT"); - - b.Property("CreationTime") - .HasColumnType("TEXT"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000) - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("SessionId") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("SubjectId") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(50) - .HasColumnType("TEXT"); - - b.HasKey("Key"); - - b.HasIndex("Expiration"); - - b.HasIndex("SubjectId", "ClientId", "Type"); - - b.HasIndex("SubjectId", "SessionId", "Type"); - - b.ToTable("PersistedGrants"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\PersistedGrantDb\PersistedGrantDbContextModelSnapshot.cs - -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace xIds.Migrations.PersistedGrantDb -{ - [DbContext(typeof(PersistedGrantDbContext))] - partial class PersistedGrantDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => - { - b.Property("UserCode") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("CreationTime") - .HasColumnType("TEXT"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000) - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("DeviceCode") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("SessionId") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("SubjectId") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.HasKey("UserCode"); - - b.HasIndex("DeviceCode") - .IsUnique(); - - b.HasIndex("Expiration"); - - b.ToTable("DeviceCodes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => - { - b.Property("Key") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ConsumedTime") - .HasColumnType("TEXT"); - - b.Property("CreationTime") - .HasColumnType("TEXT"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000) - .HasColumnType("TEXT"); - - b.Property("Description") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Expiration") - .HasColumnType("TEXT"); - - b.Property("SessionId") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("SubjectId") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(50) - .HasColumnType("TEXT"); - - b.HasKey("Key"); - - b.HasIndex("Expiration"); - - b.HasIndex("SubjectId", "ClientId", "Type"); - - b.HasIndex("SubjectId", "SessionId", "Type"); - - b.ToTable("PersistedGrants"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\XIdentityDb\20261010111228_InitialIdentityServerDbContext.cs - -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace xIds.Migrations.XIdentityDb -{ - public partial class InitialIdentityServerDbContext : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "ApiKeyUsages", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - ApiKeyId = table.Column(type: "TEXT", nullable: false), - Endpoint = table.Column(type: "TEXT", nullable: true), - HttpMethod = table.Column(type: "TEXT", nullable: true), - ClientIP = table.Column(type: "TEXT", nullable: true), - StatusCode = table.Column(type: "INTEGER", nullable: false), - RequestedOn = table.Column(type: "TEXT", nullable: false), - ResponseTimeMs = table.Column(type: "INTEGER", nullable: false), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiKeyUsages", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Applications", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), - Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - OwnerId = table.Column(type: "TEXT", maxLength: 255, nullable: false), - Type = table.Column(type: "INTEGER", nullable: false), - IsActive = table.Column(type: "INTEGER", nullable: false), - CreatedOn = table.Column(type: "TEXT", nullable: false), - UpdatedAt = table.Column(type: "TEXT", nullable: false), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Applications", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AspNetRoles", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Name = table.Column(type: "TEXT", maxLength: 256, nullable: true), - NormalizedName = table.Column(type: "TEXT", maxLength: 256, nullable: true), - ConcurrencyStamp = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetRoles", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "AspNetUsers", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Discriminator = table.Column(type: "TEXT", nullable: false), - FirstName = table.Column(type: "TEXT", maxLength: 50, nullable: true), - LastName = table.Column(type: "TEXT", maxLength: 100, nullable: true), - IsEnable = table.Column(type: "INTEGER", nullable: true), - IsBanned = table.Column(type: "INTEGER", nullable: true), - DateOfBirth = table.Column(type: "TEXT", nullable: true), - CreationDate = table.Column(type: "TEXT", nullable: true), - LastLogin = table.Column(type: "TEXT", nullable: true), - Avatar = table.Column(type: "TEXT", nullable: true), - Gender = table.Column(type: "INTEGER", nullable: true), - Bio = table.Column(type: "TEXT", nullable: true), - CoverImage = table.Column(type: "TEXT", nullable: true), - OpenToSearch = table.Column(type: "INTEGER", nullable: true), - UserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), - NormalizedUserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), - Email = table.Column(type: "TEXT", maxLength: 256, nullable: true), - NormalizedEmail = table.Column(type: "TEXT", maxLength: 256, nullable: true), - EmailConfirmed = table.Column(type: "INTEGER", nullable: false), - PasswordHash = table.Column(type: "TEXT", nullable: true), - SecurityStamp = table.Column(type: "TEXT", nullable: true), - ConcurrencyStamp = table.Column(type: "TEXT", nullable: true), - PhoneNumber = table.Column(type: "TEXT", nullable: true), - PhoneNumberConfirmed = table.Column(type: "INTEGER", nullable: false), - TwoFactorEnabled = table.Column(type: "INTEGER", nullable: false), - LockoutEnd = table.Column(type: "TEXT", nullable: true), - LockoutEnabled = table.Column(type: "INTEGER", nullable: false), - AccessFailedCount = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUsers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "BannedDevices", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - BannedOn = table.Column(type: "TEXT", nullable: false), - DeviceStr = table.Column(type: "TEXT", nullable: true), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_BannedDevices", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Tokens", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Token = table.Column(type: "TEXT", nullable: true), - Hash = table.Column(type: "TEXT", nullable: true), - UserSelectByParam = table.Column(type: "TEXT", nullable: true), - DeviceStr = table.Column(type: "TEXT", nullable: true), - Type = table.Column(type: "INTEGER", nullable: false), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Tokens", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "VerificationRequests", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - VerificationCode = table.Column(type: "TEXT", nullable: false), - NumberOfTries = table.Column(type: "INTEGER", nullable: false), - LastTryOn = table.Column(type: "TEXT", nullable: false), - RequestStr = table.Column(type: "TEXT", nullable: true), - DeviceStr = table.Column(type: "TEXT", nullable: true), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_VerificationRequests", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ApiKeys", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - ApplicationId = table.Column(type: "INTEGER", nullable: false), - Key = table.Column(type: "TEXT", nullable: false), - KeyHash = table.Column(type: "TEXT", maxLength: 512, nullable: false), - KeyPrefix = table.Column(type: "TEXT", maxLength: 100, nullable: true), - ExpiresAt = table.Column(type: "TEXT", nullable: false), - CreatedOn = table.Column(type: "TEXT", nullable: false), - LastUsedAt = table.Column(type: "TEXT", nullable: true), - RevokedAt = table.Column(type: "TEXT", nullable: true), - RevokedBy = table.Column(type: "TEXT", nullable: true), - AllowedScopes = table.Column(type: "TEXT", maxLength: 1000, nullable: true), - AllowedIPs = table.Column(type: "TEXT", maxLength: 2000, nullable: true), - RateLimitPerMinute = table.Column(type: "INTEGER", nullable: false), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiKeys", x => x.Id); - table.ForeignKey( - name: "FK_ApiKeys_Applications_ApplicationId", - column: x => x.ApplicationId, - principalTable: "Applications", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetRoleClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - RoleId = table.Column(type: "TEXT", nullable: false), - ClaimType = table.Column(type: "TEXT", nullable: true), - ClaimValue = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); - table.ForeignKey( - name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", - column: x => x.RoleId, - principalTable: "AspNetRoles", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserClaims", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - UserId = table.Column(type: "TEXT", nullable: false), - ClaimType = table.Column(type: "TEXT", nullable: true), - ClaimValue = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); - table.ForeignKey( - name: "FK_AspNetUserClaims_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserLogins", - columns: table => new - { - LoginProvider = table.Column(type: "TEXT", nullable: false), - ProviderKey = table.Column(type: "TEXT", nullable: false), - ProviderDisplayName = table.Column(type: "TEXT", nullable: true), - UserId = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); - table.ForeignKey( - name: "FK_AspNetUserLogins_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserRoles", - columns: table => new - { - UserId = table.Column(type: "TEXT", nullable: false), - RoleId = table.Column(type: "TEXT", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); - table.ForeignKey( - name: "FK_AspNetUserRoles_AspNetRoles_RoleId", - column: x => x.RoleId, - principalTable: "AspNetRoles", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_AspNetUserRoles_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "AspNetUserTokens", - columns: table => new - { - UserId = table.Column(type: "TEXT", nullable: false), - LoginProvider = table.Column(type: "TEXT", nullable: false), - Name = table.Column(type: "TEXT", nullable: false), - Value = table.Column(type: "TEXT", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); - table.ForeignKey( - name: "FK_AspNetUserTokens_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Avatars", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - UserId = table.Column(type: "TEXT", nullable: true), - Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), - Thumb = table.Column(type: "TEXT", maxLength: 255, nullable: false), - Path = table.Column(type: "TEXT", maxLength: 255, nullable: false), - ThumbPath = table.Column(type: "TEXT", maxLength: 255, nullable: false), - CreationDate = table.Column(type: "TEXT", nullable: false), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Avatars", x => x.Id); - table.ForeignKey( - name: "FK_Avatars_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateTable( - name: "Devices", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - Os = table.Column(type: "TEXT", nullable: true), - OsVersion = table.Column(type: "TEXT", nullable: true), - Browser = table.Column(type: "TEXT", nullable: true), - UserAgent = table.Column(type: "TEXT", nullable: true), - DeviceType = table.Column(type: "INTEGER", nullable: false), - UserId = table.Column(type: "TEXT", nullable: true), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Devices", x => x.Id); - table.ForeignKey( - name: "FK_Devices_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateTable( - name: "Followers", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - State = table.Column(type: "INTEGER", nullable: false), - UserId = table.Column(type: "TEXT", nullable: true), - DestId = table.Column(type: "TEXT", nullable: true), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Followers", x => x.Id); - table.ForeignKey( - name: "FK_Followers_AspNetUsers_DestId", - column: x => x.DestId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - table.ForeignKey( - name: "FK_Followers_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateTable( - name: "Followings", - columns: table => new - { - Id = table.Column(type: "INTEGER", nullable: false) - .Annotation("Sqlite:Autoincrement", true), - State = table.Column(type: "INTEGER", nullable: false), - UserId = table.Column(type: "TEXT", nullable: true), - DestId = table.Column(type: "TEXT", nullable: true), - Deleted = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Followings", x => x.Id); - table.ForeignKey( - name: "FK_Followings_AspNetUsers_DestId", - column: x => x.DestId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - table.ForeignKey( - name: "FK_Followings_AspNetUsers_UserId", - column: x => x.UserId, - principalTable: "AspNetUsers", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); - - migrationBuilder.CreateIndex( - name: "IX_ApiKeys_ApplicationId", - table: "ApiKeys", - column: "ApplicationId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiKeys_ExpiresAt", - table: "ApiKeys", - column: "ExpiresAt"); - - migrationBuilder.CreateIndex( - name: "IX_ApiKeys_KeyHash", - table: "ApiKeys", - column: "KeyHash", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Applications_Name", - table: "Applications", - column: "Name", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_AspNetRoleClaims_RoleId", - table: "AspNetRoleClaims", - column: "RoleId"); - - migrationBuilder.CreateIndex( - name: "RoleNameIndex", - table: "AspNetRoles", - column: "NormalizedName", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_AspNetUserClaims_UserId", - table: "AspNetUserClaims", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_AspNetUserLogins_UserId", - table: "AspNetUserLogins", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_AspNetUserRoles_RoleId", - table: "AspNetUserRoles", - column: "RoleId"); - - migrationBuilder.CreateIndex( - name: "EmailIndex", - table: "AspNetUsers", - column: "NormalizedEmail"); - - migrationBuilder.CreateIndex( - name: "UserNameIndex", - table: "AspNetUsers", - column: "NormalizedUserName", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Avatars_UserId", - table: "Avatars", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Devices_UserId", - table: "Devices", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Followers_DestId", - table: "Followers", - column: "DestId"); - - migrationBuilder.CreateIndex( - name: "IX_Followers_UserId", - table: "Followers", - column: "UserId"); - - migrationBuilder.CreateIndex( - name: "IX_Followings_DestId", - table: "Followings", - column: "DestId"); - - migrationBuilder.CreateIndex( - name: "IX_Followings_UserId", - table: "Followings", - column: "UserId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ApiKeys"); - - migrationBuilder.DropTable( - name: "ApiKeyUsages"); - - migrationBuilder.DropTable( - name: "AspNetRoleClaims"); - - migrationBuilder.DropTable( - name: "AspNetUserClaims"); - - migrationBuilder.DropTable( - name: "AspNetUserLogins"); - - migrationBuilder.DropTable( - name: "AspNetUserRoles"); - - migrationBuilder.DropTable( - name: "AspNetUserTokens"); - - migrationBuilder.DropTable( - name: "Avatars"); - - migrationBuilder.DropTable( - name: "BannedDevices"); - - migrationBuilder.DropTable( - name: "Devices"); - - migrationBuilder.DropTable( - name: "Followers"); - - migrationBuilder.DropTable( - name: "Followings"); - - migrationBuilder.DropTable( - name: "Tokens"); - - migrationBuilder.DropTable( - name: "VerificationRequests"); - - migrationBuilder.DropTable( - name: "Applications"); - - migrationBuilder.DropTable( - name: "AspNetRoles"); - - migrationBuilder.DropTable( - name: "AspNetUsers"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\XIdentityDb\20261010111228_InitialIdentityServerDbContext.Designer.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xIds.DbContext; - -namespace xIds.Migrations.XIdentityDb -{ - [DbContext(typeof(XIdentityDbContext))] - [Migration("20261010111228_InitialIdentityServerDbContext")] - partial class InitialIdentityServerDbContext - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => - { - b.Property("Id") - .HasColumnType("TEXT"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("TEXT"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("NormalizedName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName") - .IsUnique() - .HasDatabaseName("RoleNameIndex"); - - b.ToTable("AspNetRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClaimType") - .HasColumnType("TEXT"); - - b.Property("ClaimValue") - .HasColumnType("TEXT"); - - b.Property("RoleId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AccessFailedCount") - .HasColumnType("INTEGER"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("EmailConfirmed") - .HasColumnType("INTEGER"); - - b.Property("LockoutEnabled") - .HasColumnType("INTEGER"); - - b.Property("LockoutEnd") - .HasColumnType("TEXT"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("PasswordHash") - .HasColumnType("TEXT"); - - b.Property("PhoneNumber") - .HasColumnType("TEXT"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("INTEGER"); - - b.Property("SecurityStamp") - .HasColumnType("TEXT"); - - b.Property("TwoFactorEnabled") - .HasColumnType("INTEGER"); - - b.Property("UserName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasDatabaseName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasDatabaseName("UserNameIndex"); - - b.ToTable("AspNetUsers"); - - b.HasDiscriminator("Discriminator").HasValue("IdentityUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClaimType") - .HasColumnType("TEXT"); - - b.Property("ClaimValue") - .HasColumnType("TEXT"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("TEXT"); - - b.Property("ProviderKey") - .HasColumnType("TEXT"); - - b.Property("ProviderDisplayName") - .HasColumnType("TEXT"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("RoleId") - .HasColumnType("TEXT"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("LoginProvider") - .HasColumnType("TEXT"); - - b.Property("Name") - .HasColumnType("TEXT"); - - b.Property("Value") - .HasColumnType("TEXT"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKey", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AllowedIPs") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("AllowedScopes") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("ApplicationId") - .HasColumnType("INTEGER"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("ExpiresAt") - .HasColumnType("TEXT"); - - b.Property("Key") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("KeyHash") - .IsRequired() - .HasMaxLength(512) - .HasColumnType("TEXT"); - - b.Property("KeyPrefix") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("LastUsedAt") - .HasColumnType("TEXT"); - - b.Property("RateLimitPerMinute") - .HasColumnType("INTEGER"); - - b.Property("RevokedAt") - .HasColumnType("TEXT"); - - b.Property("RevokedBy") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApplicationId"); - - b.HasIndex("ExpiresAt"); - - b.HasIndex("KeyHash") - .IsUnique(); - - b.ToTable("ApiKeys"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKeyUsage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiKeyId") - .HasColumnType("TEXT"); - - b.Property("ClientIP") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT"); - - b.Property("HttpMethod") - .HasColumnType("TEXT"); - - b.Property("RequestedOn") - .HasColumnType("TEXT"); - - b.Property("ResponseTimeMs") - .HasColumnType("INTEGER"); - - b.Property("StatusCode") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.ToTable("ApiKeyUsages"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApplication", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("IsActive") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("Applications"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XBannedDevice", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("BannedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("BannedDevices"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XToken", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.Property("Hash") - .HasColumnType("TEXT"); - - b.Property("Token") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UserSelectByParam") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Tokens"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XVerificationRequest", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.Property("LastTryOn") - .HasColumnType("TEXT"); - - b.Property("NumberOfTries") - .HasColumnType("INTEGER"); - - b.Property("RequestStr") - .HasColumnType("TEXT"); - - b.Property("VerificationCode") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("VerificationRequests"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XDevice", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Browser") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceType") - .HasColumnType("INTEGER"); - - b.Property("Os") - .HasColumnType("TEXT"); - - b.Property("OsVersion") - .HasColumnType("TEXT"); - - b.Property("UserAgent") - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("Devices"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollower", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DestId") - .HasColumnType("TEXT"); - - b.Property("State") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("DestId"); - - b.HasIndex("UserId"); - - b.ToTable("Followers"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollowing", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DestId") - .HasColumnType("TEXT"); - - b.Property("State") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("DestId"); - - b.HasIndex("UserId"); - - b.ToTable("Followings"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XProfileImage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreationDate") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Path") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Thumb") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("Avatars"); - }); - - modelBuilder.Entity("xIdentityModels.XUser", b => - { - b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); - - b.Property("Avatar") - .HasColumnType("TEXT"); - - b.Property("Bio") - .HasColumnType("TEXT"); - - b.Property("CoverImage") - .HasColumnType("TEXT"); - - b.Property("CreationDate") - .HasColumnType("TEXT"); - - b.Property("DateOfBirth") - .HasColumnType("TEXT"); - - b.Property("FirstName") - .IsRequired() - .HasMaxLength(50) - .HasColumnType("TEXT"); - - b.Property("Gender") - .HasColumnType("INTEGER"); - - b.Property("IsBanned") - .HasColumnType("INTEGER"); - - b.Property("IsEnable") - .HasColumnType("INTEGER"); - - b.Property("LastLogin") - .HasColumnType("TEXT"); - - b.Property("LastName") - .IsRequired() - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("OpenToSearch") - .HasColumnType("INTEGER"); - - b.HasDiscriminator().HasValue("XUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("xIdentityModels.XUser", null) - .WithMany("Roles") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKey", b => - { - b.HasOne("xIdentityModels.Models.XApplication", "Application") - .WithMany("ApiKeys") - .HasForeignKey("ApplicationId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Application"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XDevice", b => - { - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Devices") - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollower", b => - { - b.HasOne("xIdentityModels.XUser", "Dest") - .WithMany() - .HasForeignKey("DestId"); - - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Followers") - .HasForeignKey("UserId"); - - b.Navigation("Dest"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollowing", b => - { - b.HasOne("xIdentityModels.XUser", "Dest") - .WithMany() - .HasForeignKey("DestId"); - - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Followings") - .HasForeignKey("UserId"); - - b.Navigation("Dest"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XProfileImage", b => - { - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Avatars") - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApplication", b => - { - b.Navigation("ApiKeys"); - }); - - modelBuilder.Entity("xIdentityModels.XUser", b => - { - b.Navigation("Avatars"); - - b.Navigation("Devices"); - - b.Navigation("Followers"); - - b.Navigation("Followings"); - - b.Navigation("Roles"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Migrations\XIdentityDb\XIdentityDbContextModelSnapshot.cs - -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using xIds.DbContext; - -namespace xIds.Migrations.XIdentityDb -{ - [DbContext(typeof(XIdentityDbContext))] - partial class XIdentityDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.2"); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => - { - b.Property("Id") - .HasColumnType("TEXT"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("TEXT"); - - b.Property("Name") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("NormalizedName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName") - .IsUnique() - .HasDatabaseName("RoleNameIndex"); - - b.ToTable("AspNetRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClaimType") - .HasColumnType("TEXT"); - - b.Property("ClaimValue") - .HasColumnType("TEXT"); - - b.Property("RoleId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetRoleClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AccessFailedCount") - .HasColumnType("INTEGER"); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnType("TEXT"); - - b.Property("Discriminator") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("Email") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("EmailConfirmed") - .HasColumnType("INTEGER"); - - b.Property("LockoutEnabled") - .HasColumnType("INTEGER"); - - b.Property("LockoutEnd") - .HasColumnType("TEXT"); - - b.Property("NormalizedEmail") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("NormalizedUserName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.Property("PasswordHash") - .HasColumnType("TEXT"); - - b.Property("PhoneNumber") - .HasColumnType("TEXT"); - - b.Property("PhoneNumberConfirmed") - .HasColumnType("INTEGER"); - - b.Property("SecurityStamp") - .HasColumnType("TEXT"); - - b.Property("TwoFactorEnabled") - .HasColumnType("INTEGER"); - - b.Property("UserName") - .HasMaxLength(256) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedEmail") - .HasDatabaseName("EmailIndex"); - - b.HasIndex("NormalizedUserName") - .IsUnique() - .HasDatabaseName("UserNameIndex"); - - b.ToTable("AspNetUsers"); - - b.HasDiscriminator("Discriminator").HasValue("IdentityUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ClaimType") - .HasColumnType("TEXT"); - - b.Property("ClaimValue") - .HasColumnType("TEXT"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserClaims"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.Property("LoginProvider") - .HasColumnType("TEXT"); - - b.Property("ProviderKey") - .HasColumnType("TEXT"); - - b.Property("ProviderDisplayName") - .HasColumnType("TEXT"); - - b.Property("UserId") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("LoginProvider", "ProviderKey"); - - b.HasIndex("UserId"); - - b.ToTable("AspNetUserLogins"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("RoleId") - .HasColumnType("TEXT"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId"); - - b.ToTable("AspNetUserRoles"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.Property("UserId") - .HasColumnType("TEXT"); - - b.Property("LoginProvider") - .HasColumnType("TEXT"); - - b.Property("Name") - .HasColumnType("TEXT"); - - b.Property("Value") - .HasColumnType("TEXT"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AspNetUserTokens"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKey", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AllowedIPs") - .HasMaxLength(2000) - .HasColumnType("TEXT"); - - b.Property("AllowedScopes") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("ApplicationId") - .HasColumnType("INTEGER"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("ExpiresAt") - .HasColumnType("TEXT"); - - b.Property("Key") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("KeyHash") - .IsRequired() - .HasMaxLength(512) - .HasColumnType("TEXT"); - - b.Property("KeyPrefix") - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("LastUsedAt") - .HasColumnType("TEXT"); - - b.Property("RateLimitPerMinute") - .HasColumnType("INTEGER"); - - b.Property("RevokedAt") - .HasColumnType("TEXT"); - - b.Property("RevokedBy") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ApplicationId"); - - b.HasIndex("ExpiresAt"); - - b.HasIndex("KeyHash") - .IsUnique(); - - b.ToTable("ApiKeys"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKeyUsage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("ApiKeyId") - .HasColumnType("TEXT"); - - b.Property("ClientIP") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Endpoint") - .HasColumnType("TEXT"); - - b.Property("HttpMethod") - .HasColumnType("TEXT"); - - b.Property("RequestedOn") - .HasColumnType("TEXT"); - - b.Property("ResponseTimeMs") - .HasColumnType("INTEGER"); - - b.Property("StatusCode") - .HasColumnType("INTEGER"); - - b.HasKey("Id"); - - b.ToTable("ApiKeyUsages"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApplication", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreatedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Description") - .HasMaxLength(1000) - .HasColumnType("TEXT"); - - b.Property("IsActive") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("OwnerId") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UpdatedAt") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("Applications"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XBannedDevice", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("BannedOn") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("BannedDevices"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XToken", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.Property("Hash") - .HasColumnType("TEXT"); - - b.Property("Token") - .HasColumnType("TEXT"); - - b.Property("Type") - .HasColumnType("INTEGER"); - - b.Property("UserSelectByParam") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("Tokens"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XVerificationRequest", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceStr") - .HasColumnType("TEXT"); - - b.Property("LastTryOn") - .HasColumnType("TEXT"); - - b.Property("NumberOfTries") - .HasColumnType("INTEGER"); - - b.Property("RequestStr") - .HasColumnType("TEXT"); - - b.Property("VerificationCode") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("VerificationRequests"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XDevice", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Browser") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DeviceType") - .HasColumnType("INTEGER"); - - b.Property("Os") - .HasColumnType("TEXT"); - - b.Property("OsVersion") - .HasColumnType("TEXT"); - - b.Property("UserAgent") - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("Devices"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollower", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DestId") - .HasColumnType("TEXT"); - - b.Property("State") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("DestId"); - - b.HasIndex("UserId"); - - b.ToTable("Followers"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollowing", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("DestId") - .HasColumnType("TEXT"); - - b.Property("State") - .HasColumnType("INTEGER"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("DestId"); - - b.HasIndex("UserId"); - - b.ToTable("Followings"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XProfileImage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("CreationDate") - .HasColumnType("TEXT"); - - b.Property("Deleted") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Path") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("Thumb") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("ThumbPath") - .IsRequired() - .HasMaxLength(255) - .HasColumnType("TEXT"); - - b.Property("UserId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("Avatars"); - }); - - modelBuilder.Entity("xIdentityModels.XUser", b => - { - b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); - - b.Property("Avatar") - .HasColumnType("TEXT"); - - b.Property("Bio") - .HasColumnType("TEXT"); - - b.Property("CoverImage") - .HasColumnType("TEXT"); - - b.Property("CreationDate") - .HasColumnType("TEXT"); - - b.Property("DateOfBirth") - .HasColumnType("TEXT"); - - b.Property("FirstName") - .IsRequired() - .HasMaxLength(50) - .HasColumnType("TEXT"); - - b.Property("Gender") - .HasColumnType("INTEGER"); - - b.Property("IsBanned") - .HasColumnType("INTEGER"); - - b.Property("IsEnable") - .HasColumnType("INTEGER"); - - b.Property("LastLogin") - .HasColumnType("TEXT"); - - b.Property("LastName") - .IsRequired() - .HasMaxLength(100) - .HasColumnType("TEXT"); - - b.Property("OpenToSearch") - .HasColumnType("INTEGER"); - - b.HasDiscriminator().HasValue("XUser"); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("xIdentityModels.XUser", null) - .WithMany("Roles") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => - { - b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) - .WithMany() - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApiKey", b => - { - b.HasOne("xIdentityModels.Models.XApplication", "Application") - .WithMany("ApiKeys") - .HasForeignKey("ApplicationId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Application"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XDevice", b => - { - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Devices") - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollower", b => - { - b.HasOne("xIdentityModels.XUser", "Dest") - .WithMany() - .HasForeignKey("DestId"); - - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Followers") - .HasForeignKey("UserId"); - - b.Navigation("Dest"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XFriendshipFollowing", b => - { - b.HasOne("xIdentityModels.XUser", "Dest") - .WithMany() - .HasForeignKey("DestId"); - - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Followings") - .HasForeignKey("UserId"); - - b.Navigation("Dest"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Navigations.XProfileImage", b => - { - b.HasOne("xIdentityModels.XUser", "User") - .WithMany("Avatars") - .HasForeignKey("UserId"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("xIdentityModels.Models.XApplication", b => - { - b.Navigation("ApiKeys"); - }); - - modelBuilder.Entity("xIdentityModels.XUser", b => - { - b.Navigation("Avatars"); - - b.Navigation("Devices"); - - b.Navigation("Followers"); - - b.Navigation("Followings"); - - b.Navigation("Roles"); - }); -#pragma warning restore 612, 618 - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Models\XDbInfo.cs - -using System; -using xIds.Constants; - -namespace xIds.Models -{ - public class XDbInfo - { - private string _migrationAssembly; - public XDbProviders ProviderType { get; set; } - public string MigrationsAssembly - { - get - { - return _migrationAssembly; - } - - set - { - // - _migrationAssembly = value; - - // - OptionsBuilder = b => - { - b.MigrationsAssembly(value); - }; - } - } - public Action OptionsBuilder { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Models\XDbSeedDescriptor.cs - -using System.Collections.Generic; -using IdentityServer4.Models; -using xIdentityModels.Descriptors; - -namespace xIds.Models -{ - /// - /// the resource Descriptors for Using on DbSeed - /// - public class XDbSeedDescriptor - { - public bool UpdateExists { get; set; } - public ICollection ApiScopes { get; set; } - public ICollection ApiResources { get; set; } - public ICollection IdentityResources { get; set; } - public ICollection Clients { get; set; } - public ICollection Users { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApiKeyAccessAttribute.cs - -using System; -using xIds.Interfaces; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using xIdentityModels.Constants; -using xIdentityService.Constants; -using xIdentityModels.Extensions; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.DependencyInjection; - -namespace xIds.Providers -{ - [AttributeUsage( - AttributeTargets.Class | AttributeTargets.Method, - AllowMultiple = false, - Inherited = true - )] - public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter - { - /// - /// Optional allowed scopes. If empty, no scope enforcement. - /// - public XApiKeyScope[] Scopes { get; set; } - - public XApiKeyAccessAttribute( - XApiKeyScope[] scopes = null - ) - { - // - if (!scopes.HasChild()) - { - scopes = [XApiKeyScope.Read]; - } - - // - Scopes = scopes; - } - - /// - /// Authorization Filtering ... - /// - /// - public void OnAuthorization(AuthorizationFilterContext context) - { - Task.FromResult(OnAuthorizationAsync(context)); - } - - /// - /// Handle Authorization Filtering Using Tasks ... - /// - /// - /// - /// - private async Task OnAuthorizationAsync( - AuthorizationFilterContext context, - CancellationToken cancellationToken = default - ) - { - // - // Access HttpContext ... - var http = context.HttpContext; - var error = XException.NotAuthorized.ToXError(); - var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue(); - - // - try - { - // - // Obtain the endpoint currently being executed - var endpoint = http.GetEndpoint(); - - // - // Retrieve the application provider from DI ... - var applicationProvider = http.RequestServices - .GetService(); - if (applicationProvider.IsNull()) - { - // - error.Message = "Api Key Service not Registered ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Checking Header ... - var apiKeyHeader = XHeader.ApiKey.GetStringValue(); - if (!http.Request.Headers.ContainsKey(apiKeyHeader)) - { - // - error.Message = "ApiKey not Exists ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Extract ApiKey from Header ... - var apiKey = http.Request.Headers[apiKeyHeader].ToString(); - if (apiKey.IsNullOrEmpty()) - { - // - error.Message = "ApiKey not Provided ..."; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Extract Client IP ... - var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString(); - var scopes = - !Scopes.HasChild() - ? string.Empty - : Scopes.ToListString(); - - // - // Validating ApiKey ... - var validationResult = await applicationProvider - .ValidateApiKey( - apiKey: apiKey, - userInfo: null, - clientIP: clientIP, - requiredScope: scopes, - cancellationToken: cancellationToken - ); - if (validationResult.Errors.HasChild()) - { - // - var message = validationResult.Errors.ToListString(','); - error.Message = message; - context.Result = new UnauthorizedObjectResult(error); - return; - } - - // - // Creating Claims ... - var claims = validationResult.ToXClaims(); - - // - // Create Principal and Ticket ... - var identity = new ClaimsIdentity(claims, apiKeyAuthentication); - var principal = new ClaimsPrincipal(identity); - - // - http.User = principal; - } - catch - { - // - error.Message = "ApiKey authorization failed ..."; - context.Result = new UnauthorizedObjectResult(error); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using xIds.DbContext; -using xIds.Interfaces; -using xCommons.Extensions; -using xIds.Configurations; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using IdentityServer4.Extensions; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.Extensions.Caching.Memory; -using AutoMapper; - -namespace xIds.Providers -{ - /// - /// a Service For Manage Security Applications and also Api Key(s) ... - /// - public partial class XApplicationProvider : IXApplicationProvider - { - private readonly IMemoryCache cache; - private readonly string permittedRole; - private readonly XIdentityDbContext dbContext; - private readonly IXIdentityManager identityManager; - private readonly XDataServiceConfiguration configuration; - private readonly XApiKeyConfiguration apiKeyConfiguration; - private readonly Action mapperConfigurationExp; - - public XApplicationProvider( - IMemoryCache cache, - XIdentityDbContext dbContext, - IXIdentityManager identityManager, - XDataServiceConfiguration configuration, - XApiKeyConfiguration apiKeyConfiguration, - string permittedRole = "admin" - ) - { - // - this.cache = cache; - this.dbContext = dbContext; - this.permittedRole = permittedRole; - this.configuration = configuration; - this.identityManager = identityManager; - this.apiKeyConfiguration = apiKeyConfiguration; - - // - // Configure Mapper Options ... - mapperConfigurationExp = cfg => - { - // - cfg.CreateMap() - .ReverseMap(); - - // - cfg.CreateMap() - .ReverseMap(); - - // - cfg.CreateMap() - .ReverseMap(); - }; - } - - /// - /// Retrieve Owner ... - /// - /// - /// - public async Task GetOwner(string ownerId) - { - // - if (ownerId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var user = await identityManager.GetUserAsync(ownerId); - XPersonDto result = user.ToXPerson(); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - - /// - /// Check Specifed User Info is Owned for Action or not ... - /// - /// - /// - /// - public bool IsOwned( - XApplication source, - XUserClaimsInfoDto userInfo = null - ) - { - // - var result = - !source.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - (userInfo.UserId == source.OwnerId || - userInfo.Roles - .Any(r => - r.ToNormalString() == permittedRole.ToNormalString())); - - // - return result; - } - - /// - /// Check Specifed User Info is Owned for Action or not ... - /// - /// - /// - /// - public bool IsOwned( - XApplicationDto source, - XUserClaimsInfoDto userInfo = null - ) - { - // - var result = - !source.IsNullOrDefault() && - !userInfo.IsNullOrDefault() && - (userInfo.UserId == source.OwnerId || - userInfo.Roles - .Any(r => - r.ToNormalString() == permittedRole.ToNormalString())); - - // - return result; - } - - /// - /// Normalize an XQuery based on Data Service Configurations ... - /// - /// - /// - /// - public XQuery NormalizeQuery( - XQuery source, - XDataServiceConfiguration configuration // - ) - { - // - if (source.IsNull()) - { - source = new XQuery(); - } - - // - // Page Size Normalization ... - if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize; - } - if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize) - { - source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize; - } - - // - return source; - } - - /// - /// Prepare a Queryable of Items ... - /// - /// - /// - /// - /// - public IQueryable GetApplicationsQeryable( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Global Result ... - var result = dbContext.Applications.AsQueryable(); - - // - // Handle Filtering ... - if (!predicate.IsNull()) - { - result = result.Where(predicate); - } - - // - // Handle Including ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - // Handle Ordering ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - // Return result ... - return result; - } - - /// - /// Prepare a Queryable of Items ... - /// - /// - /// - /// - /// - public IQueryable GetApiKeysQeryable( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Global Result ... - var result = dbContext.ApiKeys.AsQueryable(); - - // - // Handle Filtering ... - if (!predicate.IsNull()) - { - result = result.Where(predicate); - } - - // - // Handle Including ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - // Handle Ordering ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - // Return result ... - return result; - } - - /// - /// Prepare a Queryable of Items ... - /// - /// - /// - /// - /// - public IQueryable GetApiKeyUsagesQeryable( - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null - ) - { - // - // Global Result ... - var result = dbContext.ApiKeyUsages.AsQueryable(); - - // - // Handle Filtering ... - if (!predicate.IsNull()) - { - result = result.Where(predicate); - } - - // - // Handle Including ... - if (!includeBuilder.IsNull()) - { - result = includeBuilder(result); - } - - // - // Handle Ordering ... - if (!orderBuilder.IsNull()) - { - result = orderBuilder(result); - } - - // - // Return result ... - return result; - } - - /// - /// Handle Rate Limit Checking ... - /// - /// - /// - /// - private bool CheckRateLimit( - Guid apiKeyId, - int limitPerMinute - ) - { - // - var cacheKey = $"ratelimit:{apiKeyId}"; - var currentCount = cache.GetOrCreate( - cacheKey, - entry => - { - // - entry.SlidingExpiration = TimeSpan.FromMinutes(1); - return 0; - } - ); - - // - if (currentCount >= limitPerMinute) - { - return false; - } - - // - cache.Set( - cacheKey, - currentCount + 1, - TimeSpan.FromMinutes(1) - ); - - // - return true; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager.cs - -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using xCommons.Extensions; -using xCommons.Providers; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Configurations; -using xIdentityModels.Constants; -using xIdentityModels.Models; -using xMessageService.Interfaces; -using xStorageService.Interfaces; -using xIds.Configurations; -using xIds.DbContext; -using xIds.Interfaces; - -namespace xIds.Providers -{ - public partial class XIdentityManager : IXIdentityManager - { - // - private JsonSerializerSettings jsonSerializerSettings; - - // - public XIdentityDbContext DbContext { get; } - public UserManager UserManager { get; } - public IXIdentityHelper IdentityHelper { get; } - public ILogger Logger { get; } - public IXMessageProvider MessageProvider { get; } - public IXStorageProvider StorageProvider { get; } - public SignInManager SignInManager { get; } - public IXSecurityProvider SecurityProvider { get; } - public XIdentityConfiguration Configuration { get; } - public RoleManager RoleManager { get; } - public XValidationProvider ValidationProvider { get; } - public XDataServiceConfiguration DataConfiguration { get; } - public IXIdentityMessageProvider IdentityMessageProvider { get; } - public XIdentityResourceConfiguration IdentityResourceConfiguration { get; } - - public XIdentityManager( - XIdentityDbContext dbContext, - UserManager userManager, - IXIdentityHelper identityHelper, - ILogger logger, - IXMessageProvider messageProvider, - IXStorageProvider storageProvider, - SignInManager signInManager, - IXSecurityProvider securityProvider, - XIdentityConfiguration configuration, - RoleManager roleManager, - XValidationProvider validationProvider, - XDataServiceConfiguration dataConfiguration, - IXIdentityMessageProvider identityMessageProvider, - XIdentityResourceConfiguration identityResourceConfiguration - ) - { - // - Logger = logger; - DbContext = dbContext; - RoleManager = roleManager; - UserManager = userManager; - SignInManager = signInManager; - SecurityProvider = securityProvider; - Configuration = configuration; - IdentityHelper = identityHelper; - MessageProvider = messageProvider; - StorageProvider = storageProvider; - DataConfiguration = dataConfiguration; - ValidationProvider = validationProvider; - IdentityMessageProvider = identityMessageProvider; - IdentityResourceConfiguration = identityResourceConfiguration; - - // - this.jsonSerializerSettings = new JsonSerializerSettings - { - ContractResolver = new CamelCasePropertyNamesContractResolver() - }; - } - - // - #region Class Getter (s) Methods ... - /// - /// Retrieve User DB Set - /// - /// specifies returned object contains all Navigation Properties or not, default is false - /// - public IQueryable GetUsersDbSet( - bool containDetails = false - ) - { - // - var dbSet = containDetails ? GetUsersFullDbSet() : - UserManager.Users; - return dbSet; - } - - /// - /// Retrieve User Db Set Full Navigation Properties - /// - /// - /// - public IQueryable GetUsersFullDbSet(bool enableTracking = false) - { - // - var dbSet = UserManager.Users - .Include(u => u.Roles) - .Include(u => u.Devices) - .Include(u => u.Followers) - .Include(u => u.Followings) - .Include(u => u.Avatars); - - // - return dbSet.AsSplitQuery(); - } - #endregion - - // - #region Tools ... - /// - /// Get User SelectBy Param - /// - /// - /// - /// - /// - public string GetUserSelectByParam( - XActionRequest model, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(model); - - // - var id = model.UserId; - var userName = model.UserName; - var email = model.Email; - var phoneNumber = model.MobileNumber; - - // - if (excludes != null) - { - // - if (excludes.Contains(XUserSelectBy.ID)) - { - id = null; - } - if (excludes.Contains(XUserSelectBy.Email)) - { - email = null; - } - if (excludes.Contains(XUserSelectBy.MobileNumber)) - { - phoneNumber = null; - } - if (excludes.Contains(XUserSelectBy.Username)) - { - userName = null; - } - } - - var selectByParam = - id.IsNullOrEmpty() ? - userName.IsNullOrEmpty() ? - email.IsNullOrEmpty() ? - phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; - - // - // Check result ... - if (forceNotNull && - selectByParam.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - return selectByParam; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityMessageProvider.cs - -using System.Linq; -using Microsoft.Extensions.Logging; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Configurations; -using xIds.Constants; -using xIds.Interfaces; - -namespace xIds.Providers -{ - public class XIdentityMessageProvider : IXIdentityMessageProvider - { - // - public string InviteMsg { get; set; } - public string RegistrationApproveMsg { get; set; } - public string RegisteredMsg { get; set; } - public string VerificationCodeMsg { get; set; } - public string ChangePasswordMsg { get; set; } - public string PasswordChangedMsg { get; set; } - public string NewDeviceLoggedInMsg { get; set; } - - private readonly ILogger logger; - private readonly XIdentityConfiguration identityConfiguration; - - public XIdentityMessageProvider( - ILogger logger, - XIdentityConfiguration identityConfiguration - ) - { - this.logger = logger; - this.identityConfiguration = identityConfiguration; - } - - /// - /// Determine All things is Ready or Not - /// - /// - public bool IsReady() - { - return !InviteMsg.IsNullOrEmpty() && - !RegistrationApproveMsg.IsNullOrEmpty() && - !RegisteredMsg.IsNullOrEmpty() && - !VerificationCodeMsg.IsNullOrEmpty() && - !ChangePasswordMsg.IsNullOrEmpty() && - !PasswordChangedMsg.IsNullOrEmpty() && - !NewDeviceLoggedInMsg.IsNullOrEmpty(); - } - - /// - /// Retrieve a Translated Value Based on Given Lang - /// - /// - /// - /// - private string GetStringResource(string resourceTitle, string lang) - { - // - var item = identityConfiguration.IdentityMessages - .FirstOrDefault(sr => - sr.Language.ToNormalString() == lang.ToNormalString() && - sr.ResourceTitle.ToNormalString() == resourceTitle.ToNormalString()); - // - if (item == null) - { - return null; - } - - // - return item.TranslatedValue; - } - - /// - /// Prepare Helper Class and Fill Messages - /// with Specific Language - /// - /// - public void PrepareMessages(string lang) - { - // - InviteMsg = GetStringResource(IdentityMessagesKeys.InviteMsg, lang); - RegisteredMsg = GetStringResource(IdentityMessagesKeys.RegisteredMsg, lang); - ChangePasswordMsg = GetStringResource(IdentityMessagesKeys.ChangePasswordMsg, lang); - PasswordChangedMsg = GetStringResource(IdentityMessagesKeys.PasswordChangedMsg, lang); - VerificationCodeMsg = GetStringResource(IdentityMessagesKeys.VerificationCodeMsg, lang); - NewDeviceLoggedInMsg = GetStringResource(IdentityMessagesKeys.NewDeviceLoggedInMsg, lang); - RegistrationApproveMsg = GetStringResource(IdentityMessagesKeys.RegistrationApproveMsg, lang); - - // - if (!IsReady()) - { - XException.InvalidArgs.Throw(); - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityProfileService.cs - -using System.Linq; -using System.Threading.Tasks; -using IdentityServer4.Extensions; -using IdentityServer4.Models; -using IdentityServer4.Services; -using Microsoft.AspNetCore.Identity; -using xCommons.Extensions; -using xIdentityModels; -using xIds.Interfaces; - -namespace xIds.Providers -{ - public class XIdentityProfileService : IProfileService - { - private readonly IXIdentityManager identityManager; - private readonly IUserClaimsPrincipalFactory userClaimsPrincipalFacotry; - - public XIdentityProfileService( - IXIdentityManager identityManager, - IUserClaimsPrincipalFactory userClaimsPrincipalFacotry - ) - { - this.identityManager = identityManager; - this.userClaimsPrincipalFacotry = userClaimsPrincipalFacotry; - } - - public async Task GetProfileDataAsync(ProfileDataRequestContext context) - { - // - var sub = context.Subject.GetSubjectId(); - var user = await identityManager.GetUserAsync(sub, true); - var principal = await userClaimsPrincipalFacotry.CreateAsync(user); - - // - var claims = principal.Claims.ToList(); - - // - context.IssuedClaims = claims; - } - - public async Task IsActiveAsync(IsActiveContext context) - { - // - var sub = context.Subject.GetSubjectId(); - var user = await identityManager.GetUserAsync(sub); - - // - context.IsActive = !user.IsNull() && user.IsEnable && !user.IsBanned; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XSecurityProvider.cs - -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using xCommons.Extensions; -using xCommons.Providers; -using xIds.Configurations; -using xIds.Interfaces; - -namespace xIds.Providers -{ - public class XSecurityProvider : IXSecurityProvider - { - // - #region Props ... - private readonly string secretKey; - private readonly byte[] iv; - private readonly byte[] key; - private readonly XValidationProvider validationProvider; - #endregion - - // - #region Constructor ... - public XSecurityProvider( - XIdentityResourceConfiguration identityConfiguration, - XValidationProvider validationProvider - ) - { - // - this.secretKey = identityConfiguration.XRevisionSecretKey.ToMd5String(); - this.validationProvider = validationProvider; - - // - var ivBytes = new byte[16]; - var keyBytes = new byte[32]; - var secretBytes = Encoding.UTF8.GetBytes(this.secretKey); - - // - Array.Copy( - secretBytes, - ivBytes, - secretBytes.Length < ivBytes.Length ? - secretBytes.Length : - ivBytes.Length - ); - this.iv = ivBytes; - - // - Array.Copy( - secretBytes, - keyBytes, - secretBytes.Length < keyBytes.Length ? - secretBytes.Length : - keyBytes.Length - ); - this.key = keyBytes; - - // Encoding.UTF8.GetBytes (this.secretKey); - } - #endregion - - // - #region Actions ... - public string Encrypt(string plainText) - { - // - validationProvider.NotEmpty(plainText); - - // - var textBytes = Encoding.UTF8.GetBytes(plainText); - var result = EncryptFromBytes(textBytes); - - // - return result; - } - - public string Decrypt(string cipherText) - { - // - validationProvider.NotEmpty(cipherText); - - // - var cipherBytes = Convert.FromBase64String(cipherText); - var result = DecryptFromBytes(cipherBytes); - - // - return result; - } - - public string EncryptFromBytes(byte[] textBytes) - { - // - // Validate Args ... - validationProvider.NotNull(textBytes); - - // Declare the string used to hold - // the decrypted text. - byte[] encryptedBytes = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged()) - { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // - using (var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)) - { - encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length); - } - } - - // - return Convert.ToBase64String(encryptedBytes); - } - - public string DecryptFromBytes(byte[] cipherBytes) - { - // - // Validate Args ... - validationProvider.NotNull(cipherBytes); - - // Declare the string used to hold - // the decrypted text. - string plaintext = null; - - // Create an RijndaelManaged object - // with the specified key and IV. - using (var rijAlg = new RijndaelManaged()) - { - //Settings - rijAlg.Mode = CipherMode.CBC; - rijAlg.Padding = PaddingMode.PKCS7; - // rijAlg.FeedbackSize = 128; - - rijAlg.Key = key; - rijAlg.IV = iv; - - // Create a decrytor to perform the stream transform. - var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); - - // Create the streams used for decryption. - using (var msDecrypt = new MemoryStream(cipherBytes)) - { - using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) - { - using (var srDecrypt = new StreamReader(csDecrypt)) - { - // Read the decrypted bytes from the decrypting stream - // and place them in a string. - plaintext = srDecrypt.ReadToEnd(); - } - } - } - } - - // - return plaintext; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider\XApplicationProvider+ApiKey.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xDataService.Extensions; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace xIds.Providers -{ - public partial class XApplicationProvider - { - // - #region ApiKey ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task AddApiKeyAsync( - XApiKeyDto item, - string apiKey = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!item.IsValidForAdd()) - { - XException.InvalidArgs.Throw(); - } - - // - // Permission ... - if (userInfo.IsNullOrDefault()) - { - XException.NotAllowed.Throw(); - } - - // - // Check Application Exists ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: item.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - // Check COunt of API Keys ... - var appApiKeysCount = await dbContext.ApiKeys.CountAsync( - cancellationToken: cancellationToken, - predicate: x => x.ApplicationId == item.ApplicationId - ); - if (appApiKeysCount >= apiKeyConfiguration.MaxKeysPerApplication) - { - XException.NotAllowed.Throw(); - } - - // - item.CreatedOn = DateTime.UtcNow; - - // - var entity = item.MapConvert(mapperConfigurationExp); - if (!apiKey.IsNullOrEmpty()) - { - entity.Key = apiKey; - } - - var entry = await dbContext.ApiKeys.AddAsync( - entity: entity, - cancellationToken: cancellationToken - ); - var changes = await dbContext.SaveChangesAsync(cancellationToken); - - // - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApiKeyAsync( - Guid id, - XApiKeyDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - id != item.Id || - id.IsDefaultGuid() || - !item.IsValidForAdd() || - item.IsNullOrDefault() || - userInfo.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Entity ... - var exists = await dbContext.ApiKeys - .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: item.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - // Update Data on Exists Entity ... - exists = exists.UpdateData( - updateWith: item, - propertyWhiteList: [], - propertyBlackList: [ - nameof(XApiKey.Id), - nameof(XApiKey.KeyHash), - nameof(XApiKey.KeyPrefix), - nameof(XApiKey.CreatedOn), - nameof(XApiKey.Application), - nameof(XApiKey.ApplicationId), - ] - ); - - // - var entry = dbContext.ApiKeys.Attach(exists); - entry.State = EntityState.Modified; - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task RemoveApiKeyAsync( - Guid id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - id.IsDefaultGuid() || - userInfo.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Entity ... - var exists = await dbContext.ApiKeys - .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: exists.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - EntityEntry entry = null; - if (softDelete) - { - // - exists.Deleted = true; - entry = dbContext.ApiKeys.Update(exists); - } - else - { - entry = dbContext.ApiKeys.Remove(exists); - } - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNull() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - public async Task GetApiKeyAsync( - Guid id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (id.IsDefaultGuid() || - userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Condition ... - Expression> predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - - // - // Retrieve Queryable ... - var queryable = GetApiKeysQeryable( - orderBuilder: null, - predicate: predicate, - includeBuilder: includeBuilder - ); - - // - var entity = await queryable.FirstOrDefaultAsync( - predicate: x => x.Id == id, - cancellationToken: cancellationToken - ); - if (entity.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: entity.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - public async Task> GetAllApiKeyAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var applications = await GetAllApplicationAsync( - userInfo: userInfo, - orderBuilder: null, - includeBuilder: null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - applications = applications.Where(a => IsOwned(a, userInfo)); - var appIds = applications - .Select(a => a.Id) - .ToList(); - - // - Expression> predicate = x => - appIds.Contains(x.ApplicationId) && - !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeysQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var items = await queryable.ToListAsync(cancellationToken); - var result = await EnrichRangeAsync( - sources: items, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - public async IAsyncEnumerable GetAllApiKeyAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - var applications = await GetAllApplicationAsync( - userInfo: userInfo, - orderBuilder: null, - includeBuilder: null, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - applications = applications.Where(a => IsOwned(a, userInfo)); - var appIds = applications - .Select(a => a.Id) - .ToList(); - - // - Expression> predicate = x => - appIds.Contains(x.ApplicationId) && - !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeysQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var enumerator = queryable.AsAsyncEnumerable(); - await foreach (var item in enumerator) - { - // - // Handle Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var dto = await EnrichAsync( - source: item, - cancellationToken: cancellationToken - ); - - yield return dto; - } - } - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task FindOneApiKeyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeysQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entity = (await queryable - .ToListAsync(cancellationToken)) - .FirstOrDefault(x => predicate.Compile()(x)); - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: entity.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyApiKeyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeysQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entities = (await queryable - .ToListAsync(cancellationToken)) - .Where(x => predicate.Compile()(x)) - .ToList(); - - // - var appIds = entities - .Select(k => k.ApplicationId) - .ToList(); - - // - foreach (var appId in appIds) - { - // - // Permission Checking ... - var application = await GetApplicationAsync( - id: appId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if ( - application.IsNullOrDefault() || - !IsOwned(application, userInfo)) - { - entities = [.. entities.Where(e => e.ApplicationId != appId)]; - } - } - - // - var result = await EnrichRangeAsync( - sources: entities, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryApiKeyAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize Query ... - query = NormalizeQuery(query, configuration); - - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeysQeryable( - predicate: _predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var items = (await queryable - .ToListAsync(cancellationToken)) - .Where(x => predicate.Compile()(x)); - - // - var appIds = items - .Select(k => k.ApplicationId) - .ToList(); - - // - foreach (var appId in appIds) - { - // - // Permission Checking ... - var application = await GetApplicationAsync( - id: appId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if ( - application.IsNullOrDefault() || - !IsOwned(application, userInfo)) - { - items = [.. items.Where(e => e.ApplicationId != appId)]; - } - } - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .AsEnumerable() - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0 - ) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - var resultItems = await EnrichRangeAsync( - sources: items, - cancellationToken: cancellationToken - ); - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = [.. resultItems], - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider\XApplicationProvider+ApiKeyUsage.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xDataService.Extensions; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace xIds.Providers -{ - public partial class XApplicationProvider - { - // - #region ApiKeyUsage ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - public async Task AddApiKeyUsageAsync( - XApiKeyUsageDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!item.IsValidForAdd()) - { - XException.InvalidArgs.Throw(); - } - - // - // Check ApiKey Exists ... - var apiKey = await dbContext.ApiKeys - .FirstOrDefaultAsync(x => x.Id == item.ApiKeyId); - if (apiKey.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Check apiKey Activation ... - if (!apiKey.IsActive()) - { - XException.NotAllowed.Throw(); - } - - // - var entity = item.MapConvert(); - var entry = await dbContext.ApiKeyUsages.AddAsync( - entity: entity, - cancellationToken: cancellationToken - ); - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApiKeyUsageAsync( - long id, - XApiKeyUsageDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - id <= 0 || - id != item.Id || - !item.IsValidForAdd() || - item.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Item Exists ... - var exists = dbContext.ApiKeyUsages.FirstOrDefault(x => x.Id == id); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Update Data on Exists Entity ... - exists = exists.UpdateData( - updateWith: item, - propertyWhiteList: [], - propertyBlackList: [ - nameof(XApiKeyUsage.Id), - nameof(XApiKeyUsage.ApiKeyId), - nameof(XApiKeyUsage.ResponseTimeMs), - ] - ); - - // - var entry = dbContext.ApiKeyUsages.Attach(exists); - entry.State = EntityState.Modified; - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task RemoveApiKeyUsageAsync( - long id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Entity ... - var exists = await dbContext.ApiKeyUsages - .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - EntityEntry entry = null; - if (softDelete) - { - // - exists.Deleted = true; - entry = dbContext.ApiKeyUsages.Update(exists); - } - else - { - entry = dbContext.ApiKeyUsages.Remove(exists); - } - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNull() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - public async Task GetApiKeyUsageAsync( - long id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (id <= 0) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Condition ... - Expression> predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - - // - // Retrieve Queryable ... - var queryable = GetApiKeyUsagesQeryable( - orderBuilder: null, - predicate: predicate, - includeBuilder: includeBuilder - ); - - // - var entity = await queryable.FirstOrDefaultAsync( - predicate: x => x.Id == id, - cancellationToken: cancellationToken - ); - if (entity.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - public async Task> GetAllApiKeyUsageAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeyUsagesQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var items = await queryable.ToListAsync(cancellationToken); - var result = await EnrichRangeAsync( - sources: items, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - public async IAsyncEnumerable GetAllApiKeyUsageAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - Expression> predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeyUsagesQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var enumerator = queryable.AsAsyncEnumerable(); - await foreach (var item in enumerator) - { - // - // Handle Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var dto = await EnrichAsync( - source: item, - cancellationToken: cancellationToken - ); - - yield return dto; - } - } - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task FindOneApiKeyUsageAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeyUsagesQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entity = (await queryable - .ToListAsync(cancellationToken)) - .FirstOrDefault(x => predicate.Compile()(x)); - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyApiKeyUsageAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - var queryable = GetApiKeyUsagesQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entities = (await queryable - .ToListAsync(cancellationToken)) - .Where(x => predicate.Compile()(x)) - .ToList(); - - // - var result = await EnrichRangeAsync( - sources: entities, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryApiKeyUsageAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = NormalizeQuery(query, configuration); - - // - var items = await GetAllApiKeyUsageAsync( - userInfo: userInfo, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0 - ) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = [.. items], - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider\XApplicationProvider+Application.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xDataService.Extensions; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using xIdentityHelper.Extensions; -using Microsoft.EntityFrameworkCore; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace xIds.Providers -{ - public partial class XApplicationProvider - { - // - #region Application ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - public async Task AddApplicationAsync( - XApplicationDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!item.IsValidForAdd()) - { - XException.InvalidArgs.Throw(); - } - - // - // Permission ... - if (userInfo.IsNullOrDefault()) - { - XException.NotAllowed.Throw(); - } - - // - item.OwnerId = userInfo.UserId; - item.CreatedOn = DateTime.UtcNow; - - // - var entity = item.MapConvert(); - if (entity.Id.IsValidIntId()) - { - entity.Id = -1; - } - - // - var entry = await dbContext.Applications.AddAsync( - entity: entity, - cancellationToken: cancellationToken - ); - var changes = await dbContext.SaveChangesAsync(cancellationToken); - - // - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Update Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task UpdateApplicationAsync( - int id, - XApplicationDto item, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - id != item.Id || - !id.IsValidIntId() || - item.IsNullOrDefault() || - userInfo.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Entity ... - var exists = await dbContext.Applications - .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - if (!IsOwned(exists, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - item.UpdatedAt = DateTime.UtcNow; - - // - // Update Data on Exists Entity ... - exists = exists.UpdateData( - updateWith: item, - propertyWhiteList: [], - propertyBlackList: [ - nameof(XApiKey.Id), - nameof(XApplication.ApiKeys), - nameof(XApplication.CreatedOn), - ] - ); - - // - var entry = dbContext.Applications.Attach(exists); - entry.State = EntityState.Modified; - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNullOrDefault() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Remove Specified Item ... - /// - /// - /// - /// - /// - /// - public async Task RemoveApplicationAsync( - int id, - bool softDelete = true, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - !id.IsValidIntId() || - userInfo.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Entity ... - var exists = await dbContext.Applications - .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); - if (exists.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - if (!IsOwned(exists, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - EntityEntry entry = null; - if (softDelete) - { - // - exists.Deleted = true; - entry = dbContext.Applications.Update(exists); - } - else - { - entry = dbContext.Applications.Remove(exists); - } - - // - var changes = await dbContext.SaveChangesAsync(cancellationToken); - if ( - changes <= 0 || - entry.IsNull() || - entry.Entity.IsNull() - ) - { - XException.ActionFailed.Throw(); - } - - // - var result = await EnrichAsync( - source: entry.Entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve an Item by Providing it's ID ... - /// - /// - /// - /// - /// - /// - /// - public async Task GetApplicationAsync( - int id, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (!id.IsValidIntId() || - userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Condition ... - Expression> predicate = x => - x.OwnerId != userInfo.UserId || - !ignoreSoftDeleteds || !x.Deleted; - if (userInfo.IsAdmin()) - { - // - predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - } - - // - // Retrieve Queryable ... - var queryable = GetApplicationsQeryable( - orderBuilder: null, - predicate: predicate, - includeBuilder: includeBuilder - ); - - // - var entity = await queryable.FirstOrDefaultAsync( - predicate: x => x.Id == id, - cancellationToken: cancellationToken - ); - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve all Items ... - /// - /// - /// - /// - /// - /// - /// - public async Task> GetAllApplicationAsync( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Condition ... - Expression> predicate = x => - x.OwnerId == userInfo.UserId && - (!ignoreSoftDeleteds || !x.Deleted); - if (userInfo.IsAdmin()) - { - // - predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - } - - // - // Retrieve Queryable ... - var queryable = GetApplicationsQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var items = await queryable.ToListAsync(cancellationToken); - var result = await EnrichRangeAsync( - sources: items, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Retrieve all Items as Async Enumerable ... - /// - /// - /// - /// - /// - /// - /// - public async IAsyncEnumerable GetAllApplicationAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Condition ... - Expression> predicate = x => - x.OwnerId == userInfo.UserId && - (!ignoreSoftDeleteds || !x.Deleted); - if (userInfo.IsAdmin()) - { - // - predicate = x => - !ignoreSoftDeleteds || !x.Deleted; - } - - // - // Retrieve Queryable ... - var queryable = GetApplicationsQeryable( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder - ); - - // - var enumerator = queryable.AsAsyncEnumerable(); - await foreach (var item in enumerator) - { - // - // Handle Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - var dto = await EnrichAsync( - source: item, - cancellationToken: cancellationToken - ); - - yield return dto; - } - } - - /// - /// Find an Item By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task FindOneApplicationAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - if (!userInfo.IsAdmin()) - { - _predicate = x => - x.OwnerId == userInfo.UserId && - (!ignoreSoftDeleteds || !x.Deleted); - } - - // - var queryable = GetApplicationsQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entity = (await queryable - .ToListAsync(cancellationToken)) - .FirstOrDefault(x => predicate.Compile()(x)); - - // - var result = await EnrichAsync( - source: entity, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Find a Collection of Items By Providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyApplicationAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - Expression> _predicate = x => !ignoreSoftDeleteds || !x.Deleted; - if (!userInfo.IsAdmin()) - { - _predicate = x => - x.OwnerId == userInfo.UserId && - (!ignoreSoftDeleteds || !x.Deleted); - } - - // - var queryable = GetApplicationsQeryable( - orderBuilder: null, - predicate: _predicate, - includeBuilder: includeBuilder - ); - - // - var entities = (await queryable - .ToListAsync(cancellationToken)) - .Where(x => predicate.Compile()(x)); - - // - var result = await EnrichRangeAsync( - sources: entities, - cancellationToken: cancellationToken - ); - return result; - } - - /// - /// Retrieve Items based on XQuery Pagination Structure ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryApplicationAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize Query ... - query = NormalizeQuery(query, configuration); - - // - var items = await GetAllApplicationAsync( - userInfo: userInfo, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0 - ) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Prepare Result ... - var result = new XQueryResult - { - Page = query.Page, - Items = [.. items], - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider\XApplicationProvider+Custom.cs - -using System; -using System.Linq; -using xIds.Helpers; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore; - -namespace xIds.Providers -{ - public partial class XApplicationProvider - { - // - #region Custom Actions ... - /// - /// Show Specifid Api Key ... - /// - /// - /// - /// - /// - /// - public async Task ShowApiKey( - Guid apiKeyId, - int applicationId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - userInfo.IsNullOrDefault() || - !applicationId.IsValidIntId() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Application Exists ... - var application = await GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - // Retrieve ApiKey Entity ... - // Since ApiKey is Only Exists on ApiKey Entity ... - var entity = await dbContext.ApiKeys - .FirstOrDefaultAsync(x => x.Id == apiKeyId); - if (entity.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return entity.Key; - } - - /// - /// Generate a New ApiKey and Add It to DB ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task CreateApiKey( - int applicationId, - TimeSpan? expiration = null, - IEnumerable scopes = null, - IEnumerable allowedIPs = null, - int? rateLimit = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - userInfo.IsNullOrDefault() || - !applicationId.IsValidIntId() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Application Exists ... - var application = await GetApplicationAsync( - id: applicationId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Validate Owner ... - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - // Normalizing ... - if (!rateLimit.HasValue) - { - rateLimit = apiKeyConfiguration.DefaultRateLimit; - } - if (!expiration.HasValue) - { - expiration = TimeSpan.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes); - } - else if (expiration.Value > TimeSpan.FromMinutes(apiKeyConfiguration.MaxExpirationMinutes)) - { - expiration = TimeSpan.FromMinutes(apiKeyConfiguration.MaxExpirationMinutes); - } - - // - // Generate New Key ... - (string plainKey, string keyHash, string prefix) = XApiKeyHelper.Generate(apiKeyConfiguration.ApiKeyPrefix); - var expireAt = DateTime.UtcNow.Add(expiration.Value); - - // - var _allowedScopes = scopes.ToJSON(); - var _allowedIPs = allowedIPs.ToListString(); - - // - // Instance Dto Item ... - var result = new XApiKeyDto - { - RevokedAt = null, - KeyHash = keyHash, - LastUsedAt = null, - KeyPrefix = prefix, - ExpiresAt = expireAt, - RevokedBy = string.Empty, - AllowedIPs = _allowedIPs, - CreatedOn = DateTime.UtcNow, - ApplicationId = applicationId, - AllowedScopes = _allowedScopes, - RateLimitPerMinute = rateLimit.Value - }; - - // - // Add Item to Database ... - result = await AddApiKeyAsync( - item: result, - apiKey: plainKey, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Revoke Specified Api Key ... - /// - /// - /// - /// - /// - public async Task RevokeApiKey( - Guid apiKeyId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - userInfo.IsNullOrDefault()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve ApiKey ... - var item = await GetApiKeyAsync( - id: apiKeyId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (item.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: item.ApplicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - // Update Revoke Info ... - item.RevokedAt = DateTime.UtcNow; - item.RevokedBy = userInfo.UserId; - - // - item = await UpdateApiKeyAsync( - id: item.Id, - item: item, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - var result = !item.IsNullOrDefault(); - return result; - } - - /// - /// Renew Specified Api Key ... - /// - /// - /// - /// - /// - /// - public async Task RotateApiKey( - Guid apiKeyId, - TimeSpan? newExpiration = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - apiKeyId.IsDefaultGuid() || - userInfo.IsNullOrDefault() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Item ... - var result = await GetApiKeyAsync( - id: apiKeyId, - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - // Expired Date ... - DateTime? expiredDate = null; - if (!newExpiration.HasValue) - { - // - newExpiration = TimeSpan - .FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes); - } - expiredDate = DateTime.UtcNow.Add(newExpiration.Value); - - // - if (!expiredDate.HasValue) - { - XException.InvalidArgs.Throw(); - } - - // - // Update Item ... - result.ExpiresAt = expiredDate.Value; - - // - result = await UpdateApiKeyAsync( - item: result, - id: result.Id, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Retrieve All Api Keys for Specified Application ... - /// - /// - /// - /// - /// - public async Task> GetApplicationApiKeys( - int applicationId, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if ( - userInfo.IsNullOrDefault() || - !applicationId.IsValidIntId() - ) - { - XException.InvalidArgs.Throw(); - } - - // - // Permission Checking ... - var application = await GetApplicationAsync( - userInfo: userInfo, - includeBuilder: null, - id: applicationId, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (application.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - if (!IsOwned(application, userInfo)) - { - XException.NotAllowed.Throw(); - } - - // - var result = await FindManyApiKeyAsync( - userInfo: userInfo, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => x.ApplicationId == applicationId - ); - - // - return result; - } - - /// - /// Validate Specified Api Key in based on ClientIP ... - /// - /// - /// - /// - /// - /// - /// - public async Task ValidateApiKey( - string apiKey, - string clientIP, - string requiredScope = null, - XUserClaimsInfoDto userInfo = null, - CancellationToken cancellationToken = default - ) - { - // - var result = new XApiKeyValidationResult(); - - // - // Validate ... - var isValid = - !apiKey.IsNullOrEmpty() && - !clientIP.IsNullOrEmpty(); - if (!isValid) - { - return result; - } - - // - // Detect Specified Api Key ... - var apiKeyHash = XApiKeyHelper.ComputeHash(apiKey); - var keyModel = await dbContext.ApiKeys - .FirstOrDefaultAsync( - ak => ak.KeyHash == apiKeyHash, - cancellationToken: cancellationToken - ); - isValid = !keyModel.IsNullOrDefault(); - if (!isValid) - { - // - result.Errors.Add("ApiKey not found ..."); - return result; - } - - // - // Here we Have to Parse Allowed Ips and Scopes ... - var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty() - ? [] - : keyModel.AllowedIPs.ParseListString(); - var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty() - ? [] - : keyModel.AllowedScopes.FromJSON>(); - result.Scopes = [.. allowedScopes]; - - // - // Check Application is Exists and Active ... - var application = await dbContext.Applications - .FirstOrDefaultAsync(x => x.Id == keyModel.ApplicationId); - if (!application.IsNullOrDefault()) - { - result.OwnerId = application.OwnerId; - result.ApplicationId = application.Id; - } - - // - // Check Application is Exists and Active or not ... - var isApplicationActive = - // - // Application Exists ... - !application.IsNullOrDefault() && - // - // Check Application is Active ... - application.IsActive - // - ; - if (!isApplicationActive) - { - result.Errors.Add("Related Application is Inactive ..."); - } - - // - // Check Key is Active or not ... - var isKeyActive = - // - // Check Api Key is Active ... - // Not Revoked ... - // Not Expired ... - keyModel.IsActive() - // - ; - if (!isKeyActive) - { - // - if (keyModel.IsExpired()) - { - result.Errors.Add("ApiKey is Expired ..."); - } - - // - if (keyModel.IsRevoked()) - { - result.Errors.Add("ApiKey is Revoked ..."); - } - } - - // - // Checking Rate Limit ... - var isRateLimitPassed = CheckRateLimit(keyModel.Id, keyModel.RateLimitPerMinute); - if (!isRateLimitPassed) - { - result.Errors.Add("ApiKey Rate Limit Reached ..."); - } - - // - var requiredScopes = - requiredScope.IsNullOrEmpty() - ? [] - : requiredScope.ParseListString(); - - // - // Check Scope and IP is Valid or not ... - var isIpValid = allowedIps.IsClientIpPassed(clientIP); - var isScopeValid = - allowedScopes - .IsScopePassed(requiredScopes); - var isScopeIpValid = - isIpValid && - isScopeValid - ; - if (!isScopeIpValid) - { - // - if (!isIpValid) - { - result.Errors.Add("Client IP not Allowed to Use Resource ..."); - } - - // - if (!isScopeValid) - { - result.Errors.Add("Required Scoped is Invalid ..."); - } - } - - // - isValid = - isKeyActive && - isScopeIpValid && - isRateLimitPassed && - isApplicationActive; - if (isValid) - { - // - // Handle Attach Owner ... - try - { - // - var user = await identityManager.GetUserAsync( - containsDetail: true, - userSelectByParam: application.OwnerId - ); - - // - var owner = user.ToXPerson(); - result.Owner = owner; - } - catch (Exception ex) - { - // - result.Errors.Add($"exception occured: {ex.Message}"); - return result; - } - - result.Errors.Clear(); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XApplicationProvider\XApplicationProvider+Enricher.cs - -using System.Linq; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; - -namespace xIds.Providers -{ - public partial class XApplicationProvider - { - // - #region Enrichers ... - /// - /// Enrich Api Key ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApiKey source, - CancellationToken cancellationToken = default - ) - { - // - var result = source.MapConvert(mapperConfigurationExp); - result = await EnrichAsync( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Api Key ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApiKeyDto source, - CancellationToken cancellationToken = default - ) - { - // - if ( - !source.IsNullOrDefault() && - !source.Application.IsNullOrDefault() - ) - { - // - var application = await dbContext.Applications - .FirstOrDefaultAsync( - x => x.Id == source.ApplicationId, - cancellationToken: cancellationToken - ); - if (!application.IsNullOrDefault()) - { - // - var dto = await EnrichAsync( - source: application, - cancellationToken: cancellationToken - ); - if (!dto.IsNullOrDefault()) - { - source.Application = dto; - } - } - } - - // - return source; - } - - /// - /// Enrich Api Key Usage ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApiKeyUsage source, - CancellationToken cancellationToken = default - ) - { - // - var result = source.MapConvert(mapperConfigurationExp); - result = await EnrichAsync( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Application ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApplication source, - CancellationToken cancellationToken = default - ) - { - // - var result = source.MapConvert(mapperConfigurationExp); - result = await EnrichAsync( - source: result, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Api Key Usage ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApiKeyUsageDto source, - CancellationToken cancellationToken = default - ) - { - // - // There is not any Additional Enrichment ... - var result = await Task.FromResult(source); - return result; - } - - /// - /// Enrich Application ... - /// - /// - /// - /// - public async Task EnrichAsync( - XApplicationDto source, - CancellationToken cancellationToken = default - ) - { - // - if ( - !source.IsNullOrDefault() && - !source.OwnerId.IsNullOrEmpty() - ) - { - // - var owner = await GetOwner(source.OwnerId); - if (!owner.IsNullOrDefault()) - { - source.Owner = owner; - } - } - - // - return source; - } - - /// - /// Enrich a Collection of Api Key(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - - /// - /// Enrich a Collection of Api Key(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - - /// - /// Enrich a Collection of Api Key Usage(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - - /// - /// Enrich a Collection of Application(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - - /// - /// Enrich a Collection of Api Key Usage(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - - /// - /// Enrich a Collection of Application(s) ... - /// - /// - /// - /// - public async Task> EnrichRangeAsync( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var tasks = sources - .Select(s => EnrichAsync(s, cancellationToken)); - - // - var result = await Task.WhenAll(tasks); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Admin.cs - -using System.Collections.Generic; -using System.Threading.Tasks; -using xCommons.Extensions; -using xIdentityModels.Dtos; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - #region Admin Actions ... - /// - /// Retrieve All UnBanned Users Identifiers - /// - /// caller user identifier - /// a collection of user identifiers - public async Task> GetAllUnbanned( - ICollection userSelectByParam - ) - { - // - var result = new List(); - if (!userSelectByParam.HasChild()) - { - return result; - } - - // - foreach (var uParam in userSelectByParam) - { - // - var destUser = await ValidateUserExistsAndRetrieve(uParam, checkIsBanned: false); - if (!destUser.IsBanned) - { - result.Add(uParam); - } - } - - // - return result; - } - - /// - /// Get All Banned Users Identifiers - /// - /// caller user identifier - /// a collection of user identifiers - public async Task> GetAllBanned( - ICollection userSelectByParam - ) - { - // - var result = new List(); - if (!userSelectByParam.HasChild()) - { - return result; - } - - // - foreach (var uParam in userSelectByParam) - { - // - var destUser = await ValidateUserExistsAndRetrieve(uParam, checkIsBanned: false); - if (destUser.IsBanned) - { - result.Add(uParam); - } - } - - // - return result; - } - - /// - /// Ban a Collection of Users - /// - /// caller user identifier - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a collection of user identifiers - public async Task> Ban( - string userSelectByParam, - XUserNameIdRequest model - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(model); - ValidationProvider.NotZeroChilds(model.Ids); - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: true, - checkIsBanned: true, - containDetails: false, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = new List(); - foreach (var uParam in model.Ids) - { - // - var destUser = await ValidateUserExistsAndRetrieve(uParam, checkIsBanned: false); - - // - var isBanned = destUser.IsBanned; - if (!isBanned) - { - // - destUser.IsBanned = true; - - // - await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - result.Add(destUser.Id); - } - } - - // - return result; - } - - /// - /// UnBan a Collection of Users - /// - /// caller user identifier - /// an instance of XUserNameIdRequest which represents user identifier list to Ban - /// a collection of user identifiers - public async Task> UnBan( - string userSelectByParam, - XUserNameIdRequest model - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(model); - ValidationProvider.NotZeroChilds(model.Ids); - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: true, - checkIsBanned: true, - containDetails: false, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = new List(); - foreach (var uParam in model.Ids) - { - // - var destUser = await ValidateUserExistsAndRetrieve(uParam, checkIsBanned: false); - - // - var isBanned = destUser.IsBanned; - if (isBanned) - { - // - destUser.IsBanned = false; - - // - await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - result.Add(destUser.Id); - } - } - - // - return result; - } - - /// - /// Detrmines a User is Banned or not - /// - /// caller user identifier - /// destination user identifier which checked is banned or not - /// a boolean value which represent user banned or not - public async Task IsBanned( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: false, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - var destUser = await ValidateUserExistsAndRetrieve(destUserSelectByParam, checkIsBanned: false); - - // - var result = destUser.IsBanned; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Device.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Navigations; -using xIds.Extensions; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Device Actions ... - /// - /// Check a Device Exists or Not - /// - /// an instance of XDevice - /// a boolean value - public async Task IsDeviceExistsAsync( - XDevice device - ) - { - return await DbContext.Devices - .AnyAsync(d => d.IsSameAs(device)); - } - - /// - /// Add new Device - /// - /// an instance of XDevice - /// an instance of XDevice - public async Task AddDeviceAsync( - XDevice device - ) - { - // - var isDeviceExists = await IsDeviceExistsAsync(device); - if (isDeviceExists) - { - return null; - } - - // - await DbContext.Devices - .AddAsync(device); - - await DbContext.SaveChangesAsync(); - - return device; - } - - /// - /// Get a Device - /// - /// an instance of XDevice - /// an instance of XDevice - public Task GetDeviceAsync( - XDevice device - ) - { - // - return DbContext.Devices - .FirstOrDefaultAsync(d => - d.IsSameAs(device)); - } - - /// - /// Retrieve a List of User Related Devices - /// - /// user identifier - /// check a user can log in in system or not - /// check user is banned or not - /// a collection of XDevice instances which related to user - public async Task> GetUserDevices( - string userSelectByParam, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate ARgs ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate And Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - - // - // Check User Devices ... - if (!user.Devices.HasChild()) - { - return new List(); - } - - // - return user.Devices; - } - - /// - /// Determines a Device is Exists in User's Devices or not - /// - /// an instance of XUser - /// an instance of XDevice - /// a boolean value - public bool IsDeviceRelateDToUser( - XUser user, - XDevice device - ) - { - if (!user.Devices.HasChild()) - { - return false; - } - - // - var result = user.Devices.Any(d => d.IsSameAs(device)); - - // - return result; - } - - /// - /// Determines a Device is Exists in User's Devices or not - /// - /// user identifier - /// an instance of XDevice - /// check a user can log in in system or not - /// check user is banned or not - /// a boolean value - public async Task IsDeviceRelateDToUser( - string userSelectByParam, - XDevice device, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(device); - - // - var userDevices = await GetUserDevices( - userSelectByParam, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - if (!userDevices.HasChild()) - { - return false; - } - - // - var result = userDevices.Any(d => d.IsSameAs(device)); - - // - return result; - } - - /// - /// Add a Device to a User Related Devices - /// - /// an instance of XUser - /// an instance of XDevice - /// a boolean value - public async Task AddUserRelatedDevice( - XUser user, - XDevice device - ) - { - // - var isExists = user.Devices.Any(d => - d.IsSameAs(device)); - if (isExists) - { - return true; - } - - // - user.Devices.Add(device); - try - { - var result = await UpdateUserAsync(user); - return result.Succeeded; - } - catch - { - throw XException.ActionFailed.ToException(); - } - } - - /// - /// Add a Device to a User - /// - /// user identifier - /// an instance of XDevice - /// check a user can log in in system or not - /// check user is banned or not - /// a boolean value - public async Task AddUserRelatedDevice( - string userSelectByParam, - XDevice device, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(device); - - // - // Check Device Related ... - var isDeviceRelatedToUser = await IsDeviceRelateDToUser( - userSelectByParam, - device, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned); - if (isDeviceRelatedToUser) - { - return true; - } - - // - // Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - - // - // Add User Device ... - user.Devices.Add(device); - - // - var result = await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - return result.Succeeded; - } - - /// - /// Remove a Device from a User Related Devices List - /// - /// an instance of XUser - /// an instance of XDevice - /// a boolean value - public async Task RemoveUserRelatedDevice( - XUser user, - XDevice device - ) - { - // - var isRelated = IsDeviceRelateDToUser(user, device); - if (!isRelated) - { - return false; - } - - // - var instanse = user.Devices - .FirstOrDefault(d => - d.IsSameAs(device)); - - // - user.Devices.Remove(instanse); - - // - var result = await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - return result.Succeeded; - } - - /// - /// Remove a Device from a User Devices - /// - /// user identifier - /// an instance of XDevice - /// check a user can log in in system or not - /// check user is banned or not - /// a boolean value - public async Task RemoveUserRelatedDevice( - string userSelectByParam, - XDevice device, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(device); - - // - // Validate user exists and Retrieve it based on userselectbyparam ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - - // - return await RemoveUserRelatedDevice( - user, - device - ); - } - #endregion - - // - #region Banned Device Actions ... - /// - /// Check a Device is exists in Banned Devices or not - /// - /// an instance of XDevice - /// a boolean value - public async Task IsBannedDeviceExists( - XDevice device - ) - { - // - var result = false; - var bannedDeviceEnumerable = DbContext.BannedDevices.AsAsyncEnumerable(); - await - foreach (var bannedDevice in bannedDeviceEnumerable) - { - // - if (bannedDevice.Device.IsSameAs(device)) - { - // - result = true; - break; - } - } - - // - return result; - } - - /// - /// Find First Banned Device - /// - /// an instance of XDevice - /// an instance of XDevice - public async Task BannedDeviceFindOne( - XDevice device - ) - { - // - var result = await DbContext.BannedDevices - .FirstOrDefaultAsync(bd => - bd.Device.IsSameAs(device) - ); - - // - return result; - } - - /// - /// Remove Banned Device - /// - /// an instance of XBannedDevice - /// - public async Task BannedDeviceRemove( - XBannedDevice model - ) - { - // - var isExists = await IsBannedDeviceExists(model.Device); - if (!isExists) - { - return; - } - - // - var item = await BannedDeviceFindOne(model.Device); - if (item == null) - { - return; - } - - // - DbContext.BannedDevices.Remove(item); - await DbContext.SaveChangesAsync(); - } - - /// - /// Check a Device is Banned or not - /// - /// an instance of XDevice - /// a boolean value - private async Task IsDeviceBanned( - XDevice device - ) - { - // - var result = await IsBannedDeviceExists(device); - return result; - } - - /// - /// Retrieve Specific Banned Device - /// - /// an instance of XDevice - /// an instance of XBannedDevice - private async Task GetBannedDevice( - XDevice device - ) - { - // - var result = await BannedDeviceFindOne(device); - return result; - } - - /// - /// Is a Banned Device passed Banning Time - /// - /// an instance of XBannedDevice - /// a boolean value - private bool IsDelayTimePassed( - XBannedDevice bannedDevice - ) - { - // - // Validate Args ... - if (bannedDevice == null || - Configuration == null) - { - XException.InvalidArgs.Throw(); - } - - // - var isPassed = bannedDevice - .IsDelayTimePassed(Configuration.BannedDeviceTimeout); - - // - return isPassed; - } - - /// - /// Retrieve Passed Time from Banning Time of specific Device - /// - /// an instance of XBannedDevice - /// an instance of DateTime which represent Passed Time - private DateTime GetPassedTime( - XBannedDevice bannedDevice - ) - { - // - var result = bannedDevice.BannedOn - .AddSeconds(Configuration.BannedDeviceTimeout); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Friendship.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using xCommons.Extensions; -using xDataService.Extensions; -using xExceptions.Constants; -using xIdentityModels.Constants; -using xIdentityModels.Dtos; -using xIdentityModels.Navigations; -using xModels.Dtos; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Friendship Actions ... - // - #region Actions ... - /// - /// Send a Follow Request for userSelectByParam to - /// destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollowing - public async Task Follow( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - XFriendshipFollowing following = null; - XFriendshipFollower follower = null; - var isRequested = IsFollowRequested(xUser, xDestUser); - // - // Check Request Happens Or not ... - if (!isRequested) - { - // - following = new XFriendshipFollowing - { - UserId = xUser.Id, - DestId = xDestUser.Id, - State = XFriendshipState.Pending - }; - - // - follower = new XFriendshipFollower - { - UserId = xDestUser.Id, - DestId = xUser.Id, - State = XFriendshipState.Pending - }; - - // - xUser.Followings.Add(following); - xDestUser.Followers.Add(follower); - } - else - { - // - // if Request Done Before Must Check State ... - following = xUser.Followings.FirstOrDefault(f => f.DestId == xDestUser.Id); - follower = xDestUser.Followers.FirstOrDefault(f => f.DestId == xUser.Id); - if (following.IsNull() || - follower.IsNull()) - { - XException.NotFound.Throw(); - } - - // - switch (following.State) - { - case XFriendshipState.Accepted: - case XFriendshipState.Blocked: - throw XException.NotAllowed.ToException(); - - case XFriendshipState.Rejected: - following.State = XFriendshipState.Pending; - follower.State = XFriendshipState.Pending; - break; - } - } - - // - var canContinue = !following.IsNull() && !follower.IsNull(); - if (!canContinue) - { - XException.ActionFailed.Throw(); - } - - // - await UpdateUserAsync(xUser); - await UpdateUserAsync(xDestUser); - - // - var result = following; - - // - return result; - } - - /// - /// Cancel Following - /// - /// caller user identifier - /// dest user identifier - /// a boolean value - public async Task Cancel( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - XFriendshipFollowing following = null; - XFriendshipFollower follower = null; - var isRequested = IsFollowRequested(xUser, xDestUser); - // - // Check Request Happens Or not ... - if (!isRequested) - { - return false; - } - - // - // if Request Done Before Must Check State ... - following = xUser.Followings.FirstOrDefault(f => f.DestId == xDestUser.Id); - follower = xDestUser.Followers.FirstOrDefault(f => f.DestId == xUser.Id); - if (following.IsNull() || - follower.IsNull()) - { - XException.NotFound.Throw(); - } - - // - switch (following.State) - { - case XFriendshipState.Accepted: - case XFriendshipState.Blocked: - throw XException.NotAllowed.ToException(); - - case XFriendshipState.Rejected: - case XFriendshipState.Pending: - DbContext.Followers.Remove(follower); - DbContext.Followings.Remove(following); - break; - } - - // - var canContinue = !following.IsNull() && !follower.IsNull(); - if (!canContinue) - { - XException.ActionFailed.Throw(); - } - - // - await DbContext.SaveChangesAsync(); - - // - return true; - } - - /// - /// userSelectByParam remove friendship by it's Follower - /// destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// - public async Task UnFollowFollower( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - ValidateIsFollowers(xUser, xDestUser); - - // - var follower = xUser.Followers - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - f.State == XFriendshipState.Accepted); - var following = xDestUser.Followings - .FirstOrDefault(f => - f.DestId == xUser.Id && - f.State == XFriendshipState.Accepted); - if (follower.IsNull() || - following.IsNull()) - { - XException.NotFound.Throw(); - } - - // - DbContext.Followers.Remove(follower); - DbContext.Followings.Remove(following); - - // - await DbContext.SaveChangesAsync(); - } - - /// - /// userSelectByParam remove friendship by it's Followings - /// destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// - public async Task UnFollowFollowing( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - ValidateIsFollowings(xUser, xDestUser); - - // - var following = xUser.Followings - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - f.State == XFriendshipState.Accepted); - var follower = xDestUser.Followers - .FirstOrDefault(f => - f.DestId == xUser.Id && - f.State == XFriendshipState.Accepted); - if (follower.IsNull() || - following.IsNull()) - { - XException.NotAllowed.Throw(); - } - - // - DbContext.Followers.Remove(follower); - DbContext.Followings.Remove(following); - - // - await DbContext.SaveChangesAsync(); - } - - /// - /// userSelectByParam Block it's follower destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollowing - public async Task Block( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - // Validate XDestUser is Accepted Follower of XUser ... - ValidateIsFollowers(xUser, xDestUser); - - // - // Retrieve FriendShip Models ... - var following = xDestUser.Followings - .FirstOrDefault(f => - f.DestId == xUser.Id && - ( - f.State == XFriendshipState.Accepted - ) - ); - var follower = xUser.Followers - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - ( - f.State == XFriendshipState.Accepted - ) - ); - if (following.IsNull() || - follower.IsNull()) - { - XException.NotAllowed.Throw(); - } - - // - follower.State = XFriendshipState.Blocked; - following.State = XFriendshipState.Blocked; - - // - DbContext.Followers.Update(follower); - DbContext.Followings.Update(following); - - // - await DbContext.SaveChangesAsync(); - - // - var result = following; - - // - return result; - } - - /// - /// userSelectByParam UnBlock it's follower destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollowing - public async Task UnBlock( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - // Validate XDestUser is Accepted Follower of XUser ... - ValidateIsBlock(xUser, xDestUser); - - // - // Retrieve FriendShip Models ... - var following = xDestUser.Followings - .FirstOrDefault(f => - f.DestId == xUser.Id && - ( - f.State == XFriendshipState.Blocked - ) - ); - var follower = xUser.Followers - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - ( - f.State == XFriendshipState.Blocked - ) - ); - if ( - following.IsNull() || - follower.IsNull() - ) - { - XException.NotAllowed.Throw(); - } - - // - follower.State = XFriendshipState.Accepted; - following.State = XFriendshipState.Accepted; - - // - DbContext.Followers.Update(follower); - DbContext.Followings.Update(following); - - // - await DbContext.SaveChangesAsync(); - - // - var result = following; - - // - return result; - } - #endregion - - // - #region Request Handlers ... - /// - /// userSelectByParam Accept Follow Request of - /// destUserSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollower - public async Task AcceptRequest( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - // Validate Request Sent and in Pending State ... - ValidateFollowingRequestForAccept(xUser, xDestUser); - - // - // Retrieve FriendShip Models ... - var following = xDestUser.Followings - .FirstOrDefault(f => - f.DestId == xUser.Id && - ( - f.State == XFriendshipState.Pending || - f.State == XFriendshipState.Rejected - ) - ); - var follower = xUser.Followers - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - ( - f.State == XFriendshipState.Pending || - f.State == XFriendshipState.Rejected - ) - ); - if (following.IsNull() || - follower.IsNull()) - { - XException.NotAllowed.Throw(); - } - - // - follower.State = XFriendshipState.Accepted; - following.State = XFriendshipState.Accepted; - - // - await UpdateUserAsync(xUser); - await UpdateUserAsync(xDestUser); - - // - var result = follower; - - // - return result; - } - - /// - /// Reject a Follow Request of destUserSelectByParam - /// with userSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollower - public async Task RejectRequest( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - // Validate Request Sent and in Pending State ... - ValidateFollowingRequest(xUser, xDestUser); - - // - // Retrieve Pending Specified User Request Friendship models ... - var following = xDestUser.Followings - .FirstOrDefault(f => - f.DestId == xUser.Id && - f.State == XFriendshipState.Pending); - var follower = xUser.Followers - .FirstOrDefault(f => - f.DestId == xDestUser.Id && - f.State == XFriendshipState.Pending); - if (following.IsNull() || - follower.IsNull()) - { - XException.NotFound.Throw(); - } - - // - follower.State = XFriendshipState.Rejected; - following.State = XFriendshipState.Rejected; - - // - DbContext.Followers.Update(follower); - DbContext.Followings.Update(following); - - // - await DbContext.SaveChangesAsync(); - - // - var result = follower; - - // - return result; - } - #endregion - - // - #region Getters ... - /// - /// determines destUserSelectByParam is in followers of - /// userSelectByParam or not - /// - /// caller user identifier - /// dest user identifier - /// check user is banned or not, default is true - /// check a user can log in in system or not, default is true - /// a boolean value - public async Task IsFollower( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var result = IsFollowRequested(xDestUser, xUser, XFriendshipState.Accepted); - - // - return result; - } - - /// - /// retrieve Friendship state of destUserSelectByParam - /// in Followers of userSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// check user is banned or not, default is true - /// check a user can log in in system or not, default is true - /// a member of XFriendshipState - public async Task GetFollowerState( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var isFollow = IsFollowRequested(xDestUser, xUser); - if (!isFollow) - { - return XFriendshipState.None; - } - - // - var follower = xUser.Followers.FirstOrDefault(f => f.DestId == xDestUser.Id); - if (follower.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return follower.State; - } - - /// - /// get follower friendship model of destUserSelectByParam - /// in followers of userSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollower - public async Task GetFollower( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var isFollow = IsFollowRequested(xDestUser, xUser); - if (!isFollow) - { - return null; - } - - // - var follower = xUser.Followers - .FirstOrDefault(f => f.DestId == xDestUser.Id); - if (follower.IsNull()) - { - XException.NotFound.Throw(); - } - - // - var result = follower; - - // - return result; - } - - /// - /// Retrieve Accepted Followers list of userSelectByParam - /// - /// caller user identifier - /// a collection of XFriendshipFollower instances - public async Task> GetFollowers( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = xUser.Followers - .Where(f => f.State == XFriendshipState.Accepted); - - // - return result; - } - - /// - /// Retrieve all Followers list of userSelectByParam - /// - /// caller user identifier - /// a collection of XFriendshipFollower instances - public async Task> GetAllFollowers( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = xUser.Followers; - - // - return result; - } - - /// - /// Read Specified User's Follower's List based on Query Model ... - /// - /// - /// - /// - public async Task> QueryFollowers( - XQuery query, - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: false, - containDetails: false, - ignoreDisabledUser: false, - checkCanLoginPolicies: false - ); - - // - // Prepare Query ... - - // - if (query.PageSize < DataConfiguration - .PagingConfiguration - .MinAvailablePageSize) - { - // - query.PageSize = DataConfiguration - .PagingConfiguration - .DefaultPageSize; - } - - // - if (query.PageSize > DataConfiguration - .PagingConfiguration - .MaxAvailablePageSize) - { - // - query.PageSize = DataConfiguration - .PagingConfiguration - .MaxAvailablePageSize; - } - - // - // Prepare Enumerator ... - Expression> whereClause = x => x.UserId == xUser.Id; - var enumerator = DbContext.Followers.AsAsyncEnumerable(); - var resultItems = new List(); - await foreach (var entity in enumerator) - { - // - var isApproved = whereClause.Compile()(entity); - if (isApproved) - { - // - // Convert Approved Entity to Dto ... - // then Validate it and Add it to Results ... - var dto = await ToDto(entity); - if (!dto.IsNull()) - { - resultItems.Add(dto); - } - } - } - - // - // Enumerable ... - var result = resultItems.AsEnumerable(); - - // - // Count Total Items ... - var totalItemsCount = result.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - result = result.ApplyFilter(query.Filter); - } - - // - // Count Filtered Items ... - var totalFilteredItemsCount = result.Count(); - - // - // Apply Paging ... - if (totalItemsCount > 0 && - totalFilteredItemsCount > 0) - { - // - // Apply Sorting ... - if (!query.SortBy.IsNullOrEmpty()) - { - // - // Since Sorting Based on Date is Very Important ... - // we have to do Sorting at first Time then - // try to apply Paging ... - result = result - .ApplySorting( - query.SortBy, - query.IsAscending) - .ToList(); - } - - // - // Apply Paging ... - result = result - .ApplyPaging( - query.Page, - query.PageSize) - .ToList(); - } - - // - // Calculating Page Count ... - int pagesCount = totalItemsCount / query.PageSize; - if (totalItemsCount % query.PageSize > 0) - { - pagesCount++; - } - - // - // Generate Result Object ... - var queryResult = new XQueryResult - { - Page = query.Page, - TotalPages = pagesCount, - PageSize = query.PageSize, - TotalItems = totalItemsCount, - Items = result.AsEnumerable(), - TotalFilteredItems = totalFilteredItemsCount - }; - - // - return queryResult; - } - - /// - /// determines destUserSelectByParam is in followings of - /// userSelectByParam or not - /// - /// caller user identifier - /// dest user identifier - /// check user is banned or not, default is true - /// check a user can log in in system or not, default is true - /// a boolean value - public async Task IsFollowing( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var result = IsFollowRequested(xUser, xDestUser, XFriendshipState.Accepted); - - // - return result; - } - - /// - /// retrieve Frindship State of destUserSelectByParam - /// in Followings of userSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// check user is banned or not, default is true - /// check a user can log in in system or not, default is true - /// a member of XFriendshipState - public async Task GetFollowingState( - string userSelectByParam, - string destUserSelectByParam, - bool checkIsBanned = true, - bool checkCanLoginPolicies = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var isFollow = IsFollowRequested(xUser, xDestUser); - if (!isFollow) - { - return XFriendshipState.None; - } - - // - var following = xUser.Followings.FirstOrDefault(f => f.DestId == xDestUser.Id); - if (following.IsNull()) - { - XException.NotFound.Throw(); - } - - // - return following.State; - } - - /// - /// get following friendship model of destUserSelectByParam - /// in followings of userSelectByParam - /// - /// caller user identifier - /// dest user identifier - /// an instance of XFriendshipFollowing - public async Task GetFollowing( - string userSelectByParam, - string destUserSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - // Validate Not Same Source and Dest Users ... - ValidateNotSameUsers(xUser, xDestUser); - - // - var isFollow = IsFollowRequested(xUser, xDestUser); - if (!isFollow) - { - return null; - } - - // - var following = xUser.Followings.FirstOrDefault(f => f.DestId == xDestUser.Id); - if (following.IsNull()) - { - XException.NotFound.Throw(); - } - - // - var result = following; - - // - return result; - } - - /// - /// Retrieve accepted Followings List of userSelectByParam - /// - /// caller user identifier - /// a collection of XFriendshipFollowing instances - public async Task> GetFollowings( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = xUser.Followings - .Where(f => f.State == XFriendshipState.Accepted); - - // - return result; - } - - /// - /// Retrieve all Followings List of userSelectByParam - /// - /// caller user identifier - /// a collection of XFriendshipFollowing instances - public async Task> GetAllFollowings(string userSelectByParam) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: true, - containDetails: true, - ignoreDisabledUser: false, - checkCanLoginPolicies: true - ); - - // - var result = xUser.Followings; - - // - return result; - } - - /// - /// Read Specified User's Following's List based on Query Model ... - /// - /// - /// - /// - public async Task> QueryFollowings( - XQuery query, - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(query); - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve User ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - checkIsBanned: false, - containDetails: false, - ignoreDisabledUser: false, - checkCanLoginPolicies: false - ); - - // - // Prepare Query ... - - // - if (query.PageSize < DataConfiguration - .PagingConfiguration - .MinAvailablePageSize) - { - // - query.PageSize = DataConfiguration - .PagingConfiguration - .DefaultPageSize; - } - - // - if (query.PageSize > DataConfiguration - .PagingConfiguration - .MaxAvailablePageSize) - { - // - query.PageSize = DataConfiguration - .PagingConfiguration - .MaxAvailablePageSize; - } - - // - // Prepare Enumerator ... - Expression> whereClause = x => x.UserId == xUser.Id; - var enumerator = DbContext.Followings.AsAsyncEnumerable(); - var resultItems = new List(); - await foreach (var entity in enumerator) - { - // - var isApproved = whereClause.Compile()(entity); - if (isApproved) - { - // - // Convert Approved Entity to Dto ... - // then Validate it and Add it to Results ... - var dto = await ToDto(entity); - if (!dto.IsNull()) - { - resultItems.Add(dto); - } - } - } - - // - // Enumerable ... - var result = resultItems.AsEnumerable(); - - // - // Count Total Items ... - var totalItemsCount = result.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - result = result.ApplyFilter(query.Filter); - } - - // - // Count Filtered Items ... - var totalFilteredItemsCount = result.Count(); - - // - // Apply Paging ... - if (totalItemsCount > 0 && - totalFilteredItemsCount > 0) - { - // - // Apply Sorting ... - if (!query.SortBy.IsNullOrEmpty()) - { - // - // Since Sorting Based on Date is Very Important ... - // we have to do Sorting at first Time then - // try to apply Paging ... - result = result - .ApplySorting( - query.SortBy, - query.IsAscending) - .ToList(); - } - - // - // Apply Paging ... - result = result - .ApplyPaging( - query.Page, - query.PageSize) - .ToList(); - } - - // - // Calculating Page Count ... - int pagesCount = totalItemsCount / query.PageSize; - if (totalItemsCount % query.PageSize > 0) - { - pagesCount++; - } - - // - // Generate Result Object ... - var queryResult = new XQueryResult - { - Page = query.Page, - TotalPages = pagesCount, - PageSize = query.PageSize, - TotalItems = totalItemsCount, - Items = result.AsEnumerable(), - TotalFilteredItems = totalFilteredItemsCount - }; - - // - return queryResult; - } - #endregion - - // - #region Others ... - /// - /// Retrieve List Of All Followings User Id's - /// of userSelectByParam - /// - /// caller user identifier - /// a collection of user identifiers - public async Task> GetFollowingList( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve followings List ... - var followings = await GetFollowings(userSelectByParam); - - // - var result = followings.Select(f => f.DestId); - - // - return result.ToList(); - } - - /// - /// Retrieve List Of All Followers User Id's - /// of userSelectByParam - /// - /// caller user identifier - /// a collection of user identifiers - public async Task> GetFollowersList( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Validate and Retrieve followings List ... - var followers = await GetFollowers(userSelectByParam); - - // - var result = followers.Select(f => f.DestId); - - // - return result.ToList(); - } - - /// - /// retrieve Friendship Info Model for Specific User - /// - /// caller user identifier - /// dest user identifier - /// check a user can log in in system or not, default is true - /// check user is banned or not, default is true - /// an instance of XFriendshipInfoDto - public async Task GetFriendshipInfo( - string userSelectByParam, - string destUserSelectByParam, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - destUserSelectByParam - ); - - // - // Validate and Retrieve Dest User ... - var xSourceUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - // Validate and Retrieve Dest User ... - var xDestUser = await ValidateUserExistsAndRetrieve( - destUserSelectByParam, - forceAdmin: false, - containDetails: true, - ignoreDisabledUser: false, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - var isSame = xSourceUser.Id == xDestUser.Id; - var isFollower = false; - var isFollowing = false; - var followerState = XFriendshipState.None; - var followingState = XFriendshipState.None; - - // - if (!isSame) - { - // - isFollower = await IsFollower( - userSelectByParam, - destUserSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - isFollowing = await IsFollowing( - userSelectByParam, - destUserSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - followerState = await GetFollowerState( - userSelectByParam, - destUserSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - followingState = await GetFollowingState( - userSelectByParam, - destUserSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - } - - // - var result = new XFriendshipInfoDto - { - UserId = xDestUser.Id, - IsFollower = isFollower, - IsFollowing = isFollowing, - FollowerState = followerState, - FollowingState = followingState, - Followers = xDestUser.Followers - .Count(f => f.State == XFriendshipState.Accepted), - Followings = xDestUser.Followings - .Count(f => f.State == XFriendshipState.Accepted) - }; - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Identity.cs - -using System; -using System.Net.Http; -using System.Threading.Tasks; -using IdentityModel.Client; -using Microsoft.Extensions.Logging; -using xCommons.Extensions; -using xExceptions.Constants; -using xExceptions.Models; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIds.Extensions; -using static IdentityModel.OidcConstants; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Identity Actions ... - /// - /// Request for Discovery Document - /// - /// an instance of DiscoveryDocumentResponse - public async Task RequestDiscoveryDocument() - { - // - var httpClient = GetHttpClient(); - var result = httpClient - .GetDiscoveryDocumentAsync(IdentityResourceConfiguration.Authority) - .ContinueWith(docTask => - { - // - httpClient.Dispose(); - return docTask.Result; - }); - - // - return await result; - } - - /// - /// Request AccessToken for Specific XApiScope - /// - /// a member of XApiScope - /// an instance of TokenResponse - public async Task RequestScopeAccessToken( - string scope - ) - { - // - // Validate Args ... - if (scope.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Disco Doc ... - var discoDoc = await RequestDiscoveryDocument(); - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - var request = new ClientCredentialsTokenRequest - { - Address = discoDoc.TokenEndpoint, - GrantType = GrantTypes.ClientCredentials, - ClientId = IdentityResourceConfiguration.ClientId, - ClientSecret = IdentityResourceConfiguration.ClientSecret, - Scope = scope - }; - - // - var httpClient = GetHttpClient(); - var result = await httpClient - .RequestClientCredentialsTokenAsync(request) - .ContinueWith(response => - { - // - httpClient.Dispose(); - return response.Result; - }); - - // - return result; - } - - /// - /// Authenticate a User - /// - /// an instance of XLoginRequest class which represent Authentication requirements - /// an instance of TokenResponse - public async Task Authenticate( - XLoginRequest model - ) - { - // - // Validate Args ... - ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroup(); - - // - // Retrieve Disco Doc ... - var discoDoc = await RequestDiscoveryDocument(); - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - // Create Request ... - var request = new PasswordTokenRequest - { - // - Address = discoDoc.TokenEndpoint, - - // - GrantType = GrantTypes.ClientCredentials, - ClientId = IdentityResourceConfiguration.ClientId, - ClientSecret = IdentityResourceConfiguration.ClientSecret, - - // - UserName = model.UserSelectBy, - Password = model.Password, - - // - // Pass Device to Request ... - Parameters = { { "force", false.ToJSON () } - } - }; - - // - var httpClient = GetHttpClient(); - var result = await httpClient - .RequestPasswordTokenAsync(request) - .ContinueWith(response => - { - // - httpClient.Dispose(); - return response.Result; - }); - - // - return result; - } - - /// - /// Do Login based on XLoginRequest - /// - /// an instance of XLoginRequest class which represent Authentication requirements - /// an instance of XLoginResponse - public async Task Login( - XLoginRequest model - ) - { - // - // Validate Args ... - ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model, model.Device) - .AddNotEmpty( - model.UserSelectBy, - model.Password - ) - .ValidateGroup(); - - // - // Get Token Response ... - // - // Retrieve Disco Doc ... - var discoDoc = await RequestDiscoveryDocument(); - Logger.LogInformation($"discoDoc: {discoDoc.ToJSON()}"); - - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - // Create Request ... - var request = new PasswordTokenRequest - { - // - Address = discoDoc.TokenEndpoint, - - // - GrantType = GrantTypes.ClientCredentials, - ClientId = IdentityResourceConfiguration.ClientId, - ClientSecret = IdentityResourceConfiguration.ClientSecret, - - // - UserName = model.UserSelectBy, - Password = model.Password, - - // - // Pass Device to Request ... - Parameters = { { "force", false.ToJSON () }, - { "device", model.Device.ToJSON () }, - { "language", model.Language } - } - }; - - // - var httpClient = GetHttpClient(); - var authResponse = await httpClient - .RequestPasswordTokenAsync(request) - .ContinueWith(response => - { - // - httpClient.Dispose(); - return response.Result; - }); - - // - // Check If Response Has Error ... - Logger.LogInformation($"AuthResponse: {authResponse.ToJSON()}"); - - // - if (authResponse.IsError) - { - throw authResponse.GetException(); - } - - // - // Create XLoginResponse Model ... - var result = authResponse.CreateXLoginResponse(); - - // - // Get ans Set User Profile ... - result.Profile = await GetUserProfileAsync(model.UserSelectBy, model.UserSelectBy); - - // - return result; - } - - /// - /// Refresh Tokens - /// - /// Authentication Tokens, instance of XTokenResponse - /// an instance of XTokenResponse - public async Task RefreshTokens( - XTokenResponse model - ) - { - // - // Validate Args ... - ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty( - model.AccessToken, - model.RefreshToken - ) - .ValidateGroup(); - - // - var authResponse = await RequestDiscoveryDocument() - .ContinueWith((discoTask) => - { - // - var discoDoc = discoTask.Result; - if (discoDoc.IsError) - { - XException.ActionFailed.Throw(); - } - - // - using (var httpClient = GetHttpClient()) - { - return httpClient.RequestRefreshTokenAsync(new RefreshTokenRequest - { - // - Address = discoDoc.TokenEndpoint, - GrantType = GrantTypes.RefreshToken, - ClientId = IdentityResourceConfiguration.ClientId, - ClientSecret = IdentityResourceConfiguration.ClientSecret, - RefreshToken = model.RefreshToken - }).Result; - } - }); - - // - // Check If Response Has Error ... - if (authResponse.IsError) - { - // - XError error = authResponse.ErrorDescription.FromJSON(); - throw error.ToException(); - } - - // - // Create XLoginResponse Model ... - var result = authResponse.CreateXTokenResponse(); - - // - return result; - } - #endregion - - // - #region Requirements ... - /// - /// Get an Instance of Http Client - /// - /// an instance of HttpClient - public HttpClient GetHttpClient() - { - // - HttpClient httpClient = null; - httpClient = new HttpClient(); - var httpClientHandler = new HttpClientHandler() - { - ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => - { - // - Logger.LogInformation( - $"SSL Handler: {Environment.NewLine} sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}" - ); - - // - return true; - }, - ClientCertificateOptions = ClientCertificateOption.Manual, - }; - - // - httpClient = new HttpClient(httpClientHandler); - - // - return httpClient; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+MessageProvider.cs - -using System; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Navigations; -using xMessageService.Models; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Message Provider ... - /// - /// Generate and Prepare an XMessage Instance for - /// User Invite Action - /// - /// specify destination language - /// reciever email address - /// invitation token - /// return url for invitation user to redirect - /// an instance of XMessage - private XMessage GetUserInviteMessage( - string lang, - string emailAddress, - string inviteToken, - string returnUrl - ) - { - // - ValidationProvider - .NotEmpty(lang, emailAddress, inviteToken, returnUrl); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .Url(returnUrl); - - // - HandleMessageProviderPreperation(lang); - - // - var msgStr = IdentityMessageProvider.InviteMsg + - Environment.NewLine + - returnUrl + - "?t=" + - inviteToken; - - // - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// New Device LoggedIn Action - /// - /// specify destination language - /// reciever email address - /// an instance of XDevice which represent user new Device - /// an instance of XMessage - private XMessage GetUserNewDeviceLoggedInMessage( - string lang, - string emailAddress, - XDevice device - ) - { - // - ValidationProvider - .NotEmpty(lang, emailAddress); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .NotNull(device); - - // - HandleMessageProviderPreperation(lang); - - // - // Generate Specific Message ... - var msgStr = IdentityMessageProvider.NewDeviceLoggedInMsg + - Environment.NewLine + - nameof(XDevice.Os) + ": " + device.Os + - Environment.NewLine + - nameof(XDevice.OsVersion) + ": " + device.OsVersion + - Environment.NewLine + - nameof(XDevice.Browser) + ": " + device.Browser + - Environment.NewLine + - nameof(XDevice.UserAgent) + ": " + device.UserAgent; - - // - // Create XMessage Instance ... - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// Verification Code Action - /// - /// specify destination language - /// an string which points to a user email address or mobile number - /// user verification code - /// an instance of XMessage - private XMessage GetVerificationCodeMessage( - string lang, - string mobileNumberOrEmail, - string verificationCode - ) - { - // - ValidationProvider - .NotEmpty(lang, mobileNumberOrEmail, verificationCode); - - // - HandleMessageProviderPreperation(lang); - - // - mobileNumberOrEmail = mobileNumberOrEmail.ToNormalString(); - - // - // Validate Mobile or Email ... - var isValidEmail = mobileNumberOrEmail.IsValidEmail(); - var isValidMobileNumber = mobileNumberOrEmail.IsValidMobileNumber(); - if (!isValidEmail && - !isValidMobileNumber) - { - XException.InvalidData.Throw(); - } - - // - // Prepare Message String ... - var msgStr = IdentityMessageProvider.VerificationCodeMsg + - Environment.NewLine + - verificationCode; - - // - // Create XMessage Instance ... - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(mobileNumberOrEmail); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// Registration Approve Action - /// - /// specify destination language - /// reciever email address - /// a token which approved user action - /// return url for redirect - /// an instance of XMessage - private XMessage GetRegistrationConfirmMessage( - string lang, - string emailAddress, - string actionToken, - string returnUrl - ) - { - // - ValidationProvider - .NotEmpty(lang, emailAddress, actionToken, returnUrl); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .Url(returnUrl); - - // - HandleMessageProviderPreperation(lang); - - // - // Prepare Message Str ... - var msgStr = IdentityMessageProvider.RegistrationApproveMsg + - Environment.NewLine + - returnUrl + - "?t=" + - actionToken; - - // - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// Registration Finished Action - /// - /// specify destination language - /// reciever email address - /// return url for redirect - /// an instance of XMessage - private XMessage GetRegistrationFinishedMessage( - string lang, - string emailAddress, - string returnUrl - ) - { - // - ValidationProvider - .NotEmpty(lang, emailAddress, returnUrl); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .Url(returnUrl); - - // - HandleMessageProviderPreperation(lang); - - // - var msgStr = IdentityMessageProvider.RegisteredMsg + - Environment.NewLine + - returnUrl; - - // - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// Password Changed Action - /// - /// specify destination language - /// reciever email address - /// return url for redirect - /// specify throw exceptions on failure or not, default is true - /// an instance of XMessage - private XMessage GetPasswordChangedMessage( - string lang, - string emailAddress, - string returnUrl, - bool throwException = true - ) - { - // - if (throwException) - { - ValidationProvider - .NotEmpty(lang, emailAddress, returnUrl); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .Url(returnUrl); - } - - // - HandleMessageProviderPreperation(lang); - - // - var msgStr = IdentityMessageProvider.PasswordChangedMsg + - (returnUrl.IsNullOrEmpty() ? - "" : - Environment.NewLine + - returnUrl); - - // - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - - /// - /// Generate and Prepare an XMessage Instance for - /// Reset Password Action - /// - /// specify destination language - /// reciever email address - /// a token which approved user action - /// return url for redirect - /// an instance of XMessage - private XMessage GetResetPasswordMessage( - string lang, - string emailAddress, - string actionToken, - string returnUrl - ) - { - // - ValidationProvider - .NotEmpty(lang, emailAddress, actionToken, returnUrl); - ValidationProvider - .EmailAddress(emailAddress); - ValidationProvider - .Url(returnUrl); - - // - HandleMessageProviderPreperation(lang); - - // - // Prepare Message Str ... - var msgStr = IdentityMessageProvider.ChangePasswordMsg + - Environment.NewLine + - returnUrl + - "?t=" + - actionToken; - - // - var message = new XMessage - { - Message = msgStr, - }; - message.Recievers.Add(emailAddress); - - // - return message; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Open.cs - -using System; -using System.Linq; -using System.Threading; -using xCommons.Extensions; -using xIdentityModels.Dtos; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; -using xIdentityModels.Models; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region OpenGet ... - /// - /// Get Open Action ... - /// - /// - /// - public async Task OpenGet( - XOpenActionInnerDto model - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(model) - .AddNotEmpty(model.Token) - .AddNotEmpty(model.Payload) - .ValidateGroupAsync(); - - // - return await OpenGet( - token: model.Token, - actionRequest: model.Payload - ); - } - - /// - /// Get Open Action ... - /// - /// - /// - /// - public async Task OpenGet( - string token, - string actionRequest - ) - { - // - // Validatr Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(token) - .AddNotEmpty(actionRequest) - .ValidateGroupAsync(); - // - // Try to Decrypt Request ... - var requestModel = ParseModel( - token: token, - request: actionRequest - ); - if (requestModel.IsNull() || - requestModel.Action.IsNullOrEmpty()) - { - XException.BadRequest.Throw(); - } - - // - var responseJson = string.Empty; - switch (requestModel.Action) - { - // - case XOpenActions.GetApiKey: - // - ValidationProvider.NotEmpty(requestModel.Payload); - var apiKeyId = await GetApiKey(requestModel); - responseJson = apiKeyId.ToString(); - break; - - // - case XOpenActions.UseApiKey: - // - ValidationProvider.NotEmpty(requestModel.Payload); - var isUsed = await UseApiKey(requestModel); - responseJson = isUsed.ToString(); - break; - - // - case XOpenActions.GetUserInfo: - // - ValidationProvider.NotEmpty(requestModel.Payload); - var userInfo = await GetUserInfo(requestModel); - if (userInfo.IsNull()) - { - XException.InvalidData.Throw(); - } - - // - responseJson = userInfo.ToJSON(); - break; - - // - case XOpenActions.GetUserInfos: - ValidationProvider.NotEmpty(requestModel.Payload); - var userInfos = await GetUserInfos(requestModel); - if (userInfos.IsNull()) - { - XException.InvalidData.Throw(); - } - - // - responseJson = userInfos.ToJSON(); - break; - } - - // - // Encrypt Json Str ... - var responseStr = SecurityProvider.Encrypt(responseJson); - requestModel.Payload = responseStr; - requestModel.Timestamp = DateTime.UtcNow - .AddMinutes(5) - .ToTimestamp() - .ToString(); - - // - token = requestModel.ToOpenActionToken(); - requestModel.Checksum = token; - var result = new XOpenActionInnerDto - { - Token = token, - Payload = requestModel.ToJSON() - }; - - // - // Check Result ... - if (result.IsNull()) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - #endregion - - /// - /// Get Specified Api Key ... - /// - /// - /// - /// - public async Task GetApiKey( - XOpenActionRequestDto model, - CancellationToken cancellationToken = default - ) - { - // - var apiKey = await DbContext.ApiKeys - .FirstOrDefaultAsync(x => - x.Key == model.Payload, - cancellationToken: cancellationToken - ); - var result = Guid.Empty; - if (!apiKey.IsNullOrDefault()) - { - result = apiKey.Id; - } - - // - return result; - } - - /// - /// Use Specified Api Key ... - /// - /// - /// - /// - public async Task UseApiKey( - XOpenActionRequestDto model, - CancellationToken cancellationToken = default - ) - { - // - // Load Model from Request ... - var apiKeyUsage = model.Payload.FromJSON(); - var result = !apiKeyUsage.IsNullOrDefault(); - if (!result) - { - return result; - } - - // - // Reading ApiKey ... - var apiKey = await DbContext.ApiKeys - .FirstOrDefaultAsync(x => x.Id == apiKeyUsage.ApiKeyId); - apiKey.LastUsedAt = DateTime.UtcNow; - DbContext.ApiKeys.Update(apiKey); - await DbContext.SaveChangesAsync(); - - // - // Prepare Entity ... - var entiy = new XApiKeyUsage - { - ApiKeyId = apiKeyUsage.ApiKeyId, - Endpoint = apiKeyUsage.Endpoint, - ClientIP = apiKeyUsage.ClientIP, - HttpMethod = apiKeyUsage.HttpMethod, - StatusCode = apiKeyUsage.StatusCode, - RequestedOn = apiKeyUsage.RequestedOn, - ResponseTimeMs = apiKeyUsage.ResponseTimeMs, - }; - await DbContext.ApiKeyUsages.AddAsync(entiy); - var changes = await DbContext.SaveChangesAsync(); - result = changes > 0; - - // - return result; - } - - /// - /// Get User Info For Open Actions ... - /// - /// - /// - public async Task GetUserInfo( - XOpenActionRequestDto model - ) - { - // - // Retrieve User Profile ... - var userProfile = await GetUserProfileAsync( - checkIsBanned: false, - checkCanLoginPolicies: false, - requestedUserSelectByParam: "", - forceCheckRequestedUser: false, - userSelectByParam: model.Payload - ); - - // - // Generate a Dynamic Object ... - var result = new XOpenActionUserInfoDto - { - UserId = userProfile.UserId, - Avatar = userProfile.Avatar, - Username = userProfile.UserName, - Lastname = userProfile.LastName, - Firstname = userProfile.FirstName, - }; - - // - return result; - } - - /// - /// Retrieve a Collection of Open Actions User Info by Providing Ids ... - /// - /// - /// - public async Task> GetUserInfos( - XOpenActionRequestDto model - ) - { - // - var ids = model.Payload.ParseListString().ToList(); - var profiles = await GetUserProfilesAsync( - ids: ids, - checkIsBanned: false, - checkCanLoginPolicies: false, - requestedUserSelectByParam: "", - forceCheckRequestedUser: false - ); - var result = profiles.Select(x => new XOpenActionUserInfoDto - { - UserId = x.UserId, - Avatar = x.Avatar, - Username = x.UserName, - Lastname = x.LastName, - Firstname = x.FirstName, - }); - - // - return result; - } - - // - #region Private ... - /// - /// Parse Models ... - /// - /// - /// - /// - private XOpenActionRequestDto ParseModel( - string token, - string request - ) - { - // - // Decript request to get Json string of request object ... - var result = new XOpenActionRequestDto(); - - // - var jsonStr = SecurityProvider.Decrypt(request); - result = jsonStr.FromJSON(); - if (result.IsNull() || - !result.Validate() || - token != result.Checksum - ) - { - // - result = null; - return result; - } - - // - var modelChecksum = result.ToOpenActionToken(); - result = - token == modelChecksum - ? result - : null; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Private.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using xCommons.Extensions; -using xCommons.Helpers; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Constants; -using xIdentityModels.Dtos; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Generators ... - /// - /// Generate a Random Number ... - /// - /// a long value - private long GenerateRandom() - { - return new Random().Next(100000, 999999); - } - #endregion - - // - #region UserSelectBy Actions ... - /// - /// Retrieve UserSelectByType based on Given Info - /// - /// a user identifier - /// a boolean value which specify the identifier - /// must be specific and not empty, default is true - /// a boolean value which specify the type - /// must be specific, default is false - /// a member of XUserSelectBy - private XUserSelectBy GetUserSelectByType( - string userSelectByParam, - bool forceUserSelectByParamNotEmpty = true, - bool forceUserSelectByTypeMustSpecified = false - ) - { - // - if (forceUserSelectByParamNotEmpty) - { - ValidationProvider.NotEmpty(userSelectByParam); - } - - // - var result = XUserSelectBy.NotSpecified; - var normalizedString = userSelectByParam.ToNormalString(); - if (userSelectByParam.IsValidEmail()) - { - // - // Find User by Email ... - result = XUserSelectBy.Email; - } - else if (userSelectByParam.IsValidMobileNumber()) - { - // - // Find User by Mobile Number ... - result = XUserSelectBy.MobileNumber; - } - else if (userSelectByParam.IsGuid()) - { - // - // Find User By it's ID ... - result = XUserSelectBy.ID; - } - else - { - // - // UserName ... - result = XUserSelectBy.Username; - } - - // - if (forceUserSelectByTypeMustSpecified && - result == XUserSelectBy.NotSpecified) - { - XException.InvalidData.Throw(); - } - - // - return result; - } - - /// - /// Retrieve UserSelectByParam based on XUser Object - /// - /// an instance of XUser - /// a boolean value which specify the identifier must nut empty, - /// and throw exception if it is empty, default is true - /// a collection of XUserSelectBy members which - /// exclude them from result, default is null - /// a user identifier - private string GetUserSelectByParam( - XUser user, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(user); - - // - var id = user.Id; - var userName = user.UserName; - var email = user.Email; - var phoneNumber = user.PhoneNumber; - - // - if (excludes != null) - { - if (excludes.Contains(XUserSelectBy.ID)) - { - id = null; - } - if (excludes.Contains(XUserSelectBy.Email)) - { - email = null; - } - if (excludes.Contains(XUserSelectBy.MobileNumber)) - { - phoneNumber = null; - } - if (excludes.Contains(XUserSelectBy.Username)) - { - userName = null; - } - } - - var selectByParam = - id.IsNullOrEmpty() ? - userName.IsNullOrEmpty() ? - email.IsNullOrEmpty() ? - phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; - - // - // Check result ... - if (forceNotNull && - selectByParam.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - return selectByParam; - } - - /// - /// Retrieve UserSelectByParam based on XActionRequestContext instance - /// - /// an instance of XActionRequestContext - /// a boolean value which specify the identifier must nut empty, - /// and throw exception if it is empty, default is true - /// a collection of XUserSelectBy members which - /// exclude them from result, default is null - /// a user identifier - private string GetUserSelectByParam( - XActionRequestContext context, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(context); - - // - // Generate User SelectBy ... - var id = context.UserId; - var userName = context.UserName; - var email = context.Email; - var phoneNumber = context.MobileNumber; - - // - if (excludes != null) - { - // - if (excludes.Contains(XUserSelectBy.ID)) - { - id = null; - } - if (excludes.Contains(XUserSelectBy.Email)) - { - email = null; - } - if (excludes.Contains(XUserSelectBy.MobileNumber)) - { - phoneNumber = null; - } - if (excludes.Contains(XUserSelectBy.Username)) - { - userName = null; - } - } - - var selectByParam = - id.IsNullOrEmpty() ? - userName.IsNullOrEmpty() ? - email.IsNullOrEmpty() ? - phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id; - - // - // Check param ... - if (forceNotNull && - selectByParam.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - return selectByParam; - } - - /// - /// Retrieve UserSelectByParam based on XActionRequestToken instance - /// - /// an instance of XActionRequestToken which - /// provides required informations - /// a boolean value which specify the identifier must nut empty, - /// and throw exception if it is empty, default is true - /// a collection of XUserSelectBy members which - /// exclude them from result, default is null - /// a user identifier - private string GetUserSelectByParam( - XActionRequestToken request, - bool forceNotNull = true, - ICollection excludes = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(request); - - // - // Generate User SelectBy ... - return GetUserSelectByParam( - context: request.Context, - forceNotNull: forceNotNull, - excludes: excludes - ); - } - - /// - /// Retrieve Available UserSelectByParams from given XUser - /// - /// an instance of XUser - /// - private ICollection GenerateUserSelectByParams( - XUser user - ) - { - // - if (user == null) - { - return null; - } - - // - var result = new List { - user.Id, - user.UserName, - user.PhoneNumber, - user.Email, - }; - - // - return result; - } - - /// - /// Retrieve Required XUserSelectByTypes - /// - /// a collection of XUserSelectBy members which - /// ignored in result - /// a collection of available XUserSelectBy members - private ICollection GenerateUserSelectByExcludes( - ICollection ignores - ) - { - // - var result = ObjectHelper - .ToEnumerableValues() - .Except(ignores); - - // - return result.ToList(); - } - #endregion - - // - #region XAction Actions ... - /// - /// Retrieve Action Result Response based on XToken - /// - /// an instance of XToken - /// an instance of XActionResponse - private XActionResponse GetActionResultResponse( - XToken xToken - ) - { - // - ValidationProvider.NotNull(xToken); - ValidationProvider.NotEmpty(xToken.Hash, xToken.Token); - - // - ValidateToken(xToken.Token); - - // - var expDate = GetTokenExpirationDate(xToken.Token); - ValidationProvider.NotNull(expDate); - - // - // Generate Result class ... - var result = new XActionResponse - { - Token = xToken.Hash, - Expiration = expDate - }; - - // - return result; - } - #endregion - - // - #region XIdentityMessage Actions ... - /// - /// Prepare Message Provider and Check it's State - /// - /// specify destination language - private void HandleMessageProviderPreperation( - string lang - ) - { - // - ValidationProvider - .NotEmpty(lang); - - // - // Prepare Identity Messages ... - // the PrepareMessageMethod check IsReady of Helper automatically ... - IdentityMessageProvider.PrepareMessages(lang); - - // - // Check Message Provider ... - var isMessageProviderReady = MessageProvider.IsReady(true); - if (!isMessageProviderReady) - { - XException.MessageServiceInitialFailed.Throw(); - } - } - #endregion - - // - #region Friendship Actions ... - /// - /// Check Follow Request Sent Before - /// from dest to source - /// - /// an instance of XUser - /// an instance of XUser - /// a boolean value - private bool IsFollowRequested( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - var result = source.Followings.Any(f => f.DestId == dest.Id); - - // - return result; - } - - /// - /// Check Follow Request Sent Before - /// from dest to source - /// - /// an instance of XUser - /// an instance of XUser - /// a member of XFriendshipState - /// a boolean value - private bool IsFollowRequested( - XUser source, - XUser dest, - XFriendshipState state - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - var result = source.Followings - .Any(f => - f.DestId == dest.Id && - f.State == state); - - // - return result; - } - - /// - /// Converts to XFriendDto ... - /// - /// - /// - private async Task ToDto(XFriendshipFollower entity) - { - // - XFriendDto result = null; - - // - if (entity.IsNull()) - { - return result; - } - - // - // Reading Dest User Profile ... - var profile = await GetUserProfileAsync( - userSelectByParam: entity.DestId, - requestedUserSelectByParam: entity.UserId, - forceCheckRequestedUser: false, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - // Preparing Result ... - result = new XFriendDto - { - UserId = profile.UserId, - Avatar = profile.Avatar, - Username = profile.UserName, - Lastname = profile.LastName, - Firstname = profile.FirstName, - Type = XFriendshipType.Follower, - State = profile.FriendshipInfo.FollowerState, - }; - - // - return result; - } - - /// - /// Converts to XFriendDto ... - /// - /// - /// - private async Task ToDto(XFriendshipFollowing entity) - { - // - XFriendDto result = null; - - // - if (entity.IsNull()) - { - return result; - } - - // - // Reading Dest User Profile ... - var profile = await GetUserProfileAsync( - checkIsBanned: false, - checkCanLoginPolicies: false, - forceCheckRequestedUser: false, - userSelectByParam: entity.DestId, - requestedUserSelectByParam: entity.UserId - ); - - // - // Preparing Result ... - result = new XFriendDto - { - UserId = profile.UserId, - Avatar = profile.Avatar, - Username = profile.UserName, - Lastname = profile.LastName, - Firstname = profile.FirstName, - Type = XFriendshipType.Following, - State = profile.FriendshipInfo.FollowingState, - }; - - // - return result; - } - #endregion - - // - #region User Profile ... - /// - /// Count User's Page - /// - /// an integer value which represent page size - /// an inetger value which represent pages count - public async Task UserPagesCount( - int pageSize - ) - { - // - int count = await UserManager.Users.CountAsync(); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - - /// - /// Count Avatar's Page - /// - /// an integer value which represent page size - /// an inetger value which represent pages count - public async Task ProfileImagePagesCount( - int pageSize - ) - { - // - int count = await DbContext.Avatars.CountAsync(); - int pagesCount = count / pageSize; - - // - if (count % pageSize > 0) - { - pagesCount++; - } - - // - return pagesCount; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Profile.cs - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Constants; -using xIdentityModels.Dtos; -using xIdentityModels.Models; -using xIdentityModels.Navigations; -using xModels.Dtos; -using xIds.Extensions; -using xIdentityModels.Extensions; -using xIdentityHelper; -using xIdentityHelper.Extensions; -using xDataService.Extensions; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Retrieve Actions ... - /// - /// Retrieve User Profile - /// - /// a user identifier - /// requested user's identifier - /// specify check requested user's identifier not empty - /// and throw exception if it is, default true - /// check a user can log in in system or not, default is true - /// check user is banned or not, default is true - /// an instance of XUserProfileDto - public async Task GetUserProfileAsync( - string userSelectByParam, - string requestedUserSelectByParam, - bool forceCheckRequestedUser = true, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Data Validation ... - if (forceCheckRequestedUser) - { - ValidationProvider.NotEmpty( - userSelectByParam, - requestedUserSelectByParam); - } - else - { - ValidationProvider.NotEmpty(userSelectByParam); - } - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - var isAdmin = false; - var isSameUser = false; - if (forceCheckRequestedUser && - !requestedUserSelectByParam.IsNullOrEmpty()) - { - // - var xRequestedUser = await ValidateUserExistsAndRetrieve( - requestedUserSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - isSameUser = xUser.Id == xRequestedUser.Id; - - // - var xRequestUserRoleNames = await GetRoleNamesAsync( - userSelectByParam: requestedUserSelectByParam, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - isAdmin = xRequestUserRoleNames.Contains(XUserRole.Admin.GetStringValue()); - } - - // - var roleNames = await GetRoleNamesAsync( - userSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - var xFriendshipInfo = - requestedUserSelectByParam.IsNullOrEmpty() - ? null - : await GetFriendshipInfo( - requestedUserSelectByParam, - userSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies - ); - - // - var result = xUser.ToXProfileDto( - isAdmin: isAdmin, - roles: roleNames, - isSameUser: isSameUser, - friendship: xFriendshipInfo, - profileConfig: Configuration.Policy.Profile - ); - - // - return result; - } - - /// - /// Retrieve a Collection of User Profiles - /// - /// a collection of user identifiers - /// requested user's identifier - /// specify check requested user's identifier not empty - /// and throw exception if it is, default true - /// check a user can log in in system or not, default is true - /// check user is banned or not, default is true - /// an collection of XUserProfileDto instances - public async Task> GetUserProfilesAsync( - ICollection ids, - string requestedUserSelectByParam, - bool forceCheckRequestedUser = true, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Data Validation ... - if (forceCheckRequestedUser) - { - ValidationProvider.NotEmpty(requestedUserSelectByParam); - } - ValidationProvider.NotZeroChilds(ids); - - // - var result = new List(); - foreach (var id in ids) - { - // - var xProfile = await GetUserProfileAsync( - id, - requestedUserSelectByParam, - checkIsBanned: checkIsBanned, - checkCanLoginPolicies: checkCanLoginPolicies, - forceCheckRequestedUser: forceCheckRequestedUser - ); - result.Add(xProfile); - } - - // - return result; - } - - /// - /// Query User Profiles - /// - /// requested user's identifier - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryUsers( - string requestedUserSelectByParam, - XQuery query - ) - { - // - // Validation ... - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - query = query.NormalizeQuery(DataConfiguration.ToXDataServiceConfig()); - - // - // Since in Resourceable Entities we have to Search on Locales - // we Must Implement Senario Custom ... - var totalEntities = GetUsersDbSet() - .ToList() - .Where(u => !u.ContainsUserSelectByParam(requestedUserSelectByParam)) - .Select(u => u.Id) - .ToList(); - - // - var items = await GetUserProfilesAsync( - totalEntities, - requestedUserSelectByParam, - checkIsBanned: false, - checkCanLoginPolicies: false, - forceCheckRequestedUser: false - ); - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Generate Result Object ... - // Query = query, - var result = new XQueryResult - { - Items = items, - Page = query.Page, - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - - /// - /// Query In Roles User Profiles - /// - /// requested user's identifier - /// an string which represent user role - /// how to filter results based on XQuery structure - /// if it's true the user must has exact role, otherwise top level users also listed, default is false - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryInRoleUsers( - string requestedUserSelectByParam, - string role, - XQuery query, - bool forceRole = false - ) - { - // - // Validation ... - if (query.IsNull() || role.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Role Exists ... - var isExistsRole = await IsRoleExistsAsync(role); - if (!isExistsRole) - { - XException.NotFound.Throw(); - } - - // - // Normalize ... - query = query.NormalizeQuery(DataConfiguration.ToXDataServiceConfig()); - - // - #region Select Users Based on Specific Roles ... - var selectedUsers = new List(); - var usersEnumerator = GetUsersDbSet(query.ContainsDetail).AsAsyncEnumerable(); - await - foreach (var user in usersEnumerator) - { - // - if (user.ContainsUserSelectByParam(requestedUserSelectByParam)) - { - continue; - } - - // - // Set Default Value is True ... - var isInRole = false; - - // - // if Force Role ... - if (forceRole) - { - isInRole = await UserManager.IsInRoleAsync(user, role); - } - else - { - // - // Select User Top Role ... - var userRoles = await GetRoleNamesAsync( - checkIsBanned: false, - userSelectByParam: user.Id, - checkCanLoginPolicies: false - ); - isInRole = userRoles.HasRolePermissions(role); - } - - // - if (isInRole) - { - selectedUsers.Add(user.Id); - } - } - #endregion - - // - var items = await GetUserProfilesAsync( - selectedUsers, - requestedUserSelectByParam, - checkIsBanned: false, - checkCanLoginPolicies: false, - forceCheckRequestedUser: false - ); - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Generate Result Object ... - // Query = query, - var result = new XQueryResult - { - Items = items, - Page = query.Page, - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - - /// - /// Query Specified User's Profile Images - /// - /// a user identifier - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XProfileImage - public async Task> QueryAvatars( - string userSelectByParam, - XQuery query - ) - { - // - // Validation ... - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - query = query.NormalizeQuery(DataConfiguration.ToXDataServiceConfig()); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: true, - checkIsBanned: true - ); - - // - var items = query.ContainsDetail ? - DbContext.Avatars - .Include(pf => pf.User) - .AsEnumerable() : - DbContext.Avatars - .AsEnumerable(); - items = items - .Where(pfi => pfi.UserId == xUser.Id); - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Generate Result Object ... - // Query = query, - var result = new XQueryResult - { - Items = items, - Page = query.Page, - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - - /// - /// Check specific user Confirmed Email or not - /// - /// a user identifier - /// a boolean value - public async Task IsConfirmedEmail( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - return xUser.EmailConfirmed; - } - - /// - /// Ceck specific user Confirmed Mobile or not - /// - /// a user identifier - /// a boolean value - public async Task IsConfirmedMobile( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - return xUser.PhoneNumberConfirmed; - } - #endregion - - // - #region Update Actions ... - /// - /// Update User Profile (FirstName/LastName/DateOfBirth) ... - /// - /// a user identifier - /// requested user's identifier - /// user update info, an instance of XProfileUpdateRequest - /// an instance of XUserProfileDto - public async Task ProfileUpdateAsync( - string userSelectByParam, - string requestedUserSelectByParam, - XProfileUpdateRequest model - ) - { - // - // Data Validation ... - ValidationProvider.NotEmpty( - userSelectByParam, - requestedUserSelectByParam); - ValidationProvider.NotNull(model); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - var xRequestedUser = await ValidateUserExistsAndRetrieve( - requestedUserSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - await ValidateUserForDangerousAction(xUser, xRequestedUser); - - // - // FirstName ... - if (!model.FirstName.IsNullOrEmpty()) - { - xUser.FirstName = model.FirstName; - } - - // - // Last Name ... - if (!model.LastName.IsNullOrEmpty()) - { - xUser.LastName = model.LastName; - } - - // - // Date of Birth ... - if (model.DateOfBirth.HasValue) - { - xUser.DateOfBirth = model.DateOfBirth.Value; - } - - // - // Bio ... - xUser.Bio = model.Bio; - - // - // Cover Image ... - xUser.CoverImage = model.CoverImage; - - // - // Open To Search ... - xUser.OpenToSearch = model.OpenToSearch; - - // - var updateResult = await UpdateUserAsync(xUser); - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - var result = await GetUserProfileAsync(userSelectByParam, requestedUserSelectByParam); - return result; - } - - /// - /// Update User Profile - /// - /// a user identifier - /// requested user's identifier - /// user update info, an instance of XProfileUpdateRequest - /// an instance of XUserProfileDto - public async Task FullProfileUpdateAsync( - string userSelectByParam, - string requestedUserSelectByParam, - XProfileUpdateRequest model - ) - { - // - // Data Validation ... - ValidationProvider.NotEmpty( - userSelectByParam, - requestedUserSelectByParam); - ValidationProvider.NotNull(model); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - var xRequestedUser = await ValidateUserExistsAndRetrieve( - requestedUserSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - await ValidateUserForDangerousAction(xUser, xRequestedUser); - - // - #region Fill User with Models Value ... - // - // FirstName ... - xUser.FirstName = !model.FirstName.IsNullOrEmpty() ? - model.FirstName : - xUser.FirstName; - // - // LastName ... - xUser.LastName = !model.LastName.IsNullOrEmpty() ? - model.LastName : - xUser.LastName; - - // - // Email ... - xUser.Email = !model.Email.IsNullOrEmpty() ? - model.Email : - xUser.Email; - - // - // EmailConfirmed ... - if (model.EmailConfirmed.HasValue) - { - xUser.EmailConfirmed = model.EmailConfirmed.Value; - } - - // - // PhoneNumber ... - xUser.PhoneNumber = !model.PhoneNumber.IsNullOrEmpty() ? - model.PhoneNumber : - xUser.PhoneNumber; - - // - // PhoneNumberConfirmed ,,, - if (model.PhoneNumberConfirmed.HasValue) - { - xUser.PhoneNumberConfirmed = model.PhoneNumberConfirmed.Value; - } - - // - // DateOfBirth ... - if (model.DateOfBirth.HasValue) - { - xUser.DateOfBirth = model.DateOfBirth.Value; - } - - // - // CreationDate ... - if (model.CreationDate.HasValue) - { - xUser.CreationDate = model.CreationDate.Value; - } - - // - // LastLogin ... - if (model.LastLogin.HasValue) - { - xUser.LastLogin = model.LastLogin.Value; - } - - // - // Avatar ... - xUser.Avatar = !model.Avatar.IsNullOrEmpty() ? - model.Avatar : - xUser.Avatar; - - // - // Gender ... - if (model.Gender.HasValue) - { - xUser.Gender = model.Gender.Value; - } - - // - // IsEnable ... - if (model.IsEnable.HasValue) - { - xUser.IsEnable = model.IsEnable.Value; - } - - // - // IsBanned ... - if (model.IsBanned.HasValue) - { - xUser.IsBanned = model.IsBanned.Value; - } - - // - // Bio ... - xUser.Bio = model.Bio; - - // - // Cover Image ... - xUser.CoverImage = model.CoverImage; - - // - // Open To Search ... - xUser.OpenToSearch = model.OpenToSearch; - #endregion - - // - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // Handle Roles ... - - // - // Remove User from All Roles ... - if (xUser.Roles.HasChild()) - { - // - var roleNames = await GetRoleNamesAsync( - xUser.Id, - checkIsBanned: false, - checkCanLoginPolicies: false - ); - - // - foreach (var role in roleNames) - { - // - var isRoleExists = await IsRoleExistsAsync(role); - if (isRoleExists) - { - // - var isInRole = await UserManager.IsInRoleAsync(xUser, role); - if (!isInRole) - { - // - var removeRoleResult = await UserManager.RemoveFromRoleAsync(xUser, role); - if (!removeRoleResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - } - } - } - } - - // - // Check Roles and Add to Exists ... - if (model.Roles.HasChild()) - { - // - // Check Exists Roles for Add ... - foreach (var role in model.Roles) - { - // - var isRoleExists = await IsRoleExistsAsync(role); - if (isRoleExists) - { - // - var isInRole = await UserManager.IsInRoleAsync(xUser, role); - if (!isInRole) - { - // - var addToRoleResult = await UserManager.AddToRoleAsync(xUser, role); - if (!addToRoleResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - } - } - } - } - - // - var result = await GetUserProfileAsync( - userSelectByParam, - requestedUserSelectByParam, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - return result; - } - #endregion - - // - #region Request For Actions ... - /// - /// Request Mobile Confirm - /// - /// specify destination language - /// an instance of XDevice - /// a user identifier - /// user's password - /// mobile number which need to confirm - /// an instance of XActionResponse - public async Task RequestConfirmMobile( - string lang, - XDevice device, - string userSelectByParam, - string password, - string mobileNumber = null - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - userSelectByParam, - password) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - await ValidateDeviceForActions(device); - - // - // Prepare Request Context ... - var context = new XActionRequestContext - { - Lang = lang, - Device = device, - MobileNumber = mobileNumber - }; - - // - // Validate and Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - context.UserName = user.UserName; - - // - await ValidateUserAndPassword( - userSelectByParam, - password, - false, - XException.ActionFailed.ToException()); - - // - ValidationProvider.MobileNumber(user.PhoneNumber); - if (!mobileNumber.IsNullOrEmpty() && - user.PhoneNumber == mobileNumber && - user.PhoneNumberConfirmed) - { - XException.MobileInUsed.Throw(); - } - - // - if (mobileNumber.IsNullOrEmpty()) - { - mobileNumber = user.PhoneNumber; - } - - // - // Remove All Prevoius Requests ... - await HandleRemoveExistsTokens(user.Id); - - // - // Prepare New Token Result , - // by Requesting an Action ... - var request = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.RequestMobileVerificationCode, - context, - forceRenewToken: true - ); - - // - Logger.LogInformation($"ActionRequest: {request.ToJSON()}"); - - // - // Call Confirm Method of Registration ... - var result = await RequestMobileVerificationCode( - lang, - device, - request.Token, - mobileNumber, - checkMobileInUse: false); - - // - return result; - } - - /// - /// Request Email Confirma - /// - /// specify destination language - /// an instance of XDevice - /// a user identifier - /// user's password - /// email address which need to confirm - /// an instance of XActionResponse - public async Task RequestConfirmEmail( - string lang, - XDevice device, - string userSelectByParam, - string password, - string emailAddress = null - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - userSelectByParam, - password) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - await ValidateDeviceForActions(device); - - // - // Prepare Request Context ... - var context = new XActionRequestContext - { - Lang = lang, - Device = device, - Email = emailAddress - }; - - // - // Validate and Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - context.UserName = user.UserName; - - // - // Remove All Prevoius Requests ... - await HandleRemoveExistsTokens(user.Id); - - // - await ValidateUserAndPassword( - userSelectByParam, - password, - false, - XException.ActionFailed.ToException()); - - // - ValidationProvider.EmailAddress(user.Email); - if (!emailAddress.IsNullOrEmpty() && - user.Email == emailAddress && - user.EmailConfirmed) - { - XException.EmailInUsed.Throw(); - } - - // - if (emailAddress.IsNullOrEmpty()) - { - emailAddress = user.Email; - context.Email = user.Email; - } - - // - // Prepare New Token Result , - // by Requesting an Action ... - var request = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.RequestEmailVerificationCode, - context, - forceRenewToken: true - ); - - // - // Call Confirm Method of Registration ... - var result = await RequestEmailVerificationCode( - lang, - device, - request.Token, - emailAddress, - checkEmailInUse: false); - - // - return result; - } - - /// - /// Request Reset Password - /// - /// specify destination language - /// an instance of XDevice - /// a user identifier - /// redirection url - /// an instance of XActionResponse - public async Task RequestResetPassword( - string lang, - XDevice device, - string userSelectByParam, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - userSelectByParam, - returnUrl) - .AddNotNull(device) - .AddUrl(returnUrl) - .ValidateGroupAsync(); - - // - await ValidateDeviceForActions(device); - - // - // Validate and Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: true, - checkIsBanned: true); - - // - // Prepare Request Context ... - var context = new XActionRequestContext - { - Lang = lang, - Device = device, - Email = user.Email, - UserName = user.UserName - }; - - // - // Remove All Prevoius Requests ... - await HandleCleanUserTokens(user); - - // - // Prepare New Token Result , - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - user.Email, - XAction.RequestResetPassword, - context - ); - - // - // Prepare Message ... - var xMessage = GetResetPasswordMessage( - lang, - user.Email, - result.Token, - returnUrl); - - // - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - - // - return result; - } - - /// - /// Request Registration Confrirm - /// - /// specify destination language - /// an instance of XDevice - /// a user identifier - /// user's password - /// redirection url - /// - public async Task RequestConfirmRegistration( - string lang, - XDevice device, - string userSelectByParam, - string password, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - userSelectByParam, - password, - returnUrl) - .AddNotNull(device) - .AddUrl(returnUrl) - .ValidateGroupAsync(); - - // - // Validate user and Retrieve it ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: true, - ignoreDisabledUser: true); - - // - // Prepare Request Context ... - var context = new XActionRequestContext - { - Lang = lang, - Device = device, - Email = user.Email - }; - - // - await ValidateUserAndPassword( - userSelectByParam, - password, - false, - XException.ActionFailed.ToException()); - - // - // Remove All Prevoius Requests ... - await HandleRemoveExistsTokens(user.Id); - - // - // Prepare New Token Result , - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - user.Email, - XAction.Finish, - context - ); - - // - // Prepare XMessage Instance ... - var xMessage = GetRegistrationConfirmMessage( - lang, - user.Email, - result.Token, - returnUrl); - - // - // Send Message ... - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - #endregion - - // - #region Password Actions ... - /// - /// Change Password - /// - /// specify destination language - /// an instance of XDevice - /// a user identifier - /// user's password - /// user's new password - /// redirection url - /// - public async Task ChangePassword( - string lang, - XDevice device, - string userSelectByParam, - string password, - string newPassword, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - userSelectByParam, - password, - newPassword, - returnUrl) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Password Unique ... - if (password == newPassword) - { - XException.PasswordsSame.Throw(); - } - - // - // Validate and Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: true, - checkIsBanned: true); - - // - await ValidateUserAndPassword( - userSelectByParam, - password); - - // - // Check Password Policies ... - await ValidatePasswordPolicies(user, newPassword); - - // - // Clean All User Tokens ... - await HandleCleanUserTokens(user); - - // - // Try to Change User Password ... - var passwordResetResult = await UserManager - .ChangePasswordAsync( - user, - password, - newPassword); - - // - // Check Result ... - if (!passwordResetResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // Prepare Message ... - var xMessage = GetPasswordChangedMessage( - lang, - user.Email, - returnUrl, - throwException: false - ); - - // - // Send Message ... - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - - /// - /// Reset User Password - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// user's new password - /// redirection url - /// - public async Task ResetPassword( - string lang, - XDevice device, - string actionToken, - string newPassword, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - actionToken, - newPassword, - returnUrl) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - - // - // Get User Identifier ... - var userSelectByParam = GetUserSelectByParam(request); - - // - // Validate and Retrieve User ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: true, - checkIsBanned: true); - - // - // Check Password Policies ... - await ValidatePasswordPolicies(user, newPassword); - - // - // Clean All User Tokens ... - await HandleCleanUserTokens(user); - - // - // Try to Remove User Password ... - var removePasswordResult = await UserManager.RemovePasswordAsync(user); - if (!removePasswordResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // try to Add New Password ... - var passwordResetResult = await UserManager.AddPasswordAsync(user, newPassword); - if (!passwordResetResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // Prepare Message ... - var xMessage = GetPasswordChangedMessage( - lang, - user.Email, - returnUrl); - - // - // Send Message ... - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - #endregion - - // - #region Profile Image Actions ... - /// - /// Add Profile Image to a User - /// - /// a user identifier - /// an specific File to upload, IFormFile - /// an instance of XUserProfileDto - public async Task AddAvatar( - string userSelectByParam, - IFormFile file - ) - { - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - // Handle Saving File and Attach it to User ... - var saveResult = await StorageProvider.HandleProfileImageSave(file); - - // - var xProfileImage = new XProfileImage - { - UserId = xUser.Id, - Name = saveResult.FileName, - Path = saveResult.FilePath, - Thumb = saveResult.Thmbnail, - ThumbPath = saveResult.ThmbnailPath, - CreationDate = DateTime.UtcNow - }; - - // - xUser.Avatars.Add(xProfileImage); - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - xUser.Avatar = xProfileImage.ThumbPath; - updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - var result = await GetUserProfileAsync(userSelectByParam, userSelectByParam); - return result; - } - - /// - /// Add a Collection of Profile Images to a User - /// - /// a user identifier - /// a collection of Files to upload, IFormFileCollection - /// an instance of XUserProfileDto - public async Task AddAvatars( - string userSelectByParam, - IFormFileCollection files - ) - { - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - foreach (var file in files) - { - // - // Handle Saving File and Attach it to User ... - var saveResult = await StorageProvider.HandleProfileImageSave(file); - - // - var xProfileImage = new XProfileImage - { - UserId = xUser.Id, - Name = saveResult.FileName, - Path = saveResult.FilePath, - Thumb = saveResult.Thmbnail, - ThumbPath = saveResult.ThmbnailPath, - CreationDate = DateTime.UtcNow - }; - - // - xUser.Avatars.Add(xProfileImage); - } - - // - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - var result = await GetUserProfileAsync(userSelectByParam, userSelectByParam); - return result; - } - - /// - /// Set Specific Profie Image as Current Profile Image - /// - /// a user identifier - /// an integer which reperesent AvatarId to set as current Avatar - /// an instance of XUserProfileDto - public async Task SetAvatar( - string userSelectByParam, - int id - ) - { - // - ValidationProvider.NotEmpty(userSelectByParam); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - var xProfileImage = xUser.Avatars.FirstOrDefault(pf => pf.Id == id); - if (xProfileImage.IsNull()) - { - XException.NotFound.Throw(); - } - - // - xUser.Avatar = xProfileImage.ThumbPath; - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (!updateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - var result = await GetUserProfileAsync(userSelectByParam, userSelectByParam); - return result; - } - - /// - /// Remove a Collection of User's Profile Images - /// - /// a user identifier - /// a comma seperated list of avatarIds to remove - /// an instance of XUserProfileDto - public async Task RemoveAvatar( - string userSelectByParam, - ICollection ids - ) - { - // - ValidationProvider.NotEmpty(userSelectByParam); - - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - var xProfileImages = xUser.Avatars - .Where(pf => ids.Contains(pf.Id)); - if (xProfileImages.HasChild()) - { - // - xUser.Avatars = xUser.Avatars - .Except(xProfileImages) - .ToList(); - - // - // Creat a List of Physical Files to Remove ... - var xFilePathsForRemove = xProfileImages.Select(pf => pf.Thumb).ToList(); - xFilePathsForRemove.AddRange(xProfileImages.Select(pf => pf.Name)); - - // - StorageProvider.DeleteFiles( - xFilePathsForRemove, - forceFileExists: false); - - // - var isCurrentProfileImage = xProfileImages.Any(pfi => pfi.ThumbPath == xUser.Avatar); - if (isCurrentProfileImage) - { - xUser.Avatar = ""; - } - - // - await UpdateUserAsync(xUser); - } - - // - var result = await GetUserProfileAsync(userSelectByParam, userSelectByParam); - return result; - } - #endregion - - // - #region Confirmations ... - /// - /// Confirm Registration - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// redirection url - /// - public async Task ConfirmRegistration( - string lang, - XDevice device, - string actionToken, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - actionToken, - returnUrl) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - if (request.Action != XAction.Finish) - { - XException.ActionFailed.Throw(); - } - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam( - request, - forceNotNull: true); - - // - // Validate user and Retrieve it ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - ignoreDisabledUser: true, - checkIsBanned: true); - - // - // Make User Enabled ... - var xMessage = GetRegistrationFinishedMessage( - lang, - user.Email, - returnUrl); - - // - user.IsEnable = true; - user.EmailConfirmed = true; - - // - await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - // Remove Token ... - await RemoveTokenByHash(actionToken); - - // - // Remove All Prevoius Requests ... - await HandleRemoveExistsTokens(user.Id); - - // - await RemoveVerificationCodeRequestByDevice(device); - - // - // Send Mail ... - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - - /// - /// Confirm Mobile Number - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// recieved verification code - /// an instance of XActionResponse - public async Task ConfirmMobileNumber( - string lang, - XDevice device, - string actionToken, - string verificationCode - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(lang, actionToken, verificationCode) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - ValidationProvider.MobileNumber(request.Context.MobileNumber); - - // - // Validate two Device Must Same ... - ValidateRequestAndGiveDevices(device, request.Context.Device); - - // - // Check XActionRequest Action Must be Request Mobile Validation ... - if (request.Action != XAction.RequestMobileVerificationCode) - { - XException.InvalidData.Throw(); - } - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam(request); - - // - // since device must Requested before, - // Retrieve XVerification instance by Verification Code from Db - // and Validate it ... - XVerificationRequest xVerificationRequest = await ValidateAndRetrieveVerificationRequest(verificationCode); - - // - // Check User Added To Db or Not ... - // var isUserExists = await IsUserExistsAsync(userSelectByParam); - var isAddedUser = !request.Context.UserId.IsNullOrEmpty(); - if (isAddedUser) - { - // - // Validate User Exists and Retireve User Object ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - // Update Exists User's Mobile Confirmation ... - user.PhoneNumberConfirmed = true; - - // - // Save Changes to Db ... - await UpdateUserAsync(user, checkCanLoginPolicies: false, checkIsBanned: false); - - // - request.Context.UserId = user.Id; - } - - // - // Update Request Context MobileNumber Verification Code - // and it's Confirmation Status ... - request.Context.MobileVerificationCode = verificationCode; - request.Context.MobileVerified = true; - - // - // Prepare New Token Result , - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.ConfirmMobileNumber, - request.Context, - forceCheckUserExists: isAddedUser - ); - - // - // Remove Previous Token ... - await RemoveTokenByHash(actionToken); - - try - { - // - // Remove XVerificationRequest instance from Db ... - await RemoveVerificationRequest(verificationCode); - } - catch { } - - // - // Return Result ... - return result; - } - - /// - /// Confirm Email Address - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// recieved verification code - /// an instance of XActionResponse - public async Task ConfirmEmailAddress( - string lang, - XDevice device, - string actionToken, - string verificationCode - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(lang, actionToken, verificationCode) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - ValidationProvider.EmailAddress(request.Context.Email); - - // - // Validate two Device Must Same ... - ValidateRequestAndGiveDevices(device, request.Context.Device); - - // - // Check XActionRequest Action Must be Request Mobile Validation ... - if (request.Action != XAction.RequestEmailVerificationCode) - { - XException.InvalidData.Throw(); - } - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam(request); - - // - // since device must Requested before, - // Retrieve XVerification instance by Verification Code from Db - // and Validate it ... - XVerificationRequest xVerificationRequest = await ValidateAndRetrieveVerificationRequest(verificationCode); - - // - // Check User Added To Db or Not ... - var isAddedUser = !request.Context.UserId.IsNullOrEmpty(); - if (isAddedUser) - { - // - // Validate User Exists and Retireve User Object ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - // Update Exists User's Email Confirmation ... - user.EmailConfirmed = true; - - // - // Save Changes to Db ... - await UpdateUserAsync(user, checkCanLoginPolicies: false, checkIsBanned: false); - - // - request.Context.UserId = user.Id; - } - - // - // Update Request Context Email Address Verification Code - // and it's Confirmation Status ... - request.Context.EmailVerificationCode = verificationCode; - request.Context.EmailVerified = true; - - // - // Prepare New Token Result , - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.ConfirmEmailAddress, - request.Context, - forceCheckUserExists: isAddedUser - ); - - // - // Remove Previous Token ... - await RemoveTokenByHash(actionToken); - - // - // Remove XVerificationRequest instance from Db ... - await RemoveVerificationRequest(verificationCode); - - // - // Return Result ... - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Query.cs - -using System.Linq; -using System.Threading.Tasks; -using xCommons.Extensions; -using xDataService.Extensions; -using xExceptions.Constants; -using xIdentityModels.Extensions; -using xIds.Extensions; -using xModels.Dtos; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - /// - /// Retrieve Users as Query Model for Query Service ... - /// - /// - /// - /// - /// - /// - public async Task> QueryUsers( - string requestedUserSelectByParam, - XQuery query, - string role = null, - bool forceRole = false - ) - { - // - // Validation ... - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - query = query.NormalizeQuery(DataConfiguration.ToXDataServiceConfig()); - - // - // Since in Resourceable Entities we have to Search on Locales - // we Must Implement Senario Custom ... - var items = GetUsersDbSet() - .ToList() - .Where(u => !u.ContainsUserSelectByParam(requestedUserSelectByParam)) - .ToList() - .AsEnumerable(); - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Generate Result Object ... - // Query = query, - var result = new XQueryResult - { - Items = items - .Select(u => u.Id), - Page = query.Page, - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return await Task.Run(() => result); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Registration.cs - -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Constants; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Registration Actions ... - /// - /// Invite a User to Register on Dashboard - /// - /// specify destination language - /// an instance of XDevice - /// which email address is going to invite - /// return url for invitation user to redirect - /// an instance of XActionResponse - public async Task InviteUser( - string lang, - XDevice device, - string email, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - email, - returnUrl - ) - .AddNotNull(device) - .AddEmailAddress(email) - .ValidateGroupAsync(); - - // - // Check Email is Unique ... - await ValidateUserNotExists(email); - - // - // Get Request Result ... - var result = await ActionRequest( - lang, - device, - email, - XAction.Invite, - forceCheckContext: false, - forceCheckUserExists: false); - - // - // Prepare Propper Message ... - var xMessage = GetUserInviteMessage(lang, email, result.Token, returnUrl); - - // - // Send Message ... - try - { - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - - // - // Send Result ... - return result; - } - - /// - /// Recieve some Basic Informations and Start Registration Proccess - /// if they Valid - /// - /// Registration Proccess Starts with Invoking this Action - /// - /// specify destination language - /// an instance of XDevice - /// optional, if user invited, this is the invitation token - /// user's FirstName - /// user's LastName - /// user's dob date - /// user's Mobile Number - /// user's Email address - /// an instance of XActionResponse - public async Task RequestRegistration( - string lang, - XDevice device, - string invitationHash, - string firstName, - string lastName, - DateTime dateOfBirth, - string mobileNumber = null, - string emailAddress = null - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - firstName, - lastName - ) - .AddNotNull( - device, - dateOfBirth - ) - .ValidateGroupAsync(); - - // - // Validate Mobile Number if Exists ... - if (!mobileNumber.IsNullOrEmpty()) - { - // - ValidationProvider.MobileNumber(mobileNumber); - - // - // Check Mobile is Uniqsue ... - await ValidateUserNotExists(mobileNumber); - } - - // - // Validate Email Address if Exists ... - if (!emailAddress.IsNullOrEmpty()) - { - // - ValidationProvider.EmailAddress(emailAddress); - - // - // Check Email is Unique ... - await ValidateUserNotExists(emailAddress); - } - - // - // Get Related Token and Validate it and - // Check Related Configurations ... - await ValidateInvitationHash(invitationHash); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Validate DateOfBirth ... - ValidateDateOfBirth(dateOfBirth); - - // - // Define Empty Objects for Using ... - var userSelectByParam = ""; - var context = new XActionRequestContext(); - // - context.Lang = lang; - context.Device = device; - context.LastName = lastName; - context.FirstName = firstName; - context.DateOfBirth = dateOfBirth; - context.MobileNumber = mobileNumber ?? ""; - context.Email = !emailAddress.IsNullOrEmpty() ? emailAddress.ToNormalString() : ""; - - // - userSelectByParam = GetUserSelectByParam(context); - - // - // Token Data Parsing ... - if (!invitationHash.IsNullOrEmpty()) - { - // - // Get Related Token, Validate it and Parse Contains - // XAction Request and Validate the Request itself and - // Return it ... - var inviteRequest = await ValidateAndParseActionHash(invitationHash); - - // - // Extract User Select By Param and Type ... - userSelectByParam = GetUserSelectByParam(inviteRequest); - var userSelectBy = GetUserSelectByType(userSelectByParam); - - // - // Check Invitation Only done with Email Address ... - if (userSelectBy != XUserSelectBy.Email) - { - XException.InvalidData.Throw(); - } - - // - // Check Invited Email and Given Email to be Same ... - if (emailAddress.IsNullOrEmpty() || - (!emailAddress.IsNullOrEmpty() && - !emailAddress.IsValidEmail())) - { - XException.InvalidEmailAddress.Throw(); - } - var isSameEmail = inviteRequest.Context.Email.ToNormalString() == emailAddress.ToNormalString(); - if (!isSameEmail) - { - XException.EmailsSame.Throw(); - } - - // - // Update Context Email for Request Action ... - context.Email = userSelectByParam.ToNormalString(); - context.EmailVerified = true; - } - - // - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.Registration, - context, - forceCheckUserExists: false - ); - - // - // Remove Invitation Token ... - if (!invitationHash.IsNullOrEmpty()) - { - await RemoveTokenByHash(invitationHash); - } - - // - // Return Result ... - return result; - } - - /// - /// Add User Account Info - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// user name - /// assigne password - /// an instance of XActionResponse - public async Task AddAcountInfo( - string lang, - XDevice device, - string actionToken, - string userName, - string password - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty( - lang, - actionToken, - userName, - password) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Validate a UserSelector is Available or not ... - await ValidateCanRegister(userName); - - // - // Check UserName is Unique ... - await ValidateUserNotExists(userName); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - - // - // Validate Requeired Data for Register User must be in Action Context ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull( - request.Context, - request.Context.Device, - request.Context.DateOfBirth) - .AddNotEmpty( - request.Context.Email, - request.Context.MobileNumber, - request.Context.FirstName, - request.Context.LastName) - .AddEmailAddress(request.Context.Email) - .AddMobileNumber(request.Context.MobileNumber) - .ValidateGroupAsync(); - - // - // Validate two Device Must Same ... - ValidateRequestAndGivenDevices(device, request.Context.Device); - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam(request); - - // - // Validate Request Pointer User doesn't Exists ... - await ValidateUserNotExists(userSelectByParam); - - // - // Create an Empty Instance of XUser ... - var xUser = new XUser(); - - // - // Start Filling User Fields ... - xUser.UserName = userName; - xUser.Email = request.Context.Email; - xUser.PhoneNumber = request.Context.MobileNumber; - - // - xUser.FirstName = request.Context.FirstName; - xUser.LastName = request.Context.LastName; - xUser.DateOfBirth = request.Context.DateOfBirth; - - // - xUser.EmailConfirmed = request.Context.EmailVerified; - xUser.PhoneNumberConfirmed = request.Context.MobileVerified; - - // - xUser.CreationDate = DateTime.UtcNow; - xUser.LastLogin = null; - - // - #region Handling New User IsEnable State ... - // - // By Default New Users will Enables ... - xUser.IsEnable = true; - xUser.IsBanned = false; - - // - // Check Auto Enable Users ... - if (Configuration.RequireRegistrationConfirm) - { - xUser.IsEnable = false; - } - - // - // Check Auto Confirm Email Users ... - if (Configuration.AutoConfirmNewUsersEmail) - { - xUser.EmailConfirmed = true; - } - #endregion - - // - // Check Auto Confirm Phone Number Users ... - if (Configuration.AutoConfirmNewUsersPhoneNumber) - { - xUser.PhoneNumberConfirmed = true; - } - - // - // Validating given Password ... - await ValidatePasswordPolicies(xUser, password); - - // - // Now add new User to Database ... - var createUserResult = await CreateUserAsync(xUser, password); - if (!createUserResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // Update Request UserId Value ... - request.Context.UserId = xUser.Id; - request.Context.UserName = xUser.UserName; - - // - #region Handling New User Role ... - // - // Now Try to Assign Default User role ... - var isContainsDefaultUserRole = !Configuration.NewUsersRole.IsNullOrEmpty(); - if (isContainsDefaultUserRole) - { - // - var newUserRoleName = Configuration.NewUsersRole; - var isNewUserRoleExists = await IsRoleExistsAsync(newUserRoleName); - // - // Make Sure New User role Exists ... - if (!isNewUserRoleExists) - { - // - // Create Default Roles ... - await CreateIdentityRoles(); - } - - // - // Assign User to Role ... - var assignNewUserToRoleResult = await AddUserToRoleAsync(xUser, newUserRoleName); - if (!assignNewUserToRoleResult.Succeeded) - { - // - // Delete User if Role Assignment Faild ... - await UserManager.DeleteAsync(xUser); - - // - // Thrown ActionFailed Error ... - XException.ActionFailed.Throw(); - } - } - #endregion - - // - #region Handle Profile Image ... - // Save and Attach Profile Image to User if it's Added Before ... - if (!request.Context.UserId.IsNullOrEmpty() && - !request.Context.Thubmnail.IsNull()) - { - // - xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - // Handle Saving File and Attach it to User ... - var saveResult = await StorageProvider - .HandleProfileImageSave(request.Context.Thubmnail); - - // - var xProfileImage = new XProfileImage - { - UserId = request.Context.UserId, - Name = saveResult.FileName, - Path = saveResult.FilePath, - Thumb = saveResult.Thmbnail, - ThumbPath = saveResult.ThmbnailPath - }; - - // - xUser.Avatars.Add(xProfileImage); - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (updateResult.Succeeded) - { - // - xUser.Avatar = xProfileImage.ThumbPath; - await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - } - } - #endregion - - // - // Handle Attaching User device ... - var xUserDevice = await AddUserRelatedDevice( - userSelectByParam, - device, - checkCanLoginPolicies: false); - - // - // Prepare New Token Result Resource, - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.Finish, - request.Context, - forceCheckUserExists: false - ); - - // - // Remove Previous Token ... - await RemoveTokenByHash(actionToken); - - // - // Return Result ... - return result; - } - - /// - /// Attach Profile Image - /// - /// a token which approved user action - /// an instance of IFormFile for user's Avatar - /// an instance of XActionResponse - public async Task AttachProfileImage( - string actionToken, - IFormFile file - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(actionToken) - .AddNotNull(file) - .ValidateGroupAsync(); - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam(request); - if (userSelectByParam.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - // Validate Given FormFile as Profile Image ... - StorageProvider.ValidateProfileImage(file); - - // - request.Context.Thubmnail = file; - - // - // Save and Attach Profile Image to User if it's Added Before ... - if (!request.Context.UserId.IsNullOrEmpty()) - { - // - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - exception: XException.NotFound.ToException() - ); - - // - // Handle Saving File and Attach it to User ... - var saveResult = await StorageProvider.HandleProfileImageSave(file); - - // - var xProfileImage = new XProfileImage - { - UserId = request.Context.UserId, - Name = saveResult.FileName, - Path = saveResult.FilePath, - Thumb = saveResult.Thmbnail, - ThumbPath = saveResult.ThmbnailPath - }; - - // - xUser.Avatars.Add(xProfileImage); - var updateResult = await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - - // - if (updateResult.Succeeded) - { - // - xUser.Avatar = xProfileImage.ThumbPath; - await UpdateUserAsync( - xUser, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - } - } - - // - // Remove Invitation Token ... - if (!actionToken.IsNullOrEmpty()) - { - await RemoveTokenByHash(actionToken); - } - - // - var result = await ActionRequest( - request.Context.Lang, - request.Context.Device, - userSelectByParam, - XAction.ProfileAction, - request.Context, - forceCheckUserExists: false - ); - - // - // Return Result ... - return result; - } - - /// - /// Finishing Registration - /// - /// specify destination language - /// an instance of XDevice - /// user identifier - /// assigne password - /// return url for invitation user to redirect - /// - public async Task FinishRegistration( - string lang, - XDevice device, - string userSelectByParam, - string password, - string returnUrl - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(lang, userSelectByParam, password, returnUrl) - .AddNotNull(device) - .AddUrl(returnUrl) - .ValidateGroupAsync(); - - // - // Validate User Exists And Retrieve it ... - var xUser = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false, - ignoreDisabledUser: true, - forceAdmin: false - ); - - // - #region Handling New User Email Notification Senario ... - // - // Here we Check if User is Enable and Approved Email - // send RegisteredMsg and if User is not Enable and - // Verify Registration value in Configuration is True - // send Verify Registration mail to user and handle it ... - if (Configuration.RequireRegistrationConfirm) - { - // - if (xUser.IsEnable) - { - // - // Send Registration Finished Message ... - // since in this step we need to prevent errors from - // going forward. add this try catch here ... - try - { - // - var xMessage = GetRegistrationFinishedMessage(lang, xUser.Email, returnUrl); - - // - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - else - { - // - // Send Registration Confirm Message ... - // since in this step we need to prevent errors from - // going forward. add this try catch here ... - try - { - // - var request = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.Finish, - forceCheckContext: false, - forceCheckUserExists: true); - - // - var xMessage = GetRegistrationConfirmMessage(lang, xUser.Email, request.Token, returnUrl); - - // - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - } - - // // - // await RemoveTokenByDevice (device); - #endregion - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Request.cs - -using System.Collections.Generic; -using System.Threading.Tasks; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Constants; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Action Handlers ... - /// - /// Request an Action - /// - /// specify destination language - /// an instance of XDevice - /// specified user's identifier - /// a member of XAction which represent Action Step - /// an instance of XActionRequestContext which provides required informations for specified step - /// specify checking context, default is false - /// specify check user exists, default is true - /// specify check user and device relation, default is false - /// specifies force renew Action Token if it's expired, default is false - /// an instance of XActionResponse - private async Task ActionRequest( - string lang, - XDevice device, - string userSelectByParam, - XAction step, - XActionRequestContext context = null, - bool forceCheckContext = false, - bool forceCheckUserExists = true, - bool forceCheckUserDevice = false, - bool forceRenewToken = false - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(lang); - ValidationProvider.NotNull(device); - - // - // Check Device not Banned ... - await ValidateDeviceForActions(device); - - // - // Check User Exists and Device Relation ... - if (forceCheckUserExists) - { - if (forceCheckUserDevice) - { - // - if (context.Device != null && - !device.IsSameAs(context.Device)) - { - XException.InvalidDevice.Throw(); - } - - // - await ValidateUserAndDeviceRelation(userSelectByParam, device); - } - else - { - await ValidateUserExistsAsync(userSelectByParam); - } - } - - // - XToken xToken = null; - XActionResponse result = null; - XActionRequestToken xRequest = null; - - // - var isExists = false; - var forceUserSelectByParamNotEmpty = true; - switch (step) - { - case XAction.Registration: - // - forceUserSelectByParamNotEmpty = false; - isExists = await IsTokenExistsByDeviceAndType(device, step); - - // - if (isExists) - { - xToken = await ValidateAndRetieveTokenByDeviceAndType(device, step); - } - break; - - default: - // - isExists = await IsTokenExistsByUserAndType(userSelectByParam, step); - - // - if (isExists) - { - xToken = await ValidateAndRetieveTokenByUserAndType(userSelectByParam, step); - } - break; - } - - // - if (isExists) - { - // - var isValidToken = IsValidToken(xToken.Token); - if (!isValidToken && !forceRenewToken) - { - switch (step) - { - case XAction.Registration: - case XAction.Invite: - forceRenewToken = true; - break; - - default: - throw XException.InvalidToken.ToException(); - } - } - - // - if (!isValidToken && forceRenewToken) - { - await ValidateAndHandleToken(xToken.Token); - return await ActionRequest( - lang, - device, - userSelectByParam, - step, - context, - forceCheckContext, - forceCheckUserExists, - forceCheckUserDevice, - forceRenewToken); - } - - // - xRequest = ValidateAndParseActionToken(xToken.Token); - - // - // Check Exists Context ... - if (forceCheckContext) - { - // - var isSameContext = xRequest.Context.IsSameAs(context); - if (!isSameContext) - { - XException.InvalidData.Throw(); - } - } - } - else - { - // - if (context != null) - { - // - var contextUserSelectByParam = GetUserSelectByParam( - context, - false, - new List { - XUserSelectBy.ID, - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - var contextLang = context.Lang; - var contextDevice = context.Device; - - // - // prevent from issues on Registration Request ... - if (forceUserSelectByParamNotEmpty) - { - var userSelectByType = GetUserSelectByType(userSelectByParam); - var contextUserSelectByType = GetUserSelectByType(contextUserSelectByParam); - if (contextUserSelectByType != userSelectByType) - { - // - var excludesList = GenerateUserSelectByExcludes(new List { userSelectByType }); - - // - contextUserSelectByParam = GetUserSelectByParam(context, false, excludesList); - } - } - - // - // Fix Device Not Same on Invitation and Request - if (step == XAction.Registration) - { - // - context.Device = device; - contextDevice = context.Device; - } - - // - // Validate Context Data must be Same as Request Data ... - if ((!contextUserSelectByParam.IsNullOrEmpty() && - contextUserSelectByParam != userSelectByParam) || - (!contextLang.IsNullOrEmpty() && - contextLang != lang) || - (contextDevice != null && - !contextDevice.IsSameAs(device))) - { - XException.InvalidData.Throw(); - } - } - else - { - // - context = new XActionRequestContext - { - Lang = lang, - Device = device - }; - - // - // Add Content ... - var userSelectByType = GetUserSelectByType( - userSelectByParam, - forceUserSelectByParamNotEmpty); - switch (userSelectByType) - { - case XUserSelectBy.MobileNumber: - context.MobileNumber = userSelectByParam; - break; - - case XUserSelectBy.Email: - context.Email = userSelectByParam; - break; - - case XUserSelectBy.Username: - context.UserName = userSelectByParam; - break; - - case XUserSelectBy.ID: - context.UserId = userSelectByParam; - break; - - case XUserSelectBy.NotSpecified: - default: - if (forceCheckUserExists) - { - XException.InvalidArgs.Throw(); - } - break; - } - } - - // - // Generate Registration Request ... - xRequest = new XActionRequestToken - { - Action = step, - Context = context - }; - - // - // Add User Id if Exists to Context ... - var isUserExists = await IsUserExistsAsync(userSelectByParam); - if (isUserExists) - { - // - var user = await GetUserAsync(userSelectByParam); - if (user != null) - { - xRequest.Context.UserId = user.Id; - } - } - - // - xRequest.Prepare(Configuration.IdentitySecretKey); - - // - xToken = await HashRequest( - xRequest, - forceUserSelectByParamNotEmpty); - } - - // - // When XToken Exists Passed XToken ... - result = GetActionResultResponse(xToken); - - // - if (result == null) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - - /// - /// Request a Mobile Verification Code - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// the mobile number which is going to request a verification code - /// check mobile number is in use or not, default is true - /// an instance of XActionResponse - private async Task RequestMobileVerificationCode( - string lang, - XDevice device, - string actionToken, - string mobileNumber, - bool checkMobileInUse = true - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(lang, actionToken, mobileNumber) - .AddMobileNumber(mobileNumber) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Check Mobile is Unique ... - if (checkMobileInUse) - { - var isUserExists = await IsUserExistsAsync(mobileNumber); - if (isUserExists) - { - // - var xUser = await GetUserAsync(mobileNumber); - - // - if (xUser.PhoneNumberConfirmed) - { - XException.MobileInUsed.Throw(); - } - } - } - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - - // - // Validate two Device Must Same ... - ValidateRequestAndGiveDevices(device, request.Context.Device); - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam( - request, - forceNotNull: false, - excludes: new List { - XUserSelectBy.ID, - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // if it's null, means user doesn't have Invitation Token - // and there is no User Selector ... - if (userSelectByParam.IsNullOrEmpty()) - { - // - // Since Mobile is Unique so it can act as a - // UserSelector ... - userSelectByParam = mobileNumber; - } - - // - // Define empty Verification Code - // and Empty Verification Request ... - var verificationCode = ""; - XVerificationRequest xVerificationRequest = null; - - // - // Check Device Request Verification Code before or Not ... - var isDeviceRequested = await IsDeviceRequestedForVerificationCodeBefor(device); - if (isDeviceRequested) - { - // - // if Requested before, Retrieve XVerification instance by Device from Db - // and Validate it ... - xVerificationRequest = await ValidateAndRetrieveVerificationRequest(device); - - // - if (xVerificationRequest.VerificationCode.IsNullOrEmpty()) - { - // - verificationCode = GenerateRandom().ToString(); - xVerificationRequest.VerificationCode = verificationCode; - - // - await RemoveVerificationCodeRequestByDevice( - device, - saveChanges: false - ); - await AddVerificationRequest( - xVerificationRequest, - saveChanges: false - ); - - // - await DbContext.SaveChangesAsync(); - } - - // - // if XVerificationRequest is Valid, it must Contain an Alive Verification Code - // so retrieve it and assign it ... - verificationCode = xVerificationRequest.VerificationCode; - } - else - { - // - verificationCode = GenerateRandom().ToString(); - } - - // - // if it's First Verification Request of given Device - // Generate a new Verification Code ... - if (verificationCode.IsNullOrEmpty()) - { - verificationCode = GenerateRandom().ToString(); - } - - // - // Check Context Mobile and given Mobile ... - if (!request.Context.MobileNumber.IsNullOrEmpty() && - mobileNumber != request.Context.MobileNumber) - { - XException.InvalidMobileNumber.Throw(); - } - - // - // Check User Added To Db or Not ... - var isAddedUser = !request.Context.UserId.IsNullOrEmpty(); - if (isAddedUser) - { - // - // Validate User Exists and Retireve User Object ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - // Check Mobiles Same ... - if (user.PhoneNumber == mobileNumber && - user.PhoneNumberConfirmed) - { - XException.MobilesSame.Throw(); - } - - // - // Update User Object's Mobile Number and - // Confirmation Status ... - user.PhoneNumber = mobileNumber; - user.PhoneNumberConfirmed = false; - - // - // Save Changes to Db ... - await UpdateUserAsync(user, checkCanLoginPolicies: false, checkIsBanned: false); - } - - // - // Prepare Verification Request by Checking Next Tries, - // Device Status, and etc, Update or Add XVerificationRequest to db - // and Retrieve the added Entity ... - xVerificationRequest = await HandleVerificationRequestPreparation(verificationCode, request); - - // - // Update Request Context MobileNumber - // and it's Confirmation Status ... - request.Context.MobileNumber = mobileNumber; - request.Context.MobileVerified = false; - - // - // Remove Previous Token ... - await RemoveTokenByHash(actionToken); - - // - // Prepare New Token Result Resource, - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.RequestMobileVerificationCode, - request.Context, - forceCheckUserExists: isAddedUser - ); - - // - // Prepare Message ... - var xMessage = GetVerificationCodeMessage(lang, mobileNumber, verificationCode); - - // - // Send Verification Code Message to User Using SMS Provider ... - await MessageProvider.SendSmsAsync(xMessage, throwException: false); - - // - // Return Result ... - return result; - } - - /// - /// Request a Email Verification Code - /// - /// specify destination language - /// an instance of XDevice - /// a token which approved user action - /// the email address which is going to request a verification code - /// check email address is in use or not, default is true - /// an instance of XActionResponse - public async Task RequestEmailVerificationCode( - string lang, - XDevice device, - string actionToken, - string emailAddress, - bool checkEmailInUse = true - ) - { - // - // Validate Args ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(lang, actionToken, emailAddress) - .AddEmailAddress(emailAddress) - .AddNotNull(device) - .ValidateGroupAsync(); - - // - // Check Device Validation ... - await ValidateDeviceForActions(device); - - // - // Check Email is Unique ... - if (checkEmailInUse) - { - var isUserExists = await IsUserExistsAsync(emailAddress); - if (isUserExists) - { - // - var xUser = await GetUserAsync(emailAddress); - - // - if (xUser.EmailConfirmed) - { - XException.EmailInUsed.Throw(); - } - } - } - - // - // Get Related Token to Registration Hash and Validate it, - // then Parse XActionRequest Instance from Token ... - var request = await ValidateAndParseActionHash(actionToken); - - // - // Validate two Device Must Same ... - ValidateRequestAndGiveDevices(device, request.Context.Device); - - // - // Extract UserSelectByParam from XActionRequest ... - var userSelectByParam = GetUserSelectByParam( - request, - forceNotNull: false, - excludes: new List { - XUserSelectBy.ID, - XUserSelectBy.Email, - XUserSelectBy.MobileNumber - }); - - // - // if it's null, means user doesn't have Invitation Token - // and there is no User Selector ... - if (userSelectByParam.IsNullOrEmpty()) - { - // - // Since Email is Unique so it can act as a - // UserSelector ... - userSelectByParam = emailAddress; - } - - // - // Define empty Verification Code - // and Empty Verification Request ... - var verificationCode = ""; - XVerificationRequest xVerificationRequest = null; - - // - // Check Device Request Verification Code before or Not ... - var isDeviceRequested = await IsDeviceRequestedForVerificationCodeBefor(device); - if (isDeviceRequested) - { - // - // if Requested before, Retrieve XVerification instance by Device from Db - // and Validate it ... - xVerificationRequest = await ValidateAndRetrieveVerificationRequest(device); - - // - if (xVerificationRequest.VerificationCode.IsNullOrEmpty()) - { - // - verificationCode = GenerateRandom().ToString(); - xVerificationRequest.VerificationCode = verificationCode; - - // - await RemoveVerificationCodeRequestByDevice( - device, - saveChanges: false - ); - await AddVerificationRequest( - xVerificationRequest, - saveChanges: true - ); - } - - // - // if XVerificationRequest is Valid, it must Contain an Alive Verification Code - // so retrieve it and assign it ... - verificationCode = xVerificationRequest.VerificationCode; - } - else - { - // - verificationCode = GenerateRandom().ToString(); - } - - // - // Check Context Email and given Email ... - if (!request.Context.Email.IsNullOrEmpty() && - emailAddress != request.Context.Email) - { - XException.InvalidEmailAddress.Throw(); - } - - // - // Check User Added To Db or Not ... - var isAddedUser = !request.Context.UserId.IsNullOrEmpty(); - if (isAddedUser) - { - // - // Validate User Exists and Retireve User Object ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: false, - checkIsBanned: false); - - // - // Check Email Same ... - if (user.Email == emailAddress && - user.EmailConfirmed) - { - XException.MobilesSame.Throw(); - } - - // - // Update User Object's Email and - // Confirmation Status ... - user.Email = emailAddress; - user.EmailConfirmed = false; - - // - // Save Changes to Db ... - await UpdateUserAsync( - user, - checkCanLoginPolicies: false, - checkIsBanned: false - ); - } - - // - // Prepare Verification Request by Checking Next Tries, - // Device Status, and etc, Update or Add XVerificationRequest to db - // and Retrieve the added Entity ... - xVerificationRequest = await HandleVerificationRequestPreparation(verificationCode, request); - - // - // Update Request Context Email - // and it's Confirmation Status ... - request.Context.Email = emailAddress; - request.Context.EmailVerified = false; - - // - // Prepare New Token Result Resource, - // by Requesting an Action ... - var result = await ActionRequest( - lang, - device, - userSelectByParam, - XAction.RequestEmailVerificationCode, - request.Context, - forceCheckUserExists: isAddedUser - ); - - // - // Remove Hash ... - await RemoveTokenByHash(actionToken); - - // - // Prepare Message ... - var xMessage = GetVerificationCodeMessage(lang, emailAddress, verificationCode); - - // - // Send Verification Code Message to User Using Mail Provider ... - await MessageProvider.SendMailAsync(xMessage, throwException: false); - - // - // Return Result ... - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Role.cs - -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Role Actions ... - /// - /// Check a Role exists or not - /// - /// role name - /// a boolean value - public async Task IsRoleExistsAsync( - string roleName - ) - { - // - if (roleName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - return await RoleManager.RoleExistsAsync(roleName); - } - - /// - /// Create a new Role - /// - /// role name - /// an instance of IdentityResult - public async Task CreateRoleAsync( - string roleName - ) - { - // - var isExists = await RoleManager - .RoleExistsAsync(roleName); - if (isExists) - { - XException.Duplicate.Throw(); - } - - // - var result = await RoleManager - .CreateAsync(new IdentityRole(roleName)); - - // - return result; - } - - /// - /// Get a Role - /// - /// role name - /// an instance of IdentityRole - public async Task GetRoleAsync( - string roleName - ) - { - // - var isExists = await IsRoleExistsAsync(roleName); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - var result = await RoleManager - .FindByNameAsync(roleName); - - // - return result; - } - - /// - /// Remove a User From Role - /// - /// an instance of XUser - /// role name - /// an instance of IdentityResult - public async Task RemoveFromRoleAsync( - XUser user, - string roleName - ) - { - return await UserManager.RemoveFromRoleAsync(user, roleName); - } - - /// - /// Remove a User From Roles - /// - /// an instance of XUser - /// a collection of role names - /// an instance of IdentityResult - public async Task RemoveFromRolesAsync( - XUser user, - IEnumerable roleNames - ) - { - return await UserManager.RemoveFromRolesAsync(user, roleNames); - } - - /// - /// Assign a User to Specific Role - /// - /// an instance of XUser - /// role name - /// an instance of IdentityResult - public async Task AddUserToRoleAsync( - XUser user, - string roleName - ) - { - // - if (user == null || - roleName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var userSelectByParam = GetUserSelectByParam(user); - var isExistsUser = await IsUserExistsAsync(userSelectByParam); - var isExistsRole = await IsRoleExistsAsync(roleName); - if (!isExistsUser || !isExistsRole) - { - XException.NotFound.Throw(); - } - - // - var result = await UserManager - .AddToRoleAsync(user, roleName); - - // - return result; - } - - /// - /// Retrieve Role Name by it's ID - /// - /// role id - /// role name as string - public async Task GetRoleNameAsync( - string roleId - ) - { - // - // Validate Args ... - if (roleId.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var role = await RoleManager - .FindByIdAsync(roleId); - - // - return role.Name.ToNormalString(); - } - - /// - /// Get a List Of User Roles - /// - /// user identifier - /// - /// - /// a collection of role names - public async Task> GetRoleNamesAsync( - string userSelectByParam, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - - // - var result = new List(); - foreach (var role in user.Roles) - { - // - var roleName = await GetRoleNameAsync(role.RoleId); - roleName = roleName.ToNormalString(); - - // - result.Add(roleName); - } - - // - return result; - } - - /// - /// Check a User is Adminr not - /// - /// user identifier - /// a boolean value - public async Task IsAdmin( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true, - checkCanLoginPolicies: true); - - // - var result = await IsAdmin(user); - - // - return result; - } - - /// - /// Check a User is Adminr not - /// - /// an instance of XUser - /// a boolean value - public async Task IsAdmin( - XUser user - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(user); - ValidationProvider.NotEmpty(user.Id); - - // - // Retrieve Admin Role ... - // TODO: Fix this ... - var adminRole = "admin"; - // XUserRole.Admin - // .GetStringValue () - // .ToNormalString (); - - // - // Check Admin Role Exists in User Roles or not ... - var userRoleNames = await GetRoleNamesAsync(user.Id); - var isContainsAdminRole = userRoleNames.Contains(adminRole); - - // - // Return Result ... - return isContainsAdminRole; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Search.cs - -using System.Threading.Tasks; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Dtos; -using xModels.Dtos; -using xDataService.Extensions; -using xIds.Extensions; -using System.Linq; -using xIdentityModels.Extensions; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Actions ... - /// - /// Query User Profiles - /// - /// requested user's identifier - /// how to filter results based on XQuery structure - /// an instance of XQueryResult of XUserProfileDto - public async Task> QueryOpenToSearchUsers( - string requestedUserSelectByParam, - XQuery query - ) - { - // - // Validation ... - if (query.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - query = query.NormalizeQuery(DataConfiguration.ToXDataServiceConfig()); - - // - // Since in Resourceable Entities we have to Search on Locales - // we Must Implement Senario Custom ... - var totalEntities = GetUsersDbSet() - .Where(u => u.OpenToSearch) - .ToList() - .Where(u => !u.ContainsUserSelectByParam(requestedUserSelectByParam)) - .Select(u => u.Id) - .ToList(); - - // - var items = await GetUserProfilesAsync( - totalEntities, - requestedUserSelectByParam, - checkIsBanned: false, - checkCanLoginPolicies: false, - forceCheckRequestedUser: false - ); - - // - var totalItemsCount = items.Count(); - - // - // Apply Filter ... - if (!query.Filter.IsNullOrEmpty()) - { - // - items = items - .ApplyFilter(query.Filter); - } - int filteredItemsCount = items.Count(); - - // - // Count Pages ... - var totalPagesCount = query.CountPages(totalItemsCount); - var filteredPagesCount = query.CountPages(filteredItemsCount); - - // - // Apply Paging and Sorting ... - if (totalItemsCount > 0 && - filteredItemsCount > 0) - { - // - // Apply Sorting ... - items = items - .ToList() - .ApplySorting( - query.SortBy, - query.IsAscending - ); - - // - // Apply Paging ... - items = items - .ToList() - .ApplyPaging( - query.Page, - query.PageSize - ); - } - - // - // Generate Result Object ... - // Query = query, - var result = new XQueryResult - { - Items = items, - Page = query.Page, - PageSize = query.PageSize, - TotalPages = totalPagesCount, - TotalItems = totalItemsCount, - TotalFilteredPages = filteredPagesCount, - TotalFilteredItems = filteredItemsCount - }; - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Seed.cs - -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels.Descriptors; -using xIdentityModels.Extensions; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Default Identity Preparation Actions ... - /// - /// Create Default Roles based on Identity Configuration - /// - /// - public async Task CreateIdentityRoles() - { - // - if (Configuration == null || - Configuration.IdentityRoles == null || - Configuration.IdentityRoles.Count == 0) - { - return; - } - - // - // Check New Users Role exists in IdentityRole or not ... - if (!Configuration.NewUsersRole.IsNullOrEmpty()) - { - // - // Ensure NewUsersRole Exists in IdentityRoles ... - var isNewUserRoleExistsInIdentityRoles = Configuration - .IdentityRoles - .Contains(Configuration.NewUsersRole); - if (!isNewUserRoleExistsInIdentityRoles) - { - XException.InvalidArgs.Throw(); - } - } - - // - // loop through all roles and create them one by one ... - foreach (var roleName in Configuration.IdentityRoles) - { - // - var isRoleExists = await RoleManager.RoleExistsAsync(roleName); - if (!isRoleExists) - { - // - var result = await RoleManager.CreateAsync(new IdentityRole(roleName)); - } - } - } - - /// - /// Create a user Based on User Descriptor - /// - /// an instance of XIdentityUserDescriptor - /// - public async Task CreateUserAsync( - XIdentityUserDescriptor user - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(user); - - // - var isExistsRole = await RoleManager.RoleExistsAsync(user.Role); - if (!isExistsRole) - { - // - // Check Assigned role to user exists in app roles ... - if (!Configuration - .IdentityRoles - .Contains(user.Role)) - { - XException.InvalidArgs.Throw(); - } - - // - // Ensure All Roles Created ... - await CreateIdentityRoles(); - } - - // - // Check User Exists ... - var isExistsUser = await IsUserExistsAsync(user.UserName); - if (!isExistsUser) - { - // - // Create a DashboardUser instance based on Configuration Data ... - var userEntity = user.ToXUser(); - - // - // Try to Create User ... - var userCreateResult = await CreateUserAsync( - userEntity, - user.Password - ); - if (!userCreateResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - // Assign Admin User to it's Role ... - var roleAssignResult = await UserManager.AddToRoleAsync(userEntity, user.Role); - if (!roleAssignResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - - // - var claims = await ToJwtClaims( - userEntity, - checkCanLoginPolicies: true, - checkIsBanned: true); - - // - var addClaimsResult = await UserManager.AddClaimsAsync(userEntity, claims); - if (!addClaimsResult.Succeeded) - { - XException.ActionFailed.Throw(); - } - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Token.cs - -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Microsoft.IdentityModel.Tokens; -using xCommons.Extensions; -using xCommons.Helpers; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Constants; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Token Actions ... - /// - /// Check a Token Entity Exists or not - /// - /// an instance of XDevice - /// specifies Action Step by a member of XAction - /// a boolean value - private async Task IsTokenExistsByDeviceAndType( - XDevice device, - XAction type - ) - { - // - ValidationProvider.NotNull(device); - - // - var isExists = false; - var enumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var token in enumerator) - { - // - if (token.Type == type && - token.Device.IsSameAs(device)) - { - isExists = true; - break; - } - } - - // - return isExists; - } - - /// - /// Check a Token Entity Exists or not - /// - /// specified user's identifier - /// specifies Action Step by a member of XAction - /// a boolean value - private async Task IsTokenExistsByUserAndType( - string userSelectByParam, - XAction type - ) - { - // - ValidationProvider.NotEmpty(userSelectByParam); - - // - var isExists = false; - var tokensEnumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var token in tokensEnumerator) - { - // - if (token.Type == type && - token.UserSelectByParam - .ToNormalString() == userSelectByParam - .ToNormalString()) - { - // - isExists = true; - break; - } - } - - // - return isExists; - } - - /// - /// Check a Token Entity Exists or not - /// - /// represent specified action token - /// a boolean value - private async Task IsTokenExistsByToken( - string token - ) - { - // - var result = await DbContext.Tokens - .AnyAsync(xt => xt.Token == token); - - // - return result; - } - - /// - /// Check a Token Entity Exists or not - /// - /// represent specified action token hash - /// a boolean value - private async Task IsTokenExistsByHash( - string hash - ) - { - // - var result = await DbContext.Tokens - .AnyAsync(xt => xt.Hash == hash); - - // - return result; - } - - /// - /// Check a Token Entity Exists or not - /// - /// an instance of XToken - /// a boolean value - private async Task IsTokenExistsByToken( - XToken item - ) - { - // - var result = false; - var tokenEnumerator = DbContext.Tokens - .AsAsyncEnumerable(); - await - foreach (var token in tokenEnumerator) - { - // - if (token.Hash == item.Hash && - token.Token == item.Token && - token.Type == item.Type && - token.UserSelectByParam - .ToNormalString() == item.UserSelectByParam - .ToNormalString() && - token.Device.IsSameAs(item.Device)) - { - // - result = true; - break; - } - } - - // - return result; - } - - /// - /// Check a Token Entity Exists or not - /// - /// specifies token id - /// a boolean value - private async Task IsTokenExistsById( - int id - ) - { - return await DbContext.Tokens.AnyAsync(t => t.Id == id); - } - - /// - /// Retrieve Token Entity - /// - /// an instance of XDevice - /// specifies Action Step by a member of XAction - /// an instance of XToken - private async Task GetTokenByDeviceAndType( - XDevice device, - XAction type - ) - { - // - var isExists = await IsTokenExistsByDeviceAndType(device, type); - if (!isExists) - { - return null; - } - - // - XToken item = null; - var enumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var token in enumerator) - { - // - if (token.Type == type && - token.Device.IsSameAs(device)) - { - // - item = token; - break; - } - } - - // - return item; - } - - /// - /// Retrieve Token Entity - /// - /// specified user's identifier - /// specifies Action Step by a member of XAction - /// an instance of XToken - private async Task GetTokenByUserAndType( - string userSelectByParam, - XAction type - ) - { - // - var isExists = await IsTokenExistsByUserAndType(userSelectByParam, type); - if (!isExists) - { - return null; - } - - // - XToken item = null; - var enumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var token in enumerator) - { - // - if (token.Type == type && - token.UserSelectByParam - .ToNormalString() == userSelectByParam - .ToNormalString()) - { - // - item = token; - break; - } - } - - // - return item; - } - - /// - /// Retrieve a Token Entity - /// - /// represent specified action token - /// an instance of XToken - private async Task GetTokenByToken( - string token - ) - { - // - var isExists = await IsTokenExistsByToken(token); - if (!isExists) - { - return null; - } - - // - var result = await DbContext.Tokens - .FirstOrDefaultAsync(xt => xt.Token == token); - - // - return result; - } - - /// - /// Retrieve Related Hash to a Token - /// - /// represent specified action token - /// hash string - private async Task GetRelatedHashByToken( - string token - ) - { - // - var item = await GetTokenByToken(token); - if (item == null) - { - return null; - } - - // - return item.Hash; - } - - /// - /// Retrieve a Token Entity - /// - /// represent specified action token hash - /// an instance of XToken - private async Task GetTokenByHash( - string hash - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(hash); - - // - var isExists = await IsTokenExistsByHash(hash); - if (!isExists) - { - return null; - } - - // - var item = await DbContext.Tokens - .FirstOrDefaultAsync(t => t.Hash == hash); - - // - return item; - } - - /// - /// Retrieve Related Token to a Hash string - /// - /// represent specified action token hash - /// token string - private async Task GetRelatedTokenByHash( - string hash - ) - { - // - var item = await GetTokenByHash(hash); - if (item == null) - { - return null; - } - - // - return item.Token; - } - - /// - /// Retrieve a Token Expiration Date - /// - /// represent specified action token - /// an instance of DateTime - private DateTime GetTokenExpirationDate( - string token - ) - { - // - ValidationProvider.NotEmpty(token); - - // - var result = IdentityHelper.GetTokenExpirationDate(token); - - // - return result; - } - - /// - /// Remove a Token Entity - /// - /// represent specified action token - /// - private async Task RemoveTokenByToken( - string token - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(token); - - // - var isExists = await IsTokenExistsByToken(token); - if (!isExists) - { - return; - } - - // - var item = await GetTokenByToken(token); - if (item == null) - { - return; - } - - // - DbContext.Tokens.Remove(item); - await DbContext.SaveChangesAsync(); - } - - /// - /// Remove a Token Entity - /// - /// represent specified action token hash - /// - private async Task RemoveTokenByHash( - string hash - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(hash); - - // - var isExists = await IsTokenExistsByHash(hash); - if (!isExists) - { - return; - } - - // - var item = await GetTokenByHash(hash); - if (item == null) - { - return; - } - - // - DbContext.Tokens.Remove(item); - await DbContext.SaveChangesAsync(); - } - - /// - /// Remove a Token Entity - /// - /// an instance of XDevice - /// - private async Task RemoveTokenByDevice( - XDevice device - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(device); - - // - XToken items = null; - var enumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var token in enumerator) - { - // - if (token.Device.IsSameAs(device)) - { - // - items = token; - break; - } - } - - // - if (!items.IsNull()) - { - DbContext.Tokens.RemoveRange(items); - await DbContext.SaveChangesAsync(); - } - } - - /// - /// add a token Entity - /// - /// an instance of XToken - /// an instance of XToken - private async Task AddTokenAsync( - XToken item - ) - { - // - var isExist = await IsTokenExistsByToken(item); - if (isExist) - { - return await GetTokenByHash(item.Hash); - } - - // - var entry = await DbContext.Tokens.AddAsync(item); - await DbContext.SaveChangesAsync(); - - // - return entry.Entity; - } - - /// - /// Hash a Request Token - /// - /// an instance of XActionRequestToken - /// - /// - /// an instance of XToken - private async Task HashRequest( - XActionRequestToken request, - bool forceNotNullUserSelectByParam = true, - bool forceDeviceNotNull = true - ) - { - // - // Validate Args ... - var secretKey = Configuration.IdentitySecretKey; - ValidationProvider.NotNull(request); - ValidationProvider.NotEmpty(secretKey); - - // - ValidateActionRequest(request); - - // - var type = request.Action; - var device = request.Context.Device; - var tokenObject = ToSecurityToken(request); - var tokenString = ToTokenString(tokenObject); - var tokenHash = ToHash(tokenString); - var userSelectByParam = GetUserSelectByParam(request, forceNotNullUserSelectByParam); - - // - if (forceNotNullUserSelectByParam) - { - ValidationProvider.NotEmpty(userSelectByParam); - } - - // - ValidationProvider.NotEmpty(tokenString, tokenHash); - - // - if (forceDeviceNotNull) - { - ValidationProvider.NotNull(device); - } - - // - ValidationProvider.NotNull(tokenObject); - - // - var xToken = new XToken - { - Type = type, - Device = device, - Hash = tokenHash, - Token = tokenString, - UserSelectByParam = userSelectByParam - }; - - // - var addedToken = await AddTokenAsync(xToken); - - // - return addedToken; - } - - /// - /// Generate Token Hash string - /// - /// represent specified action token - /// check token validation parameters, default is true - /// hash string - private string ToHash( - string token, - bool checkValidation = true - ) - { - // - ValidationProvider.NotEmpty(token); - - // - if (checkValidation) - { - ValidateToken(token); - } - - // - var result = token.ToMd5String().ToNormalString(); - - // - return result; - } - - /// - /// Generate Token string - /// - /// represent specified action token - /// token string - private string ToTokenString( - SecurityToken token - ) - { - // - ValidationProvider.NotNull(token, IdentityHelper); - - // - var result = IdentityHelper.ToTokenString(token); - - // - return result; - } - - /// - /// Generate Token string - /// - /// represent specified action token - /// token string - private string ToTokenString( - JwtSecurityToken token - ) - { - // - ValidationProvider.NotNull(token, IdentityHelper); - - // - var result = IdentityHelper.ToTokenString(token); - - // - return result; - } - - /// - /// Generate Security Token - /// - /// represent specified action token - /// an instance of SecurityToken - private SecurityToken ToSecurityToken( - string token - ) - { - // - ValidationProvider.NotEmpty(token); - - // - var result = IdentityHelper.ToSecurityToken(token); - - // - return result; - } - - /// - /// Generate Security Token - /// - /// an instance of XActionRequestToken - /// an instance of SecurityToken - private SecurityToken ToSecurityToken( - XActionRequestToken request - ) - { - // - ValidationProvider.NotNull(request); - - // - ValidateActionRequest(request); - - // - var result = IdentityHelper.ToSecurityToken(request); - if (result == null) - { - XException.InvalidToken.Throw(); - } - - // - return result; - } - - /// - /// Cleanup all exists tokens related to specified User - /// - /// specified user's identifier - /// - private async Task HandleRemoveExistsTokens( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var xTokens = new List(); - var xTokenEnumerator = DbContext.Tokens.AsAsyncEnumerable(); - await - foreach (var xToken in xTokenEnumerator) - { - // - if (xToken.UserSelectByParam == userSelectByParam && - ObjectHelper.ToEnumerableValues().Contains(xToken.Type)) - { - xTokens.Add(xToken); - } - } - - // - if (xTokens.HasChild()) - { - DbContext.Tokens.RemoveRange(xTokens); - await DbContext.SaveChangesAsync(); - } - } - - /// - /// Cleanup all tokens related to specified User - /// - /// a collection of user identifiers - /// - private async Task HandleCleanUserTokens( - ICollection userSelectByParams - ) - { - // - // Validate Args ... - if (!userSelectByParams.HasChild()) - { - return; - } - - // - foreach (var userSelectByParam in userSelectByParams) - { - await HandleRemoveExistsTokens(userSelectByParam); - } - } - - /// - /// Cleanup all tokens related to specified User - /// - /// an instance of XUser - /// - private async Task HandleCleanUserTokens( - XUser user - ) - { - // - if (user == null) - { - return; - } - - // - var userSelectByParams = GenerateUserSelectByParams(user); - - // - await HandleCleanUserTokens(userSelectByParams); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+User.cs - -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using IdentityModel; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Constants; -using xIdentityModels.Dtos; -using xIdentityModels.Extensions; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region User Handlers ... - /// - /// Check a User Exists or not - /// - /// specified user's identifier - /// a boolean value - public async Task IsUserExistsAsync( - string userSelectByParam - ) - { - // - // Validate Args ... - if (userSelectByParam.IsNullOrEmpty()) - { - return false; - } - - // - var selectType = GetUserSelectByType(userSelectByParam); - - // - var result = false; - XUser user = null; - switch (selectType) - { - case XUserSelectBy.MobileNumber: - user = await GetUsersDbSet() - .Where(ur => ur.PhoneNumber == userSelectByParam) - .FirstOrDefaultAsync(); - break; - - case XUserSelectBy.Email: - user = await UserManager - .FindByEmailAsync(userSelectByParam); - break; - - case XUserSelectBy.Username: - user = await UserManager - .FindByNameAsync(userSelectByParam); - break; - - case XUserSelectBy.ID: - default: - user = await UserManager - .FindByIdAsync(userSelectByParam); - break; - } - - // - result = user != null; - - // - return result; - } - - /// - /// Check a User Selector is Available for Registration or Not - /// - /// specified user's identifier - /// a boolean value - public async Task CanRegister( - string userSelectByParam - ) - { - // - // Validate ARgs ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var selectByType = GetUserSelectByType(userSelectByParam); - - // - if (selectByType == XUserSelectBy.Username && - !ValidateUserName(userSelectByParam)) - { - return false; - } - - // - var isExists = await IsUserExistsAsync(userSelectByParam); - if (isExists) - { - return false; - } - - // - return true; - } - - /// - /// Get a User object - /// - /// specified user's identifier - /// specifies returned object contains all Navigation Properties or not, default is false - /// an instance of XUser - public async Task GetUserAsync( - string userSelectByParam, - bool containDetails = false - ) - { - // - var isExists = await IsUserExistsAsync(userSelectByParam); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Fill User ... - var selectType = GetUserSelectByType(userSelectByParam); - XUser user = null; - var usersStore = GetUsersDbSet(containDetails); - - // - // Select Type ... - switch (selectType) - { - case XUserSelectBy.MobileNumber: - user = await usersStore - .FirstOrDefaultAsync(ur => ur.PhoneNumber == - userSelectByParam); - break; - - case XUserSelectBy.Email: - user = await usersStore - .FirstOrDefaultAsync(ur => ur.Email == - userSelectByParam); - break; - - case XUserSelectBy.Username: - user = await usersStore - .FirstOrDefaultAsync(ur => ur.UserName == - userSelectByParam); - break; - - case XUserSelectBy.ID: - default: - user = await usersStore - .FirstOrDefaultAsync(ur => ur.Id == - userSelectByParam); - break; - } - - // - return user; - } - - /// - /// Retrieve User Names based on UserIds - /// - /// a collection of user identifiers - /// a collection of Usernames - public async Task> GetUserNamesAsync( - IEnumerable userIds - ) - { - // - // Validate Args ... - if (userIds == null || - userIds.Count() == 0) - { - return null; - } - - // - var result = await GetUsersDbSet() - .Where( - xu => - userIds - .Contains(xu.Id)) - .Select(xt => xt.UserName) - .ToListAsync(); - - // - return result; - } - - /// - /// get user ids and retrieve corresponding user names - /// - /// an instance of XUserNameIdRequest which represent required UserIds collection - /// a collection of XUserNameIdResponse instances - public async Task> GetUserNameIdsAsync( - XUserNameIdRequest model - ) - { - // - // Validate Args ... - if (model.IsNull() || !model.Ids.HasChild()) - { - return null; - } - - // - var result = await GetUsersDbSet() - .Where( - xu => - model.Ids.Contains(xu.Id) || - model.Ids.Contains(xu.Email) || - model.Ids.Contains(xu.UserName) || - model.Ids.Contains(xu.PhoneNumber)) - .Select(xt => new XUserNameIdResponse - { - Id = xt.Id, - UserName = xt.UserName, - }) - .ToListAsync(); - - // - return result; - } - - /// - /// Create a User - /// - /// an instance of XUser - /// user's password - /// check a user can log in in system or not, default is false - /// check user is banned or not, default is false - /// an instance of IdentityResult - public async Task CreateUserAsync( - XUser user, - string password, - bool checkCanLoginPolicies = false, - bool checkIsBanned = false - ) - { - // - if (user == null || - password.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Get User Select By param - var userSelectByParam = GetUserSelectByParam(user, excludes: new List { XUserSelectBy.ID }); - - // - // Check User Created before or not ... - var isExists = await IsUserExistsAsync(userSelectByParam); - if (isExists) - { - XException.Duplicate.Throw(); - } - - // - var result = await UserManager.CreateAsync(user, password); - if (result.Succeeded) - { - // - var claims = await ToJwtClaims( - user, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned); - - // - var addClaimsResult = await UserManager.AddClaimsAsync(user, claims); - - // - return addClaimsResult; - } - - // - return result; - } - - /// - /// Update a User Information - /// - /// an instance of XUser - /// check a user can log in in system or not, default is true - /// check user is banned or not, default is true - /// an instance of IdentityResult - public async Task UpdateUserAsync( - XUser user, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - var updateResult = await this.UserManager.UpdateAsync(user); - if (updateResult.Succeeded) - { - // - var claims = await ToJwtClaims( - user, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned - ); - var existsClaims = await UserManager.GetClaimsAsync(user); - - // - await UserManager.RemoveClaimsAsync(user, existsClaims); - var addClaimsResult = await UserManager.AddClaimsAsync(user, claims); - - // - return addClaimsResult; - } - - // - return updateResult; - } - - /// - /// Generate JWT Claims froma DashboardUser object - /// - /// an instance of XUser - /// check a user can log in in system or not, default is true - /// check user is banned or not, default is true - /// a collection of Claim instances - public async Task ToJwtClaims( - XUser user, - bool checkCanLoginPolicies = true, - bool checkIsBanned = true - ) - { - // - // Get New Instance of Claims ... - var claims = new List { - // - // Mapping to User.Identity.Name ... - new Claim (JwtClaimTypes.Name, user.UserName), - - // - // Mapping to User.Identity.Name ... - new Claim (JwtRegisteredClaimNames.UniqueName, user.UserName), - - // - // Other Usefull User Related Data ... - new Claim (JwtClaimTypes.GivenName, user.FirstName), - new Claim (JwtClaimTypes.FamilyName, user.LastName), - - // - // User Gendre ... - new Claim (JwtClaimTypes.Gender, user.Gender.ToString (), ClaimValueTypes.Integer), - - // - // User Profile Picture ... - new Claim (JwtClaimTypes.Picture, !user.Avatar.IsNullOrEmpty () ? - user.Avatar.ToString () : - ""), - - // - // The Unique Identifier for Each Token ... - new Claim (JwtRegisteredClaimNames.Jti, Guid.NewGuid ().ToString ()), - - // - // Add isEnable and isBanned feature ... - new Claim ( - XCustomClaims.IsEnabled, - user.IsEnable.ToString (), - ClaimValueTypes.Boolean - ), - new Claim ( - XCustomClaims.IsBanned, - user.IsBanned.ToString (), - ClaimValueTypes.Boolean - ), - }; - - // - #region Set Claims based on Profile Policies ... - // - if (Configuration.Policy.Profile.ContainsDateOfBirth) - { - claims.Add(new Claim(JwtRegisteredClaimNames.Birthdate, user.DateOfBirth.ToString())); - } - - // - if (Configuration.Policy.Profile.ContainsEmail) - { - claims.Add(new Claim(JwtClaimTypes.Email, user.Email)); - claims.Add(new Claim( - JwtClaimTypes.EmailVerified, - user.EmailConfirmed.ToString(), - ClaimValueTypes.Boolean)); - } - - // - if (Configuration.Policy.Profile.ContainsPhoneNumber) - { - claims.Add(new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber)); - claims.Add(new Claim( - JwtClaimTypes.PhoneNumberVerified, - user.PhoneNumberConfirmed.ToString(), - ClaimValueTypes.Boolean)); - } - - // - if (Configuration.Policy.Profile.ContainsRoles) - { - var roleNames = await GetRoleNamesAsync( - user.UserName, - checkCanLoginPolicies: checkCanLoginPolicies, - checkIsBanned: checkIsBanned); - roleNames.ToList() - .ForEach(rn => - { - claims.Add(new Claim(JwtClaimTypes.Role, rn)); - }); - } - - // - if (Configuration.Policy.Profile.ContainsLastLogin) - { - claims.Add(new Claim( - JwtClaimTypes.AuthenticationTime, - user.LastLogin.ToString(), - ClaimValueTypes.DateTime)); - } - #endregion - - // - // Return Result ... - return claims.ToArray(); - } - - /// - /// Check User and Password relation - /// - /// an instance of XUser - /// user's password - /// an instance of XDevice - /// specify destination language - /// specify account lockout on failure log in - /// specify log in force without checking XDevice and lang relation - /// an instance of SignInResult - public async Task CheckPasswordSignInAsync( - XUser user, - string password, - XDevice device, - string language, - bool lockoutOnFailure, - bool isForced = true - ) - { - // - var result = await SignInManager.CheckPasswordSignInAsync( - user, password, lockoutOnFailure - ); - - // - if (result.Succeeded && isForced) - { - // - var isExistsDevice = user.Devices.Any(d => d.IsSameAs(device)); - if (!isExistsDevice && !user.Email.IsNullOrEmpty() && user.EmailConfirmed) - { - // - user.Devices.Add(device); - - // - var updateUserResult = await UpdateUserAsync(user); - if (updateUserResult.Succeeded) - { - // - try - { - // - var xMessage = GetUserNewDeviceLoggedInMessage( - language, - user.Email, - device - ); - - // - await MessageProvider.SendMailAsync(xMessage); - } - catch { } - } - } - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+Validators.cs - -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using xCommons.Extensions; -using xExceptions.Constants; -using xIdentityModels; -using xIdentityModels.Constants; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region User Validators ... - /// - /// Validate User Name for Registration based on Policies - /// - /// provided user name - /// a boolean value - private bool ValidateUserName( - string userName - ) - { - // - // Check min/max Length ... - if (userName.IsNullOrEmpty() || - userName.Length < Configuration.Policy.User.MinLength || - userName.Length > Configuration.Policy.User.MaxLength) - { - return false; - } - - // - // Check Allowed UserName Characters ... - if (!UserManager.Options.User.AllowedUserNameCharacters.IsNullOrEmpty() && - userName.Any(c => !UserManager.Options.User.AllowedUserNameCharacters.Contains(c))) - { - return false; - } - - // - // Check invalid UserNames ... - if (Configuration.Policy.User.InvalidUserNames - .HasChild() && Configuration.Policy.User.InvalidUserNames - .Any(u => userName - .ToNormalString() - .Contains(u.ToNormalString()))) - { - return false; - } - - // - return true; - } - - /// - /// Validate a User Exists - /// - /// specifies user identifier - /// specify Excetion to thrown on failure - /// - private async Task ValidateUserExistsAsync( - string userSelectByParam, - Exception exception = null - ) - { - // - ValidationProvider - .NotEmpty(userSelectByParam); - - // - if (exception == null) - { - exception = XException.NotFound.ToException(); - } - - // - // Check User Exists ... - var isExists = await IsUserExistsAsync(userSelectByParam); - if (!isExists) - { - throw exception; - } - } - - /// - /// Validate a User Not Exists - /// - /// specifies user identifier - /// specify Excetion to thrown on failure - /// - private async Task ValidateUserNotExists( - string userSelectByParam, - Exception exception = null - ) - { - // - ValidationProvider - .NotEmpty(userSelectByParam); - - // - if (exception == null) - { - exception = XException.UserRegisteredBefore.ToException(); - } - - // - // Check User Exists ... - var isExists = await IsUserExistsAsync(userSelectByParam); - if (isExists) - { - throw exception; - } - } - - /// - /// Validate User Exists and Some Usefull Checks - /// - /// specifies user identifier - /// specifies returned object contains all Navigation Properties or not, default is false - /// check a user can log in in system or not, default is false - /// check user is banned or not, default is true - /// specify do not thrown Exception if user is Disabled, default is false - /// specify requested person is Admin role, default is false - /// specify Excetion to thrown on failure - /// an instance of XUser - public async Task ValidateUserExistsAndRetrieve( - string userSelectByParam, - bool containDetails = false, - bool checkCanLoginPolicies = false, - bool checkIsBanned = true, - bool ignoreDisabledUser = false, - bool forceAdmin = false, - Exception exception = null - ) - { - // - ValidationProvider - .NotEmpty(userSelectByParam); - ValidationProvider.NotNull( - Configuration, - Configuration.Policy, - Configuration.Policy.SignIn); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidData.ToException(); - } - - // - // Check User Exists ... - await ValidateUserExistsAsync(userSelectByParam); - - // - // Retrieve User ... - var result = await GetUserAsync(userSelectByParam, containDetails); - if (result == null) - { - throw exception; - } - - // - // Check Force Admin ... - if (forceAdmin) - { - // - var isAdmin = await IsAdmin(result); - if (!isAdmin) - { - XException.NotAuthorized.Throw(); - } - } - - // - // Check User not Bann ... - if (checkIsBanned && - result.IsBanned) - { - XException.UserBanned.Throw(); - } - - // - var requireConfirmedEmail = Configuration.Policy.SignIn.RequireConfirmedEmail; - var requireConfirmedPhoneNumber = Configuration.Policy.SignIn.RequireConfirmedPhoneNumber; - var requireEnabled = Configuration.Policy.SignIn.RequiredEnabled; - - // - var isEnabled = result.IsEnable; - var isMobileConfirmed = result.PhoneNumberConfirmed; - var isEmailConfirmed = result.EmailConfirmed; - - // - if (checkCanLoginPolicies) - { - // - // Check IsEnabled ... - if (!ignoreDisabledUser && - requireEnabled && - !isEnabled) - { - XException.UserDisabled.Throw(); - } - - // - // Check Email Confirmed ... - if (requireConfirmedEmail && - !isEmailConfirmed) - { - XException.EmailNotConfirmed.Throw(); - } - - // - // Check Mobile Confirmed ... - if (requireConfirmedPhoneNumber && - !isMobileConfirmed) - { - XException.MobileNotConfirmed.Throw(); - } - } - - // - // Return Result ... - return result; - } - - /// - /// Validate a Device for User Actions - /// - /// an instance of XDevice - /// - private async Task ValidateDeviceForActions( - XDevice device - ) - { - // - ValidationProvider - .NotNull(device); - - // - // Check is Device Banned or not ... - var isDeviceBanned = await IsDeviceBanned(device); - if (isDeviceBanned) - { - // - // Retrieve Banned Device ... - var xBannedDevice = await GetBannedDevice(device); - if (xBannedDevice == null) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Banned Device Time out Passed or not ... - var isDelayTimePassed = IsDelayTimePassed(xBannedDevice); - if (!isDelayTimePassed) - { - // - var passedTime = GetPassedTime(xBannedDevice); - - // - XException.DeviceBanned - .AddContentToException(passedTime.ToString()); - } - - // - // if Delay Passed of Banned Device - // the device must Removed ... - await BannedDeviceRemove(xBannedDevice); - } - } - - /// - /// Validate a DateOfBirth for Registration - /// - /// users dob date, an instance of DateTime - /// specify Excetion to thrown on failure - /// - private void ValidateDateOfBirth( - DateTime dateOfBirth, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(dateOfBirth); - - // - if (exception.IsNull()) - { - exception = XException.InvalidDate.ToException(); - } - - // - var currentDate = DateTime.UtcNow; - if (dateOfBirth >= currentDate) - { - throw exception; - } - - // - var zeroDate = (new DateTime(1, 1, 1)).ToUniversalTime(); - var minAge = Configuration.Policy.User.MinAgeForRegistration; - var maxAge = Configuration.Policy.User.MaxAgeForRegistration; - - // - var timeSpan = currentDate - dateOfBirth; - var age = (zeroDate + timeSpan).Year - 1; - - // - if (age > maxAge || age < minAge) - { - throw exception; - } - } - - /// - /// Validate a Given User Can Registere - /// - /// specifies user identifier - /// - private async Task ValidateCanRegister( - string userSelectByParam - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(userSelectByParam); - - // - var canRegister = await CanRegister(userSelectByParam); - if (!canRegister) - { - XException.Unavailable.Throw(); - } - } - - /// - /// Validate Password by Gicen Policies - /// - /// an instance of XUser - /// user's password - /// specify Excetion to thrown on failure - /// - private async Task ValidatePasswordPolicies( - XUser user, - string password, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(user); - ValidationProvider.NotEmpty(password); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidPassword.ToException(); - } - - // - // Check new Password Validation ... - var passwordValidator = new PasswordValidator(); - var checkPasswordResult = await passwordValidator.ValidateAsync(UserManager, user, password); - if (!checkPasswordResult.Succeeded) - { - throw exception; - } - } - - /// - /// Validate a User for Dangerous Actions - /// - /// an instance of XUser - /// specified which user request Action by an instance of XUser - /// - private async Task ValidateUserForDangerousAction( - XUser user, - XUser requester - ) - { - // - // Validate ARgs ... - ValidationProvider.NotNull(user, requester); - - // - var requesterRoleNames = await GetRoleNamesAsync(requester.Id); - - // - var isSame = user.Id == requester.Id; - var isRequesterAdmin = requesterRoleNames.Any(r => r.ToNormalString() == "admin"); - if (!isSame && !isRequesterAdmin) - { - XException.NotAllowed.Throw(); - } - } - #endregion - - // - #region Device Validators ... - /// - /// Validate a Device for Specified User - /// - /// specifies user identifier - /// an instance of XDevice - /// specify Excetion to thrown on failure - /// - private async Task ValidateUserAndDeviceRelation( - string userSelectByParam, - XDevice device, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(userSelectByParam); - ValidationProvider.NotNull(device); - - // - if (exception == null) - { - exception = XException.InvalidDevice.ToException(); - } - - // - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: true); - - // - var result = await IsDeviceRelateDToUser( - userSelectByParam, - device - ); - if (!result) - { - throw exception; - } - } - #endregion - - // - #region Token Validators ... - /// - /// Validate a Token - /// - /// token string - /// specify Excetion to thrown on failure - private void ValidateToken( - string token, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(token); - - // - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - var result = IdentityHelper.ValidateToken(token); - if (!result) - { - throw exception; - } - } - - /// - /// Validate a Token is Specified to a Device and User - /// - /// an instance of XDevice - /// specifies Action type by a member of XAction - /// specify Excetion to thrown on failure - /// an instance of XToken - private async Task ValidateAndRetieveTokenByDeviceAndType( - XDevice device, - XAction type, - Exception exception = null - ) - { - // - ValidationProvider.NotNull(device); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.NotFound.ToException(); - } - - // - var isExists = await IsTokenExistsByDeviceAndType(device, type); - if (!isExists) - { - throw exception; - } - - // - var item = await GetTokenByDeviceAndType(device, type); - if (item == null) - { - throw exception; - } - - // - return item; - } - - /// - /// Validate a Token By User and Specified Type - /// - /// specifies user identifier - /// specifies Action type by a member of XAction - /// specify Excetion to thrown on failure - /// an instance of XToken - private async Task ValidateAndRetieveTokenByUserAndType( - string userSelectByParam, - XAction type, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(userSelectByParam); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidData.ToException(); - } - - // - var isExists = await IsTokenExistsByUserAndType(userSelectByParam, type); - if (!isExists) - { - throw exception; - } - - // - var item = await GetTokenByUserAndType(userSelectByParam, type); - if (item == null) - { - throw exception; - } - - // - return item; - } - - /// - /// Check Token Validation - /// - /// token string - /// a boolean value - private bool IsValidToken( - string token - ) - { - // - ValidationProvider.NotEmpty(token); - - // - var result = IdentityHelper.ValidateToken(token); - - // - return result; - } - - /// - /// Retrieve Action Request Based on Action Token - /// - /// token string - /// specify Excetion to thrown on failure - /// an instance of XActionRequestToken - private XActionRequestToken ValidateAndParseActionToken( - string token, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(token); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - ValidateToken(token); - - // - var result = IdentityHelper.ParseActionRequestToken(token); - if (result == null) - { - throw exception; - } - - // - ValidateActionRequest(result); - - // - return result; - } - - /// - /// Parse Action Request from Token - /// - /// token string - /// an instance of XActionRequestToken - private XActionRequestToken ParseActionRequest( - string token - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(token); - - // - var result = IdentityHelper - .ParseActionRequestToken(token); - - // - return result; - } - - /// - /// Parse Action Hash by Corresponding Token - /// - /// token hash string - /// an instance of XActionRequestToken - private async Task ParseActionHash( - string hash - ) - { - // - ValidationProvider.NotEmpty(hash); - - // - var isHashExists = await IsTokenExistsByHash(hash); - if (!isHashExists) - { - return null; - } - - // - var xToken = await GetTokenByHash(hash); - if (xToken == null) - { - return null; - } - - // - var isValidToken = IsValidToken(xToken.Token); - if (!isValidToken) - { - return null; - } - - // - var result = ParseActionRequest(xToken.Token); - - // - return result; - } - - /// - /// Validate and Parse Action Hash - /// - /// token hash string - /// specifies chack token Validation Parameter, default is true - /// specifies check action Validations, default is true - /// specify Excetion to thrown on failure - /// an instance of XActionRequestToken - private async Task ValidateAndParseActionHash( - string hash, - bool forceTokenValidation = true, - bool forceActionValidation = true, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(hash); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - var token = await ValidateAndRetrieveRelatedToken(hash, forceTokenValidation); - - // - var result = await ParseActionHash(hash); - if (result == null) - { - throw exception; - } - - // - if (forceActionValidation) - { - ValidateActionRequest(result); - } - - // - return result; - } - - /// - /// Validate Action Request - /// - /// an instance of XActionRequestToken - /// specify Excetion to thrown on failure - private void ValidateActionRequest( - XActionRequestToken request, - Exception exception = null - ) - { - // - ValidationProvider - .NotNull(request); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidData.ToException(); - } - - // - var isValid = IsValidActionRequest(request); - if (!isValid) - { - throw exception; - } - } - - /// - /// Check Action Request Validation - /// - /// an instance of XActionRequestToken - /// a boolean value - private bool IsValidActionRequest( - XActionRequestToken request - ) - { - // - // Validate Args ... - if (request == null || - Configuration.IdentitySecretKey.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = request.Validate(Configuration.IdentitySecretKey); - - // - return result; - } - - /// - /// Check Token and Act Based on it - /// - /// token string - /// specify Excetion to thrown on Issue failure - /// specify Excetion to thrown on failure - /// - private async Task ValidateAndHandleToken( - string token, - bool issueExcepion = false, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(token); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - var isValidToken = IsValidToken(token); - - // - if (!isValidToken) - { - // - await RemoveTokenByToken(token); - - // - if (issueExcepion) - { - throw exception; - } - } - } - - /// - /// Validate a Hash Exists or not - /// - /// token hash string - /// specify Excetion to thrown on failure - /// - private async Task ValidateHashExists( - string hash, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(hash); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - var isExists = await IsTokenExistsByHash(hash); - if (!isExists) - { - throw exception; - } - } - - /// - /// Validate a Token Exists - /// - /// token string - /// specify Excetion to thrown on failure - /// - private async Task ValidateTokenExists( - string token, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(token); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - var isExists = await IsTokenExistsByToken(token); - if (!isExists) - { - throw exception; - } - } - - /// - /// Validate a Hash and Retrieve it's Corresponding Token - /// - /// token hash string - /// specifies chack token Validation Parameter, default is true - /// specify Excetion to thrown on Issue failure - /// specify Excetion to thrown on failure - /// token string - private async Task ValidateAndRetrieveRelatedToken( - string hash, - bool forceTokenValidation = true, - bool issueExcepion = false, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(hash); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - await ValidateHashExists(hash); - - // - var token = await GetRelatedTokenByHash(hash); - if (token.IsNullOrEmpty()) - { - throw exception; - } - - // - if (forceTokenValidation) - { - await ValidateAndHandleToken(token, issueExcepion); - } - - // - return token; - } - - /// - /// Validate a Token and Retrieve it's Corresponding Hash - /// - /// token string - /// specifies chack token Validation Parameter, default is true - /// specify Excetion to thrown on failure - /// hash string - private async Task ValidateAndRetrieveRelatedHash( - string token, - bool forceTokenValidation = true, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty(token); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidToken.ToException(); - } - - // - if (forceTokenValidation) - { - await ValidateAndHandleToken(token); - } - - // - await ValidateTokenExists(token); - - // - var hash = await GetRelatedHashByToken(token); - if (hash.IsNullOrEmpty()) - { - throw exception; - } - - // - return hash; - } - - /// - /// Validate Invitation Hash - /// - /// registration invitation hash string - /// thrown Exception if user Exists, default is true - /// - private async Task ValidateInvitationHash( - string invitationHash, - bool forceUserExists = true - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(Configuration); - - // - if (Configuration.RegistrationJustWithInvite && - invitationHash.IsNullOrEmpty()) - { - XException.NotAllowed.Throw(); - } - - // - // Validate Invitation Token if it isn't null ... - if (!invitationHash.IsNullOrEmpty()) - { - // - await ValidateHashExists(invitationHash); - - // - // Token Validation also done in this task ... - var relatedToken = await ValidateAndRetrieveRelatedToken(invitationHash); - - // - var inviteAction = ValidateAndParseActionToken(relatedToken); - ValidationProvider.NotNull(inviteAction); - - // - var inviteUerSelectByParam = GetUserSelectByParam(inviteAction); - var inviteUserSelectBy = GetUserSelectByType(inviteUerSelectByParam); - if (inviteUserSelectBy != XUserSelectBy.Email) - { - XException.InvalidToken.Throw(); - } - - // - if (forceUserExists) - { - // - await ValidateUserNotExists( - inviteUerSelectByParam, - XException.EmailInUsed.ToException()); - } - } - } - #endregion - - // - #region Profile Validators ... - /// - /// Validate a Request is Corresponding to Specific Device - /// - /// an instance of XDevice - /// specify requested device by an instance of XDevice - /// specify Excetion to thrown on failure - private void ValidateRequestAndGiveDevices( - XDevice device, - XDevice requestDevice, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(device, requestDevice); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidDevice.ToException(); - } - - // - var isDevicesSame = device.IsSameAs(requestDevice); - - // - if (!isDevicesSame) - { - throw exception; - } - } - - /// - /// Check Validation of a User SelectBy Param and Password - /// - /// specifies user identifier - /// user's password - /// check a user can log in in system or not, default is true - /// specify Excetion to thrown on failure - /// - private async Task ValidateUserAndPassword( - string userSelectByParam, - string password, - bool checkCanLoginPolicies = true, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotEmpty( - userSelectByParam, - password - ); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.LoginFailed.ToException(); - } - - // - // Retrieve User and Validate User Exists ... - var user = await ValidateUserExistsAndRetrieve( - userSelectByParam, - containDetails: false, - checkCanLoginPolicies: checkCanLoginPolicies, - ignoreDisabledUser: false, - checkIsBanned: true, - exception: exception); - - // - // Check Given Password Follows Policies ... - await ValidatePasswordPolicies(user, password, exception); - - // - // Check Password for User ... - var checkPasswordResult = await UserManager.CheckPasswordAsync(user, password); - if (!checkPasswordResult) - { - throw exception; - } - } - #endregion - - // - #region Friendship Validators ... - /// - /// Validate Friendship Requested Before or not - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateRequestBefore( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - var isRequested = IsFollowRequested(source, dest); - if (!isRequested) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate a Friendship Not Requested Before - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateNotRequestBefore( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - var isRequested = IsFollowRequested(source, dest); - if (isRequested) - { - XException.Duplicate.Throw(); - } - } - - /// - /// Validate User Can Send Following Request to Dest User - /// - /// specifies a user to check as dest by an instance of XUser - /// specifies a user to check as source by an instance of XUser - private void ValidateFollowingRequest( - XUser accepterUser, - XUser requesterUser - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(accepterUser, requesterUser); - - // - var isRequest = IsFollowRequested(requesterUser, accepterUser, XFriendshipState.Pending); - if (!isRequest) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate a User can Accept a Following Request or Not - /// - /// specifies a user to check as dest by an instance of XUser - /// specifies a user to check as source by an instance of XUser - private void ValidateFollowingRequestForAccept( - XUser accepterUser, - XUser requesterUser - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(accepterUser, requesterUser); - - // - var isRequestPending = IsFollowRequested(requesterUser, accepterUser, XFriendshipState.Pending); - var isRequestRejected = IsFollowRequested(requesterUser, accepterUser, XFriendshipState.Rejected); - if (!isRequestPending && - !isRequestRejected) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate a Request is not Passed for Same Users - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateNotSameUsers( - XUser source, - XUser dest - ) - { - // - // Validate ARgs ... - ValidationProvider.NotNull(source, dest); - - // - var isSame = source.Id == dest.Id; - if (isSame) - { - XException.ActionFailed.Throw(); - } - } - - /// - /// Check a user is in Followers of another - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateIsFollowers( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - ValidateNotSameUsers(source, dest); - ValidateRequestBefore(dest, source); - - // - var isFollower = IsFollowRequested(dest, source, XFriendshipState.Accepted) || - IsFollowRequested(dest, source, XFriendshipState.Blocked); - if (!isFollower) - { - XException.NotFound.Throw(); - } - } - - /// - /// Check a user is in Followings of another - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateIsFollowings( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - ValidateNotSameUsers(source, dest); - ValidateRequestBefore(source, dest); - - // - var isFollowing = IsFollowRequested(source, dest, XFriendshipState.Accepted); - if (!isFollowing) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate a User Blocked another - /// - /// specifies a user to check as source by an instance of XUser - /// specifies a user to check as dest by an instance of XUser - private void ValidateIsBlock( - XUser source, - XUser dest - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(source, dest); - - // - ValidateNotSameUsers(source, dest); - ValidateRequestBefore(dest, source); - - // - var isFollower = IsFollowRequested(dest, source, XFriendshipState.Blocked); - if (!isFollower) - { - XException.NotFound.Throw(); - } - } - #endregion - - // - #region XActionRequest Validators ... - /// - /// Validate a Device for Request - /// - /// an instance of XDevice - /// specify requested device by an instance of XDevice - /// specify Excetion to thrown on failure - private void ValidateRequestAndGivenDevices( - XDevice device, - XDevice requestDevice, - Exception exception = null - ) - { - // - // Validate Args ... - ValidationProvider.NotNull(device, requestDevice); - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.InvalidDevice.ToException(); - } - - // - var isDevicesSame = device.IsSameAs(requestDevice); - - // - if (!isDevicesSame) - { - throw exception; - } - } - #endregion - - // - #region XVerification Request ... - /// - /// Validate Verification Request Exists by Device - /// - /// an instance of XDevice - /// specify Excetion to thrown on failure - /// - private async Task ValidateVerificationRequestExists( - XDevice device, - Exception exception = null - ) - { - // - ValidationProvider.NotNull(device); - - // - if (exception == null) - { - exception = XException.InvalidDevice.ToException(); - } - - // - var isExists = await IsDeviceRequestedForVerificationCodeBefor(device); - if (!isExists) - { - throw exception; - } - } - - /// - /// Validate Verification Request Exists by VerificationCode - /// - /// Confirm Verification Code - /// specify Excetion to thrown on failure - /// - private async Task ValidateVerificationRequestExists( - string verificationCode, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(verificationCode); - - // - if (exception == null) - { - exception = XException.InvalidVerificationCode.ToException(); - } - - // - var isExists = await IsVerificationCodeRequested(verificationCode); - if (!isExists) - { - throw exception; - } - } - - /// - /// Validate and Retrive Verification Request for Given Device - /// - /// an instance of XDevice - /// specify Excetion to thrown on failure - /// an instance of XVerificationRequest - private async Task ValidateAndRetrieveVerificationRequest( - XDevice device, - Exception exception = null - ) - { - // - ValidationProvider.NotNull(device); - - // - if (exception == null) - { - exception = XException.InvalidDevice.ToException(); - } - - // - await ValidateVerificationRequestExists(device); - - // - var result = await GetVerificationRequest(device); - if (result == null) - { - throw exception; - } - - // - return result; - } - - /// - /// Validate and Retrieve Verification Request for Given VerificationCode - /// - /// Confirm Verification Code - /// specify Excetion to thrown on failure - /// an instance of XVerificationRequest - private async Task ValidateAndRetrieveVerificationRequest( - string verificationCode, - Exception exception = null - ) - { - // - ValidationProvider.NotEmpty(verificationCode); - - // - if (exception == null) - { - exception = XException.InvalidVerificationCode.ToException(); - } - - // - await ValidateVerificationRequestExists(verificationCode); - - // - var result = await GetVerificationRequest(verificationCode); - if (result == null) - { - throw exception; - } - - // - return result; - } - - /// - /// Handle Prepare Verification Request - /// - /// Confirm Verification Code - /// an instance of XActionRequestToken - /// an instance of XVerificationRequest - private async Task HandleVerificationRequestPreparation( - string verificationCode, - XActionRequestToken request - ) - { - // - ValidationProvider - .NotEmpty(verificationCode); - - // - // Check Action Request Validation ... - ValidateActionRequest(request); - - // - var device = request.Context.Device; - - // - // Check is Device Requested Before or not ... - XVerificationRequest xVerificationRequest = null; - var isDeviceRequested = await IsDeviceRequestedForVerificationCodeBefor(device); - if (!isDeviceRequested) - { - // - xVerificationRequest = new XVerificationRequest - { - VerificationCode = verificationCode, - NumberOfTries = 1, - LastTryOn = DateTime.UtcNow, - Device = device, - Request = request - }; - - // - await AddVerificationRequest(xVerificationRequest); - } - else - { - // - // Get Verification Request ... - xVerificationRequest = await ValidateAndRetrieveVerificationRequest(device); - } - - // - return xVerificationRequest; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Providers\XIdentityManager\XIdentityManager+VerificationCode.cs - -using System.Threading.Tasks; -using xCommons.Extensions; -using xIdentityModels.Extensions; -using xIdentityModels.Models; -using xIdentityModels.Navigations; - -namespace xIds.Providers -{ - public partial class XIdentityManager - { - // - #region Verification Code Actions ... - /// - /// Check a Device Requeste for Verification Code before or not - /// - /// an instance of XDevice - /// a boolean value - private async Task IsDeviceRequestedForVerificationCodeBefor( - XDevice device - ) - { - // - var result = false; - var enumerator = DbContext.VerificationRequests - .AsAsyncEnumerable(); - await - foreach (var entity in enumerator) - { - // - if (entity.Device.IsSameAs(device)) - { - // - result = true; - break; - } - } - - // - return result; - } - - /// - /// Check a Verification Code Requested before or not - /// - /// Confirm Verification Code - /// a boolean value - private async Task IsVerificationCodeRequested( - string verificationCode - ) - { - // - // Validate Args ... - if (verificationCode.IsNullOrEmpty()) - { - return false; - } - - // - var result = false; - var enumerator = DbContext.VerificationRequests - .AsAsyncEnumerable(); - await - foreach (var entity in enumerator) - { - // - if (entity.VerificationCode == verificationCode) - { - // - result = true; - break; - } - } - - // - return result; - } - - /// - /// Retrieve Verification Request - /// - /// an instance of XDevice - /// an instance of XVerificationRequest - private async Task GetVerificationRequest( - XDevice device - ) - { - // - XVerificationRequest result = null; - var enumerator = DbContext.VerificationRequests - .AsAsyncEnumerable(); - await - foreach (var entity in enumerator) - { - // - if (entity.Device.IsSameAs(device)) - { - // - result = entity; - break; - } - } - - // - return result; - } - - /// - /// Retrieve Verification Request - /// - /// Confirm Verification Code - /// an instance of XVerificationRequest - private async Task GetVerificationRequest( - string verificationCode - ) - { - // - XVerificationRequest result = null; - var enumerator = DbContext.VerificationRequests - .AsAsyncEnumerable(); - await - foreach (var entity in enumerator) - { - // - if (entity.VerificationCode == verificationCode) - { - // - result = entity; - break; - } - } - - // - return result; - } - - /// - /// Remove Exists Verification Code Request - /// - /// an instance of XDevice - /// save changes on DbContext, default is true - /// - private async Task RemoveVerificationCodeRequestByDevice( - XDevice device, - bool saveChanges = true - ) - { - // - if (!await IsDeviceRequestedForVerificationCodeBefor(device)) - { - return; - } - - // - var xvr = await GetVerificationRequest(device); - DbContext.VerificationRequests.Remove(xvr); - - // - if (saveChanges) - { - await DbContext.SaveChangesAsync(); - } - } - - /// - /// Remove Exists Verification Code Request - /// - /// Confirm Verification Code - /// save changes on DbContext, default is true - /// - private async Task RemoveVerificationRequest( - string verificationCode, - bool saveChanges = true - ) - { - // - ValidationProvider.NotEmpty(verificationCode); - - // - var request = await GetVerificationRequest(verificationCode); - DbContext.VerificationRequests.Remove(request); - - // - if (saveChanges) - { - await DbContext.SaveChangesAsync(); - } - } - - /// - /// Add Verification Code Request - /// - /// an instance of XVerificationRequest - /// save changes on DbContext, default is true - /// an instance of XVerificationRequest - private async Task AddVerificationRequest( - XVerificationRequest request, - bool saveChanges = true - ) - { - // - if (await IsDeviceRequestedForVerificationCodeBefor(request.Device)) - { - await RemoveVerificationCodeRequestByDevice(request.Device); - } - - // - var entry = await DbContext.VerificationRequests.AddAsync(request); - - // - if (saveChanges) - { - await DbContext.SaveChangesAsync(); - } - - // - return entry.Entity; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Stores\XPersistedGrantStore.cs - -using System.Linq; -using IdentityServer4.Models; -using IdentityServer4.Stores; -using System.Threading.Tasks; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; -using IdentityServer4.EntityFramework.Mappers; -using IdentityServer4.EntityFramework.DbContexts; - -namespace xIds.Stores -{ - public class XPersistedGrantStore : IPersistedGrantStore - { - private readonly PersistedGrantDbContext dbContext; - - public XPersistedGrantStore(PersistedGrantDbContext dbContext) - { - this.dbContext = dbContext; - } - - public async Task> GetAllAsync(string subjectId) - { - // - var result = (await dbContext.PersistedGrants - .Where(g => g.SubjectId == subjectId) - .AsNoTracking() - .Select(res => res.ToModel()) - .ToListAsync()).AsEnumerable(); - - // - return result; - } - - public async Task GetAsync(string key) - { - // - var result = await dbContext.PersistedGrants - .FirstOrDefaultAsync(g => g.Key == key); - - // - return result.ToModel(); - } - - public async Task RemoveAllAsync(string subjectId, string clientId) - { - // - var items = await dbContext.PersistedGrants - .Where(g => - g.SubjectId == subjectId && - g.ClientId == clientId) - .ToListAsync(); - - // - dbContext.PersistedGrants.RemoveRange(items); - - // - await dbContext.SaveChangesAsync(); - } - - public async Task RemoveAllAsync(string subjectId, string clientId, string type) - { - // - var items = await dbContext.PersistedGrants - .Where(g => - g.SubjectId == subjectId && - g.ClientId == clientId && - g.Type == type) - .ToListAsync(); - - // - dbContext.PersistedGrants.RemoveRange(items); - - // - await dbContext.SaveChangesAsync(); - } - - public async Task RemoveAsync(string key) - { - // - var items = await dbContext.PersistedGrants - .Where(g => g.Key == key) - .ToListAsync(); - - // - dbContext.PersistedGrants.RemoveRange(items); - - // - await dbContext.SaveChangesAsync(); - } - - public async Task IsExistsAsync(string key) - { - return await this.dbContext.PersistedGrants.AnyAsync(g => g.Key == key); - } - - public async Task IsExistsAsync(PersistedGrant grant) - { - return await IsExistsAsync(grant.Key); - } - - public async Task AddOrUpdateAsync(PersistedGrant grant) - { - // - var isExists = await IsExistsAsync(grant); - if (isExists) - { - await UpdateAsync(grant); - } - else - { - await AddAsync(grant); - } - } - - public async Task AddAsync(PersistedGrant grant) - { - // - var item = grant.ToEntity(); - await dbContext.PersistedGrants.AddAsync(item); - await dbContext.SaveChangesAsync(); - } - - public async Task UpdateAsync(PersistedGrant grant) - { - // - var item = grant.ToEntity(); - var entity = dbContext.Attach(item); - entity.State = EntityState.Modified; - await dbContext.SaveChangesAsync(); - } - - public async Task StoreAsync(PersistedGrant grant) - { - await AddOrUpdateAsync(grant); - } - - // - // TODO: Complete this ... - public Task> GetAllAsync(PersistedGrantFilter filter) - { - throw new System.NotImplementedException(); - } - - // - // TODO: Complete this ... - public Task RemoveAllAsync(PersistedGrantFilter filter) - { - throw new System.NotImplementedException(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xIds\Validators\XResourceOwnerPasswordValidator.cs - -using System; -using xIds.Interfaces; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using IdentityServer4.Events; -using IdentityServer4.Models; -using IdentityServer4.Services; -using IdentityServer4.Validation; -using xIdentityModels.Navigations; -using Microsoft.Extensions.Logging; -using static IdentityModel.OidcConstants; - -namespace xIds.Validators -{ - public class XResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator - { - private readonly IXIdentityManager identityManager; - private readonly IEventService events; - private readonly ILogger logger; - - public XResourceOwnerPasswordValidator( - IXIdentityManager identityProvider, - IEventService events, - ILogger logger - ) - { - this.identityManager = identityProvider; - this.events = events; - this.logger = logger; - } - - /// - /// Validates the resource owner password credential - /// by providing UserName/Email or PhoneNumber - /// - /// The context. - /// - public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) - { - // - var clientId = context.Request?.Client?.ClientId; - var xUser = await identityManager.GetUserAsync(context.UserName, true); - - // - // Check Force Data ... - var isForced = true; - var isForcedStr = context.Request?.Raw["force"]; - if (!isForcedStr.IsNullOrEmpty()) - { - isForced = isForcedStr.FromJSON(); - } - - // - XDevice device = null; - var language = context.Request?.Raw["language"]; - var deviceStr = context.Request?.Raw["device"]; - if (deviceStr.IsNullOrEmpty() && isForced) - { - // - logger.LogError($"Device not Found ..."); - - // - await events - .RaiseAsync( - new UserLoginFailureEvent( - xUser.UserName, - XException.InvalidDevice.ToXError().Message, - false, - clientId - )); - return; - } - device = isForced ? deviceStr.FromJSON() : null; - - // - XException exception; - if (!xUser.IsNull()) - { - // - var result = await identityManager - .CheckPasswordSignInAsync( - xUser, - context.Password, - device, - language, - true, - isForced - ); - if (result.Succeeded) - { - // - logger.LogInformation("Credentials validated for username: {username}", xUser.UserName); - - // - // Update User Last Login ... - xUser.LastLogin = DateTime.UtcNow; - await identityManager.UpdateUserAsync(xUser); - - // - await events.RaiseAsync( - new UserLoginSuccessEvent( - xUser.UserName, xUser.Id, xUser.UserName, false, clientId - )); - - // - context.Result = new GrantValidationResult(xUser.Id, AuthenticationMethods.Password); - return; - } - else if (result.IsLockedOut) - { - // - logger.LogInformation("Authentication failed for username: {username}, reason: locked out", xUser.UserName); - - // - exception = XException.AccountLockedOut; - await events - .RaiseAsync( - new UserLoginFailureEvent( - xUser.UserName, - exception.ToXError().Message, - false, - clientId - )); - } - else if (result.IsNotAllowed) - { - // - logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", xUser.UserName); - - // - exception = XException.NotAllowed; - await events - .RaiseAsync( - new UserLoginFailureEvent( - xUser.UserName, - exception.ToXError().Message, - false, - clientId - )); - } - else - { - // - logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", xUser.UserName); - - // - exception = XException.LoginFailed; - await events - .RaiseAsync( - new UserLoginFailureEvent( - xUser.UserName, - exception.ToXError().Message, - false, - clientId - )); - - // - - } - } - else - { - // - logger.LogInformation("No user found matching username: {username}", xUser.UserName); - - // - exception = XException.InvalidUserName; - await events - .RaiseAsync( - new UserLoginFailureEvent( - xUser.UserName, - exception.ToXError().Message, - false, - clientId - )); - } - - // - Exception ecs = exception.ToException(); - if (exception == XException.AccountLockedOut && xUser.LockoutEnd.HasValue) - { - // - var passedTime = xUser.LockoutEnd.Value.UtcDateTime; - ecs = XException.AccountLockedOut - .AddContentToException(passedTime.ToString()); - } - - // - context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, ecs.Message); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xLoggingService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xLoggingService-20261109_152621.txt deleted file mode 100644 index 127feac..0000000 --- a/Documents/GeneratedContext/xDashboard-xLoggingService-20261109_152621.txt +++ /dev/null @@ -1,1246 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Background\XLogDispatcher.cs - -using System; -using System.Threading; -using System.Threading.Tasks; -using xLoggingService.Models; -using xLoggingService.Interfaces; -using System.Collections.Generic; -using System.Collections.Concurrent; - -namespace xLoggingService.Background -{ - public sealed class XLogDispatcher : IDisposable - { - private readonly Task worker; - private readonly BlockingCollection queue; - private readonly IReadOnlyCollection writers; - private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); - - public XLogDispatcher( - int capacity, - IEnumerable writers - ) - { - // - queue = new BlockingCollection(Math.Max(100, capacity)); - this.writers = new List(writers) - .AsReadOnly(); - - // - worker = Task.Run(RunAsync); - } - - public void Enqueue(XLogEntry entry) - { - if (!queue.IsAddingCompleted && !queue.TryAdd(entry)) { } - } - - private async Task RunAsync() - { - // - try - { - // - foreach (var entry in queue.GetConsumingEnumerable(cancellation.Token)) - { - // - foreach (var writer in writers) - { - // - try - { - // - await writer.WriteAsync(entry, cancellation.Token) - .ConfigureAwait(false); - } - catch { } - } - } - } - catch (OperationCanceledException) { } - } - - public void Dispose() - { - // - queue.CompleteAdding(); - - // - try - { - worker.Wait(TimeSpan.FromSeconds(10)); - } - catch { } - - // - cancellation.Cancel(); - queue.Dispose(); - cancellation.Dispose(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Configuration\XLoggingServiceConfiguration.cs - -using Microsoft.Extensions.Logging; - -namespace xLoggingService.Configuration -{ - public sealed class XLoggingServiceConfiguration - { - public bool Enabled { get; set; } = false; - public XFileLogConfiguration File { get; set; } = new(); - public XLogQueueConfiguration Queue { get; set; } = new(); - public XEventLogConfiguration Event { get; set; } = new(); - public XDatabaseLogConfiguration Database { get; set; } = new(); - public LogLevel MinimumLevel { get; set; } = LogLevel.Information; - } - - public class XLogQueueConfiguration { - public bool Enabled { get; set; } - public int Capacity { get; set; } = 10000; - public int ShutdownTimeoutSeconds { get; set; } = 10; - } - - public class XFileLogConfiguration { - public bool Enabled { get; set; } - public string Format { get; set; } = "Json"; - public string Directory { get; set; } = "./Logs"; - public int RetainedFileCountLimit { get; set; } = 30; - public string FileName { get; set; } = "x-logging-.log"; - public LogLevel MinimumLevel { get; set; } = LogLevel.Information; - } - - public class XDatabaseLogConfiguration { - public bool Enabled { get; set; } = false; - public string ConnectionString { get; set; } - public string TableName { get; set; } = "XLogs"; - public bool AutoCreateTable { get; set; } = true; - public LogLevel MinimumLevel { get; set; } = LogLevel.Warning; - public string Provider { get; set; } = "Microsoft.Data.Sqlite"; - } - - public class XEventLogConfiguration { - public bool Enabled { get; set; } = false; - public string Sender { get; set; } = "Application"; - public string Action { get; set; } = "XLogCreated"; - public LogLevel MinimumLevel { get; set; } = LogLevel.Error; - public string Topic { get; set; } = "x-logging-service-logs"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Constants\ConfigurationNodeNames.cs - -namespace xLoggingService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string LOGGING_SERVICE_NODE = "LoggingServiceConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Constants\XLoggingServiceConstants.cs - -namespace xLoggingService.Constants -{ - public struct XLoggingServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XLoggingServiceDILogTag = "XLoggingService"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\DI\XDIHelperExtension.cs - -using System; -using OpenTelemetry.Logs; -using OpenTelemetry.Trace; -using xCommons.Extensions; -using xExceptions.Constants; -using OpenTelemetry.Resources; -using xLoggingService.Writers; -using xEventService.Interfaces; -using xLoggingService.Providers; -using xLoggingService.Constants; -using xLoggingService.Interfaces; -using xLoggingService.MIddlewares; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Hosting; -using Microsoft.AspNetCore.Builder; -using xLoggingService.Configuration; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace xLoggingService.DI -{ - public static class XDIHelperExtension - { - /// - /// Retrieve Logging Service Configuration ... - /// - /// - /// - public static XLoggingServiceConfiguration GetXLoggingServiceConfiguration( - this IConfiguration source - ) - { - // - var section = source - .GetSection(ConfigurationNodeNames.LOGGING_SERVICE_NODE); - - // - var result = section.Get(); - if (result.IsNull()) - { - result = new(); - } - - // - return result; - } - - /// - /// Extract Service Configurations and Register it ... - /// - /// - /// - public static void AddXLoggingServiceConfiguration( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXLoggingServiceConfiguration(); - source.AddXLoggingServiceConfiguration(config); - } - - /// - /// Register Service Configuration ... - /// - /// - /// - public static void AddXLoggingServiceConfiguration( - this IServiceCollection source, - XLoggingServiceConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - // - Log($"Invalid Configuration ..."); - XException.InvalidConfiguration.Throw(); - } - - // - source.AddSingleton(configuration); - Log($"Logging Configuration Registered Successfully ..."); - } - - /// - /// Register Logging Service ... - /// - /// - /// - public static void AddXLoggingService( - this IServiceCollection source, - IConfiguration configuration - ) - { - // - var config = configuration.GetXLoggingServiceConfiguration(); - source.AddLoggingService( - configuration: config, - lifeTime: ServiceLifetime.Scoped - ); - } - - /// - /// Enable Telemetry Service on Logging ... - /// - /// - public static void AddXTelemetryLogger( - this ILoggingBuilder builder - ) - { - // - AppContext.SetSwitch( - "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); - - // - // Clear Providers ... - builder.ClearProviders(); - builder.AddConsole(); - builder.AddOpenTelemetry(options => - { - // - options.SetResourceBuilder( - ResourceBuilder - .CreateDefault() - .AddService(nameof(xLoggingService))); - - // - options.AddOtlpExporter(); - }); - } - - /// - /// Add Telemetry Service to Services ... - /// - /// - /// - public static IHostBuilder AddXTelemetry( - this IHostBuilder builder - ) - { - // - // Configure Services ... - builder = builder - .ConfigureServices((hostContext, services) => - { - // - services - .AddOpenTelemetry() - .ConfigureResource(resource => - resource.AddService(nameof(xLoggingService))) - .WithTracing(tracing => - tracing - .AddAspNetCoreInstrumentation() - .AddHttpClientInstrumentation() - .AddOtlpExporter()); - }); - - // - return builder; - } - - /// - /// Use Request Logging Middleware ... - /// Log all Requests, and it's Flow to Logger ... - /// - /// - /// - public static IApplicationBuilder UseXRequestLogger( - this IApplicationBuilder source - ) - { - return source.UseMiddleware(); - } - - // - #region Private - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XLoggingServiceConstants.XLoggingServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Logging Service ... - /// - /// - /// - /// - private static void AddLoggingService( - this IServiceCollection services, - XLoggingServiceConfiguration configuration, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Validate ... - if (lifeTime.IsNull()) - { - // - Log($"Invalid Service Lifetime ..."); - XException.InvalidArgs.Throw(); - } - - // - // Register Service Configuration ... - services.AddXLoggingServiceConfiguration(configuration); - - // - // File Log Provider ... - if (configuration.File.Enabled) - { - // - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); - - // - Log("FileLogWriter registered."); - } - - // - // Database Log Provider ... - if (configuration.Database.Enabled) - { - // - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); - - // - Log("DatabaseLogWriter registered."); - } - - // - // Event Service Provider ... - if (configuration.Event.Enabled) - { - // - var eventService = services.GetRegisteredService(); - if (eventService.IsNull()) - { - // - Log("Event Service not Provided ..."); - XException.InvalidConfiguration.Throw(); - } - - // - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); - - // - Log("EventLogWriter registered."); - } - - // - services.TryAddEnumerable( - ServiceDescriptor.Singleton()); - - // - Log($"Logging Service registered successfully ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Extensions\XLoggingServiceExtensions.cs - -using xCommons.Extensions; -using xLoggingService.Models; -using xCommons.Configurations; - -namespace xLoggingService.Extensions -{ - public static class XLoggingServiceExtensions - { - /// - /// Enrich LogEntry ... - /// - /// - /// - /// - public static XLogEntry Enrich( - this XLogEntry source, - XAppConfiguration configuration - ) - { - // - if (source.IsNull() || configuration.IsNull()) - { - return source; - } - - // - source.Application = configuration.Name; - - // - return source; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Interfaces\IXLogWriter.cs - -using System.Threading; -using System.Threading.Tasks; -using xLoggingService.Models; - -namespace xLoggingService.Interfaces -{ - public interface IXLogWriter - { - /// - /// Write Log ... - /// - /// - /// - /// - Task WriteAsync( - XLogEntry entry, - CancellationToken cancellationToken - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\MIddlewares\XRequestLoggingMiddleware.cs - -using System; -using System.IO; -using xCommons.Models; -using System.Diagnostics; -using xCommons.Extensions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; - -namespace xLoggingService.MIddlewares -{ - public class XRequestLoggingMiddleware - { - // - private readonly RequestDelegate next; - private readonly bool useSimpleLogging = false; - private readonly ILogger logger; - - public XRequestLoggingMiddleware( - RequestDelegate next, - ILogger logger - ) - { - // - this.next = next; - this.logger = logger; - } - - public async Task InvokeAsync(HttpContext context) - { - // - if (useSimpleLogging) - { - await InvokeAsyncSimple(context); - } - else - { - await InvokeAsyncFull(context); - } - } - - public async Task InvokeAsyncSimple(HttpContext context) - { - // - var stopwatch = Stopwatch.StartNew(); - try - { - // - // Logging Request Start ... - logger.LogInformation( - "Handling request: {Method} {Path}", - context.Request.Method, - context.Request.Path - ); - - // - // Handling Request ... - await next(context); - - // - // Logging Request End ... - stopwatch.Stop(); - logger.LogInformation( - "Finished handling request: {Method} {Path} in {Elapsed}ms", - context.Request.Method, - context.Request.Path, - stopwatch.ElapsedMilliseconds - ); - } - catch (Exception ex) - { - // - // Logging Request Error ... - stopwatch.Stop(); - logger.LogError(ex, - "Request failed: {Method} {Path} after {Elapsed}ms", - context.Request.Method, - context.Request.Path, - stopwatch.ElapsedMilliseconds - ); - - // - // Throw Exception Agains for Handling using Top Level Middlewares ... - throw; - } - } - - public async Task InvokeAsyncFull(HttpContext context) - { - // - var stopwatch = Stopwatch.StartNew(); - try - { - // - // Logging Request Start ... - logger.LogInformation( - "Handling request: {Method} {Path}", - context.Request.Method, - context.Request.Path - ); - - // - var logModel = new XLoggerModel(); - - // - logModel.Path = context.Request.Path; - logModel.Schema = context.Request.Scheme; - logModel.Method = context.Request.Method; - logModel.Headers = context.Request.Headers; - logModel.Host = context.Request.Host.ToString(); - logModel.QueryString = context.Request.QueryString.ToString(); - logModel.UserID = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Not Authenticated"; - - // - logModel.Connection = new XLoggerHttpConnection - { - Id = context.Connection.Id, - RemoteIpAddress = context.Connection.RemoteIpAddress.ToString(), - RemotePort = context.Connection.RemotePort.ToString(), - LocalIpAddress = context.Connection.LocalIpAddress.ToString(), - LocalPort = context.Connection.LocalPort.ToString(), - }; - - // - // Check if a request is a Post Call so read data from Body ... - if (context.Request.Method.ToNormalString() == "post") - { - // - context.Request.EnableBuffering(); - var request = await new StreamReader(context.Request.Body) - .ReadToEndAsync(); - - // - context.Request.Body.Position = 0; - logModel.Request = request; - } - - // - logModel.RequestedOn = DateTime.UtcNow; - - // - // Do Request ... - await next.Invoke(context); - - // - using (Stream originalRequest = context.Response.Body) - { - try - { - // - using (var memStream = new MemoryStream()) - { - // - context.Response.Body = memStream; - - // - // All the Request processing as described above - // happens from here. - // Response handling starts from here - // set the pointer to the beginning of the - // memory stream to read - memStream.Position = 0; - - // - // read the memory stream till the end - var response = await new StreamReader(memStream) - .ReadToEndAsync(); - - // - logModel.Response = response; - logModel.RespondedOn = DateTime.UtcNow; - logModel.StatusCode = context.Response.StatusCode; - logModel.IsSucceed = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299; - - // - // since we have read till the end of the stream, - // reset it onto the first position - memStream.Position = 0; - - // - // now copy the content of the temporary memory - // stream we have passed to the actual response body - // which will carry the response out. - await memStream.CopyToAsync(originalRequest); - } - } - catch (Exception ex) - { - // - // Log Exception ... - logModel.Exception = ex; - logger.LogError($"Error on Logging Request/Response ... {ex.ToJSON()}"); - } - finally - { - // - // assign the response body to the actual context - logModel.RespondedOn = DateTime.UtcNow; - context.Response.Body = originalRequest; - } - } - - // - // Logging Request End ... - stopwatch.Stop(); - logger.LogInformation( - "Finished handling request: {Method} {Path} in {Elapsed}ms", - context.Request.Method, - context.Request.Path, - stopwatch.ElapsedMilliseconds - ); - - // - // Log Response ... - logger.LogCritical($"Http Response/Response Information:{Environment.NewLine}" + - $"Schema:{logModel.Schema} " + Environment.NewLine + - $"Host: {logModel.Host} " + Environment.NewLine + - $"Path: {logModel.Path} " + Environment.NewLine + - $"Method: {logModel.Method} " + Environment.NewLine + - $"UserID: {logModel.UserID} " + Environment.NewLine + - $"QueryString: {context.Request.QueryString} " + Environment.NewLine + - $"Headers: {logModel.Headers.ToJSON()}" + Environment.NewLine + - $"" + Environment.NewLine + - $"Http Connection: " + Environment.NewLine + - $"Id: {logModel.Connection.Id}" + Environment.NewLine + - $"RemoteIpAddress: {logModel.Connection.RemoteIpAddress}" + Environment.NewLine + - $"RemotePort: {logModel.Connection.RemotePort}" + Environment.NewLine + - $"LocalIpAddress: {logModel.Connection.LocalIpAddress}" + Environment.NewLine + - $"LocalPort: {logModel.Connection.LocalPort}" + Environment.NewLine + - $"" + Environment.NewLine + - $"Request Body: {logModel.Request}" + Environment.NewLine + - $"RequestedOn: {logModel.RequestedOn}" + Environment.NewLine + - $"" + Environment.NewLine + - $"IsSucceed: {logModel.IsSucceed}" + Environment.NewLine + - $"StatucCode: {logModel.StatusCode}" + Environment.NewLine + - $"Response Body: {logModel.Response}" + Environment.NewLine + - $"RespondedOn: {logModel.RespondedOn}" + Environment.NewLine + - $"" + Environment.NewLine - ); - } - catch (Exception ex) - { - // - // Logging Request Error ... - stopwatch.Stop(); - logger.LogError(ex, - "Request failed: {Method} {Path} after {Elapsed}ms", - context.Request.Method, - context.Request.Path, - stopwatch.ElapsedMilliseconds - ); - - // - // Throw Exception Agains for Handling using Top Level Middlewares ... - throw; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Models\XLogEntry.cs - -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; - -namespace xLoggingService.Models -{ - /// - /// a Log which Issued ... - /// - public class XLogEntry - { - public int EventId { get; set; } - public string State { get; set; } - public string SpanId { get; set; } - public LogLevel Level { get; set; } - public string Message { get; set; } - public string TraceId { get; set; } - public string Category { get; set; } - public string Exception { get; set; } - public DateTime Timestamp { get; set; } - public string Application { get; set; } - public string Environment { get; set; } - public string MachineName { get; set; } - public string CorrelationId { get; set; } - public IDictionary Scope { get; set; } = new Dictionary(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Providers\XLoggerProvider.cs - -using System; -using Newtonsoft.Json; -using System.Diagnostics; -using xLoggingService.Models; -using xCommons.Configurations; -using System.Collections.Generic; -using xLoggingService.Background; -using xLoggingService.Interfaces; -using Microsoft.Extensions.Logging; -using xLoggingService.Configuration; - -namespace xLoggingService.Providers -{ - public class XLoggerProvider : ILoggerProvider - { - // - private readonly XLogDispatcher dispatcher; - private readonly XAppConfiguration configuration; - private readonly XLoggingServiceConfiguration config; - private readonly IReadOnlyCollection writers; - - public XLoggerProvider( - XAppConfiguration configuration, - XLoggingServiceConfiguration config, - IEnumerable writers - ) - { - // - this.config = config; - this.configuration = configuration; - this.writers = new List(writers) - .AsReadOnly(); - - // - dispatcher = new XLogDispatcher( - config.Queue.Capacity, this.writers); - } - - public ILogger CreateLogger(string categoryName) - { - // - return new XLogger( - config: config, - category: categoryName, - dispatcher: dispatcher, - configuration: configuration - ); - } - - public void Dispose() - { - dispatcher.Dispose(); - } - } - - public class XLogger : ILogger - { - // - private readonly string category; - private readonly XLogDispatcher dispatcher; - private readonly XAppConfiguration configuration; - private readonly XLoggingServiceConfiguration config; - - public XLogger( - string category, - XLogDispatcher dispatcher, - XAppConfiguration configuration, - XLoggingServiceConfiguration config - ) - { - // - this.config = config; - this.category = category; - this.dispatcher = dispatcher; - this.configuration = configuration; - } - - public IDisposable BeginScope(TState state) - { - return NullScope.Instance; - } - - public bool IsEnabled(LogLevel level) - { - // - var result = - config.Enabled && - level >= config.MinimumLevel && - level != LogLevel.None; - - // - return result; - } - - public void Log( - LogLevel level, - EventId eventId, - TState state, - Exception exception, - Func formatter - ) - { - // - if (!IsEnabled(level)) - { - return; - } - - // - var activity = Activity.Current; - dispatcher.Enqueue(new XLogEntry - { - Level = level, - Category = category, - EventId = eventId.Id, - TraceId = activity?.Id, - SpanId = activity?.RootId, - Timestamp = DateTime.UtcNow, - Message = formatter == null - ? state == null - ? string.Empty - : state.ToString() - : formatter(state, exception), - Exception = exception == null - ? null - : exception.ToString(), - State = state == null - ? null : - JsonConvert.SerializeObject(state), - Application = configuration.Name, - MachineName = Environment.MachineName, - Environment = configuration.Environment, - }); - } - - private sealed class NullScope : IDisposable { - public static readonly NullScope Instance = new(); - public void Dispose() { } - } - } -} - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XDatabaseLogWriter.cs - -using System; -using System.Threading; -using System.Data.Common; -using xCommons.Extensions; -using System.Threading.Tasks; -using xLoggingService.Models; -using xCommons.Configurations; -using xLoggingService.Interfaces; -using xLoggingService.Extensions; -using xLoggingService.Configuration; - -namespace xLoggingService.Writers -{ - public sealed class XDatabaseLogWriter : IXLogWriter - { - // - private bool initialized; - private readonly object sync = new(); - private readonly XDatabaseLogConfiguration config; - private readonly XAppConfiguration appConfiguration; - - public XDatabaseLogWriter( - XDatabaseLogConfiguration config, - XAppConfiguration appConfiguration - ) - { - // - this.config = config; - this.appConfiguration = appConfiguration; - } - - public Task WriteAsync( - XLogEntry e, - CancellationToken token - ) - { - // - if (e.IsNull()) - { - return Task.CompletedTask; - } - - // - // Handle Task Enrichment ... - e = e.Enrich(appConfiguration); - - // - if (e.Level < config.MinimumLevel || config.ConnectionString.IsNullOrEmpty()) - { - return Task.CompletedTask; - } - - // - try - { - // - lock (sync) - { - // - using (var c = CreateConnection()) - { - // - c.Open(); - if (!initialized) - { - using (var cmd = c.CreateCommand()) - { - // - cmd.CommandText = $"CREATE TABLE IF NOT EXISTS [{config.TableName}] (Id INTEGER PRIMARY KEY, Timestamp TEXT, Level TEXT, Category TEXT, EventId INTEGER, Message TEXT, Exception TEXT, State TEXT, Application TEXT, Environment TEXT, MachineName TEXT, TraceId TEXT, SpanId TEXT, CorrelationId TEXT)"; - cmd.ExecuteNonQuery(); - } - initialized = true; - } - - // - using (var cmd = c.CreateCommand()) - { - // - cmd.CommandText = $"INSERT INTO [{config.TableName}] (Timestamp,Level,Category,EventId,Message,Exception,State,Application,Environment,MachineName,TraceId,SpanId,CorrelationId) VALUES (@Timestamp,@Level,@Category,@EventId,@Message,@Exception,@State,@Application,@Environment,@MachineName,@TraceId,@SpanId,@CorrelationId)"; - - // - Add(cmd, "@State", e.State); - Add(cmd, "@SpanId", e.SpanId); - Add(cmd, "@EventId", e.EventId); - Add(cmd, "@Message", e.Message); - Add(cmd, "@TraceId", e.TraceId); - Add(cmd, "@Category", e.Category); - Add(cmd, "@Exception", e.Exception); - Add(cmd, "@Level", e.Level.ToString()); - Add(cmd, "@Application", e.Application); - Add(cmd, "@Environment", e.Environment); - Add(cmd, "@MachineName", e.MachineName); - Add(cmd, "@CorrelationId", e.CorrelationId); - Add(cmd, "@Timestamp", e.Timestamp.ToString("O")); - - // - cmd.ExecuteNonQuery(); - } - } - } - } - catch { } - - // - return Task.CompletedTask; - } - - private DbConnection CreateConnection() - { - // - var typeName = - config.Provider == "Microsoft.Data.Sqlite" - ? "Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite" - : config.Provider == "System.Data.SqlClient" ? - "System.Data.SqlClient.SqlConnection, System.Data.SqlClient" - : config.Provider; - - // - var type = Type.GetType(typeName, false); - if (type.IsNull()) - { - throw new InvalidOperationException("Database provider was not found: " + typeName); - } - - // - var c = (DbConnection)Activator.CreateInstance(type); - c.ConnectionString = config.ConnectionString; - - // - return c; - } - - private static void Add( - DbCommand c, - string name, - object value - ) { - // - var p = c.CreateParameter(); - p.ParameterName = name; - p.Value = (object)value ?? DBNull.Value; - c.Parameters.Add(p); - } - } -} - - - - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XEventLogWriter.cs - -using System; -using System.Threading; -using xCommons.Extensions; -using xEventService.Models; -using System.Threading.Tasks; -using xLoggingService.Models; -using xCommons.Configurations; -using xEventService.Interfaces; -using System.Collections.Generic; -using xLoggingService.Interfaces; -using xLoggingService.Extensions; -using xLoggingService.Configuration; - -namespace xLoggingService.Writers -{ - public sealed class XEventLogWriter : IXLogWriter - { - - // - private readonly XAppConfiguration appConfiguration; - private readonly XLoggingServiceConfiguration config; - private readonly Func resolver; - - public XEventLogWriter( - XAppConfiguration appConfiguration, - XLoggingServiceConfiguration config, - Func resolver - ) - { - // - this.config = config; - this.resolver = resolver; - this.appConfiguration = appConfiguration; - } - - public async Task WriteAsync( - XLogEntry entry, - CancellationToken token - ) - { - // - if (entry.IsNull()) - { - return; - } - - // - // Handle Task Enrichment ... - entry = entry.Enrich(appConfiguration); - - // - var provider = resolver(); - if (provider.IsNull() || entry.Level < config.Event.MinimumLevel) - { - return; - } - - // - var payload = new Dictionary { - { nameof(XLogEntry.Category), entry.Category }, - { nameof(XLogEntry.Level), entry.Level.ToString() }, - { nameof(XLogEntry.State), entry.State ?? string.Empty }, - { nameof(XLogEntry.TraceId), entry.TraceId ?? string.Empty } , - { nameof(XLogEntry.Exception), entry.Exception ?? string.Empty }, - }; - - // - await provider.SendMessageAsync( - new XEventMessage - { - Payload = payload, - Message = entry.Message, - Offset = entry.Timestamp, - Sender = config.Event.Sender, - Action = config.Event.Action, - }, - config.Event.Topic, - token - ).ConfigureAwait(false); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XFileLogWriter.cs - -using System; -using System.IO; -using System.Text; -using Newtonsoft.Json; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xLoggingService.Models; -using xCommons.Configurations; -using xLoggingService.Interfaces; -using xLoggingService.Extensions; -using xLoggingService.Configuration; - -namespace xLoggingService.Writers -{ - public sealed class XFileLogWriter : IXLogWriter - { - // - private readonly object sync = new(); - private readonly XAppConfiguration appConfiguration; - private readonly XLoggingServiceConfiguration configuration; - - public XFileLogWriter( - XAppConfiguration appConfiguration, - XLoggingServiceConfiguration configuration - ) - { - // - if (configuration.IsNull() || appConfiguration.IsNull()) - { - XException.InvalidConfiguration.Throw(); - } - - // - this.configuration = configuration; - this.appConfiguration = appConfiguration; - - // - Directory.CreateDirectory(configuration.File.Directory); - } - - public Task WriteAsync( - XLogEntry entry, - CancellationToken token - ) - { - // - if (entry.IsNull()) - { - return Task.CompletedTask; - } - - // - // Handle Task Enrichment ... - entry = entry.Enrich(appConfiguration); - - // - if (entry.Level < configuration.File.MinimumLevel) - { - return Task.CompletedTask; - } - - // - var path = Path.Combine(configuration.File.Directory, configuration.File.FileName.Replace("-", "-")); - - // - lock (sync) - { - // - File.AppendAllText(path, configuration.File.Format.Equals( - "Json", - StringComparison.OrdinalIgnoreCase) - ? JsonConvert.SerializeObject(entry) + Environment.NewLine - : $"{entry.Timestamp:O} [{entry.Level}] {entry.Category}: {entry.Message}{Environment.NewLine}", Encoding.UTF8); - } - - // - return Task.CompletedTask; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xMessageService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xMessageService-20261109_152621.txt deleted file mode 100644 index a5e8b8a..0000000 --- a/Documents/GeneratedContext/xDashboard-xMessageService-20261109_152621.txt +++ /dev/null @@ -1,727 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Constants\ConfigurationNodeNames.cs - -namespace xMessageService.Constants { - public partial struct ConfigurationNodeNames { - public const string MESSAGE_NODE_NAME = "MessageConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Constants\xMessageServiceConstants.cs - -namespace xMessageService.Constants { - public struct xMessageServiceConstants { - public const string DEFAULT_EMPTY_PROVIDER = "EMPTY"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using xCommons.Extensions; -using xMessageService.Models; -using xMessageService.Constants; -using xMessageService.Providers; -using System.Collections.Generic; -using xMessageService.Interfaces; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xMessageService.DI { - public static partial class XDIHelperExtension { - /// - /// Retrieve XMessage Configuration from App Settings - /// - /// - /// - public static XMessageConfiguration GetXMessageConfiguration (this IConfiguration config) { - // - var xMessageConfigSection = config.GetSection (ConfigurationNodeNames.MESSAGE_NODE_NAME); - var xMessageConfiguration = xMessageConfigSection.Get (); - - // - var defaultMailConfiguration = new Dictionary { - ["EMPTY"] = - new XMailConfiguration { - Title = xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER, - Host = "", - Port = 25, - EnableSsl = false, - Username = "", - Password = "" - } - }; - - // - var defaultSmsConfiguration = new Dictionary { - ["EMPTY"] = - new XSmsConfiguration { - ServiceUrl = "", - Username = "", - Password = "", - LineNumber = "", - UserApiKey = "", - SecretKey = "", - } - }; - - // - if (xMessageConfiguration.IsNull ()) { - // - xMessageConfiguration = new XMessageConfiguration { - DefaultSMSProvider = xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER, - DefaultMailProvider = xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER, - MailConfigurations = defaultMailConfiguration, - SmsConfigurations = defaultSmsConfiguration - }; - - // - // Warn Message is Default Configuration ... - Console.WriteLine ($"IMPORTANT: xMessageService Configuration is Default, so the Service can't works properly ..."); - } - - // - // Handle Default Mail Provider ... - if (xMessageConfiguration.DefaultMailProvider.IsNullOrEmpty ()) { - // - if (xMessageConfiguration.IsNull () || - // - xMessageConfiguration.MailConfigurations.IsNull () || - xMessageConfiguration.MailConfigurations.Count == 0) { - // - Console.WriteLine ("There is no defined Mail Provider Configurations ..."); - xMessageConfiguration.DefaultMailProvider = xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER; - } - - // - if (xMessageConfiguration.DefaultMailProvider == xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER) { - xMessageConfiguration.MailConfigurations = defaultMailConfiguration; - } else { - xMessageConfiguration.DefaultMailProvider = xMessageConfiguration.MailConfigurations.Keys.First (); - } - } - - // - // Handle Default SMS Provider ... - if (xMessageConfiguration.DefaultSMSProvider.IsNullOrEmpty ()) { - // - if (xMessageConfiguration.IsNull () || - xMessageConfiguration.SmsConfigurations.IsNull () || - xMessageConfiguration.SmsConfigurations.Count == 0) { - // - Console.WriteLine ("There is no defined SMS Provider Configurations ..."); - xMessageConfiguration.DefaultSMSProvider = xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER; - } - - // - if (xMessageConfiguration.DefaultSMSProvider == xMessageServiceConstants.DEFAULT_EMPTY_PROVIDER) { - xMessageConfiguration.SmsConfigurations = defaultSmsConfiguration; - } else { - xMessageConfiguration.DefaultSMSProvider = xMessageConfiguration.SmsConfigurations.Keys.First (); - } - } - - // - return xMessageConfiguration; - } - - /// - /// Register XMessage Service - /// - /// - /// - public static void AddXMessageService (this IServiceCollection services, IConfiguration config) { - // - var xMessageConfiguration = config.GetXMessageConfiguration (); - services.AddSingleton (xMessageConfiguration); - - // - // Register SMS Service ... - var xSmsService = new XSmsService ( - xMessageConfiguration.DefaultSMSProvider, - xMessageConfiguration.SmsConfigurations - ); - services.AddSingleton (xSmsService); - - // - // Register Mail Service ... - var xMailService = new XMailService ( - xMessageConfiguration.DefaultMailProvider, - xMessageConfiguration.MailConfigurations - ); - services.AddSingleton (xMailService); - - // - // Register MEssage Provider ... - services.AddSingleton (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Interfaces\IXMailService.cs - -using System.Threading.Tasks; -using xMessageService.Models; - -namespace xMessageService.Interfaces { - public partial interface IXMailService { - Task SendMailAsync ( - XMessage message, - string provider = null - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Interfaces\IXMessageProvider.cs - -using System; -using System.Threading.Tasks; -using xMessageService.Models; - -namespace xMessageService.Interfaces { - public partial interface IXMessageProvider { - bool IsReady ( - bool? checkMailService = false, - bool? checkSmsService = false - ); - - Task SendMailAsync ( - XMessage message, - string provider = null, - bool throwException = true, - Exception exception = null - ); - - Task SendSmsAsync ( - XMessage message, - string provider = null, - bool throwException = true, - Exception exception = null - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Interfaces\IXSmsService.cs - -using System.Threading.Tasks; -using xMessageService.Models; - -namespace xMessageService.Interfaces { - public partial interface IXSmsService { - Task SendSmsAsync ( - XMessage message, - string provider = null - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Models\XMailConfiguration.cs - -namespace xMessageService.Models { - public partial class XMailConfiguration { - public string Title { get; set; } - public string Host { get; set; } - public int Port { get; set; } - public bool EnableSsl { get; set; } - public string Username { get; set; } - public string Password { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Models\XMessage.cs - -using xModels.Base; -using System.Collections.Generic; - -namespace xMessageService.Models { - public partial class XMessage : XBaseDto { - public HashSet Recievers { get; set; } = new HashSet (); - public string Message { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Models\XMessageConfiguration.cs - -using System.Collections.Generic; - -namespace xMessageService.Models { - public partial class XMessageConfiguration { - public string DefaultSMSProvider { get; set; } - public string DefaultMailProvider { get; set; } - public IDictionary MailConfigurations { get; set; } - public IDictionary SmsConfigurations { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Models\XSmsConfiguration.cs - -namespace xMessageService.Models { - public partial class XSmsConfiguration { - public string ServiceUrl { get; set; } - public string Username { get; set; } - public string Password { get; set; } - public string LineNumber { get; set; } - public string UserApiKey { get; set; } - public string SecretKey { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Providers\XMailService.cs - -using System; -using System.Net; -using System.Net.Mail; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xMessageService.Models; -using System.Collections.Generic; -using xMessageService.Interfaces; - -namespace xMessageService.Providers { - public partial class XMailService : IXMailService { - private SmtpClient smtpClient; - private readonly string defaultProvider; - private readonly IDictionary configurations; - - public XMailService ( - string defaultProvider, - IDictionary configurations - ) { - this.defaultProvider = defaultProvider; - this.configurations = configurations; - - // - // Get instance of SMTP Client ... - PrepareSmtpClient (); - } - - public Task SendMailAsync ( - XMessage message, - string provider = null - ) { - // - // Run Send Mail Asynchronous ... - return Task.Run (() => { - SendMail (message, provider); - }); - } - - #region Private ... - /// - /// Validate and Retrieve Provider Configuration for Service - /// - /// - /// - private XMailConfiguration GetConfiguration (string provider = null) { - // - if (provider.IsNullOrEmpty ()) { - provider = defaultProvider; - } - - // - if (!configurations.Keys.Contains (provider)) { - XException.MessageServiceInitialFailed.Throw (); - } - - // - return configurations[provider]; - } - - /// - /// Prepare SMTP Client by Using Specified/Default Provider - /// - /// - private void PrepareSmtpClient (string provider = null) { - // - var config = GetConfiguration (provider); - if (config.IsNull()) { - return; - } - - // - smtpClient = new SmtpClient () { - Host = config.Host, - Port = config.Port, - EnableSsl = config.EnableSsl, - UseDefaultCredentials = false, - Credentials = new NetworkCredential ( - config.Username, - config.Password) - }; - } - - /// - /// Prepare Mail Message With Specified/Default Provider - /// - /// - /// - /// - private MailMessage PrepareMailMessage ( - XMessage message, - string provider = null - ) { - // - if (message == null || - message.Message.IsNullOrEmpty () || - message.Recievers.Count == 0) { - XException.InvalidMessage.Throw (); - } - - // - var config = GetConfiguration (provider); - var mailMessage = new MailMessage () { - From = new MailAddress (config.Username), - Subject = config.Title, - Body = message.Message - }; - - // - foreach (var reciever in message.Recievers) { - mailMessage.To.Add (reciever); - } - - // - return mailMessage; - } - - /// - /// Send Mail Using Specified/Default Provider - /// - /// - /// - private void SendMail ( - XMessage message, - string provider = null - ) { - // - if (smtpClient.IsNull()) { - // - Console.WriteLine ($"SMTP Error: MessageServiceInitialFailed ..."); - XException.MessageServiceInitialFailed.Throw (); - } - - // - var mailMessage = PrepareMailMessage (message, provider); - - // - try { - smtpClient.Send (mailMessage); - } catch (Exception ex) { - // - Console.WriteLine ($"SMTP Error: {ex.Message}"); - XException.MessageServiceInitialFailed.Throw (); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Providers\XMessageProvider.cs - -using System; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xMessageService.Models; -using xMessageService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xMessageService.Providers { - public partial class XMessageProvider : IXMessageProvider { - private readonly XMessageConfiguration configuration; - private readonly ILogger logger; - private readonly IXSmsService smsService; - private readonly IXMailService mailService; - - public XMessageProvider ( - XMessageConfiguration configuration, - ILogger logger, - IXSmsService smsService, - IXMailService mailService - ) { - this.configuration = configuration; - this.logger = logger; - this.smsService = smsService; - this.mailService = mailService; - } - - /// - /// Send a Mail Message - /// - /// - /// - /// - /// - /// - public async Task SendMailAsync ( - XMessage message, - string provider = null, - bool throwException = true, - Exception exception = null - ) { - // - if (exception.IsNull ()) { - exception = XException.ActionFailed.ToException (); - } - - // - try { - await mailService.SendMailAsync (message, provider); - } catch (Exception ex) { - // - logger.LogError ($"Exeption: {ex.Message}"); - - // - if (throwException) { - throw exception; - } - } - } - - /// - /// Send SMS Message - /// - /// - /// - /// - /// - /// - public async Task SendSmsAsync ( - XMessage message, - string provider = null, - bool throwException = true, - Exception exception = null - ) { - // - if (exception.IsNull ()) { - exception = XException.ActionFailed.ToException (); - } - - // - try { - await smsService.SendSmsAsync (message, provider); - } catch { - if (throwException) { - throw exception; - } - } - } - - /// - /// Check Message Provider is Ready or not - /// - /// - /// - /// - public bool IsReady ( - bool? checkMailService = false, - bool? checkSmsService = false - ) { - // - var result = true; - - // - // Check Mail Service ... - if (checkMailService.HasValue && - checkMailService.GetValueOrDefault ()) { - result = result && mailService != null; - } - - // - // Check Sms Service ... - if (checkSmsService.HasValue && - checkSmsService.GetValueOrDefault ()) { - result = result && smsService != null; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xMessageService\Providers\XSmsService.cs - -using System; -using RestSharp; -using PhoneNumbers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xMessageService.Models; -using System.Collections.Generic; -using xMessageService.Interfaces; - -namespace xMessageService.Providers { - public partial class XSmsService : IXSmsService { - private string serviceUrl; - private readonly string defaultProvider; - private readonly IDictionary configurations; - - public XSmsService ( - string defaultProvider, - IDictionary configurations - ) { - this.defaultProvider = defaultProvider; - this.configurations = configurations; - - // - PrepareServiceUrl (); - } - - public Task SendSmsAsync ( - XMessage message, - string provider = null - ) { - // - // Run Send SMS Asynchronous ... - return Task.Run (() => { - SendSMS (message, provider); - }); - } - - #region Private ... - /// - /// Prepare Service Url for Specified/Default Provider - /// - /// - private void PrepareServiceUrl (string provider = null) { - // - if (provider.IsNullOrEmpty ()) { - provider = defaultProvider; - } - - // - var config = GetConfiguration (provider); - if (config.IsNull ()) { - return; - } - - // - serviceUrl = config.ServiceUrl; - serviceUrl += "&username=" + config.Username + "&password=" + config.Password + "&"; - } - - /// - /// Prepare Service url for Integrating XMessage by - /// using Specified/Default Provider Configurations - /// - /// - /// - private void PrepareSmsMessage ( - XMessage message, - string provider = null - ) { - // - if (message == null || - message.Message.IsNullOrEmpty () || - message.Recievers.Count == 0) { - XException.InvalidMessage.Throw (); - } - - // - // Validating Mobile Numbers ... - var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance (); - var recieversList = ""; - - // - PrepareServiceUrl (provider); - - // - foreach (var reciever in message.Recievers) { - try { - // - var mPhoneNumber = phoneNumberUtil.Parse (reciever, null); - if (phoneNumberUtil.IsValidNumber (mPhoneNumber)) { - // - // Format Phone Numbers to the '+989120000000' pattern ... - var recieverPhone = phoneNumberUtil.Format (mPhoneNumber, PhoneNumberFormat.E164); - if (recieversList.Length > 0) { - recieversList += ","; - } - recieversList += reciever; - } - } catch { } - } - - // - var config = GetConfiguration (); - - // - // Preparing All Content and Configurations for Sending Messages ... - serviceUrl += "to=" + - recieversList + - "&message=" + - message.Message + - "&from=" + - config.LineNumber + - "&flash=" + - false; - } - - /// - /// Send a Message as SMS by Specified/Default Provider - /// - /// - /// - private void SendSMS ( - XMessage message, - string provider = null - ) { - // - if (serviceUrl.IsNullOrEmpty ()) { - // - Console.WriteLine ($"SMS Error: MessageServiceInitialFailed ..."); - XException.MessageServiceInitialFailed.Throw (); - } - - // - try { - // - // preparing Service Url based on message data ... - PrepareSmsMessage (message, provider); - - // - // Implementing Service Calling Using RestSharp Library ... - // We Select RestSharp because it supports Sync/Async Calls ... - var client = new RestClient (serviceUrl); - var request = new RestRequest (Method.POST); - - // - // Send Request ... - var response = client.Execute (request); - } catch (Exception ex) { - Console.WriteLine ($"SMS Error: {ex.Message}"); - XException.MessageServiceInitialFailed.Throw (); - } - } - - /// - /// Validate and Retrieve Provider Configuration for Service - /// - /// - /// - private XSmsConfiguration GetConfiguration (string provider = null) { - // - if ( - provider.IsNullOrEmpty () || - provider.ToNormalString () == "empty" - ) { - // - provider = defaultProvider; - return null; - } - - // - if (!configurations.Keys.Contains (provider)) { - XException.MessageServiceInitialFailed.Throw (); - } - - // - return configurations[provider]; - } - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xModels-20261109_152619.txt b/Documents/GeneratedContext/xDashboard-xModels-20261109_152619.txt deleted file mode 100644 index 6d9da66..0000000 --- a/Documents/GeneratedContext/xDashboard-xModels-20261109_152619.txt +++ /dev/null @@ -1,1620 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseClass.cs - -using System; -using xCommons.Extensions; -using xExceptions.Constants; -using Microsoft.Extensions.Logging; - -namespace xModels.Base { - /// - /// a Base class which carry required things as a Father for it's childs ... - /// - public abstract class XBaseClass { - // - #region Properties ... - /// - /// LogTag which Specified for this class ... - /// - private readonly string LOG_TAG; - - /// - /// logger instance ... - /// - private readonly ILogger logger; - #endregion - - // - #region Constructor ... - public XBaseClass (ILoggerFactory loggerFactory) { - // - // Preparing Log Tag ... - LOG_TAG = this.GetType ().Name; - - // - Type classType = this.GetType (); - logger = loggerFactory.CreateLogger (classType); - } - #endregion - - // - #region Protected ... - /// - /// Extract Prepared Log MEssage ... - /// - /// - /// - protected virtual string GetLogMessage (string message) { - // - // Prepare Log Message ... - message = $"{LOG_TAG} => {message}"; - return message; - } - - /// - /// Logging specific Message ... - /// - /// - /// - protected virtual void LogMessage ( - string message, - LogLevel logLevel = LogLevel.Information - ) { - // - // Validate Args ... - if (message.IsNullOrEmpty ()) { - throw XException.InvalidArgs - .ToException (); - } - - // - // Prepare Log Message ... - message = GetLogMessage (message); - - // - // Logging Message ... - logger.Log ( - message: message, - logLevel: logLevel - ); - } - - /// - /// Logging specific Message to Console ... - /// - /// - protected virtual void ConsoleMessage (string message) { - // - // Validate Args ... - if (message.IsNullOrEmpty ()) { - throw XException.InvalidArgs - .ToException (); - } - - // - // Prepare Log Message ... - message = GetLogMessage (message); - - // - // Logging Message ... - Console.WriteLine (message); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseDescriptor.cs - -namespace xModels.Base { - /// - /// Descriptors classes Map required data for creating Entities on Seeding time ... - /// this is a Base Descriptor class ... - /// - public abstract class XBaseDescriptor { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseDto.cs - -namespace xModels.Base { - /// - /// DTO - Data Transfer Objects is a kind of classes which Represent Entities ... - /// this is base Dto class ... - /// - public abstract class XBaseDto { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseEntity.cs - -using System.ComponentModel.DataAnnotations; - -namespace xModels.Base { - /// - /// Base Entity Class - /// - /// - public abstract class XBaseEntity { - /// - /// Entity Id - /// - /// entity unique id - [Key] - [Required] - public T Id { get; set; } - - /// - /// Provided Soft Delete Behaviour ... - /// - /// - public bool Deleted { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseEntityDto.cs - -namespace xModels.Base -{ - /// - /// Base Entity Related Dto Class ... - /// - /// - public abstract class XBaseEntityDto - { - /// - /// Entity Id - /// - /// entity unique id - public TKey Id { get; set; } - - /// - /// Provided Soft Delete Behaviour ... - /// - /// - public bool Deleted { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseGuidIDEntity.cs - -using System; - -namespace xModels.Base { - /// - /// a BaseEntity Class which has Id of Guid type - /// - public class XBaseGuidIDEntity : XBaseEntity { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseGuidIDEntityDto.cs - -using System; - -namespace xModels.Base -{ - public class XBaseGuidIDEntityDto : XBaseEntityDto - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseIntIDEntity.cs - -using System.ComponentModel.DataAnnotations; - -namespace xModels.Base { - /// - /// a BaseEntity Class which has Id of int type - /// - public abstract class XBaseIntIDEntity : XBaseEntity { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseIntIDEntityDto.cs - -namespace xModels.Base -{ - public class XBaseIntIDEntityDto : XBaseEntityDto - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseLongIDEntity.cs - -namespace xModels.Base -{ - public class XBaseLongIDEntity : XBaseEntity - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseLongIDEntityDto.cs - -namespace xModels.Base -{ - public class XBaseLongIDEntityDto : XBaseEntityDto - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseRangeRequest.cs - -using System.Collections.Generic; - -namespace xModels.Base { - /// - /// Range Request Classes Carry a List of Objects - /// - /// - public class XBaseRangeRequest { - public IEnumerable Items { get; set; } = new HashSet (); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseStorableDto.cs - -namespace xModels.Base { - public abstract class XBaseStorableDto : XBaseDto { - public abstract TKey Id { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseStorableDtoEventModel.cs - -namespace xModels.Base -{ - public class XBaseStorableDtoEventModel - { - public T Model { get; set; } - - public XBaseStorableDtoEventModel(T model) - { - Model = model; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseStoreEvent.cs - -using System; -using xModels.Interfaces; -using System.Reactive.Linq; -using System.Reactive.Subjects; -using System.Collections.Generic; - -namespace xModels.Base -{ - public abstract class XBaseStoreEvent : IXBaseStoreEvents - where T : XBaseStorableDto - { - // - private readonly ISubject> onAddSubject; - private readonly ISubject> onUpdateSubject; - private readonly ISubject> onRemoveSubject; - - // - private readonly ISubject>> onAddManySubject; - private readonly ISubject>> onUpdateManySubject; - private readonly ISubject>> onRemoveManySubject; - - // - public IObservable> OnAddObservable => onAddSubject.AsObservable(); - - public IObservable> OnUpdateObservable => onUpdateSubject.AsObservable(); - - public IObservable> OnRemoveObservable => onRemoveSubject.AsObservable(); - - // - - public IObservable>> OnAddManyObservable => onAddManySubject.AsObservable(); - - public IObservable>> OnUpdateManyObservable => onUpdateManySubject.AsObservable(); - - public IObservable>> OnRemoveManyObservable => onRemoveManySubject.AsObservable(); - - // - protected XBaseStoreEvent() - { - // - onAddSubject = new ReplaySubject>(1); - onUpdateSubject = new ReplaySubject>(1); - onRemoveSubject = new ReplaySubject>(1); - - // - onAddManySubject = new ReplaySubject>>(1); - onUpdateManySubject = new ReplaySubject>>(1); - onRemoveManySubject = new ReplaySubject>>(1); - } - - // - #region Base Actions ... - public void AddEvent(XBaseStorableDtoEventModel model) - { - onAddSubject.OnNext(model); - } - - public void AddManyEvent(XBaseStorableDtoEventModel> model) - { - onAddManySubject.OnNext(model); - } - - public void RemoveEvent(XBaseStorableDtoEventModel model) - { - onRemoveSubject.OnNext(model); - } - - public void RemoveManyEvent(XBaseStorableDtoEventModel> model) - { - onRemoveManySubject.OnNext(model); - } - - public void UpdateEvent(XBaseStorableDtoEventModel model) - { - onUpdateSubject.OnNext(model); - } - - public void UpdateManyEvent(XBaseStorableDtoEventModel> model) - { - onUpdateManySubject.OnNext(model); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseStringIDEntity.cs - -namespace xModels.Base { - /// - /// a BaseEntity Class which has Id of string type - /// - public class XBaseStringIDEntity : XBaseEntity { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseStringIDEntityDto.cs - -namespace xModels.Base -{ - public class XBaseStringIDEntityDto : XBaseEntityDto - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Base\XBaseValueContainer.cs - -namespace xModels.Base -{ - public class XBaseValueContainer - { - public T Value { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XBaseIndexedDto.cs - -using xModels.Base; - -namespace xModels.Dtos -{ - public class XBaseIndexedDto : XBaseDto - { - public T Item { get; set; } - public TKey Key { get; set; } - public TIndex Index { get; set; } - } - - public class XBaseIntIndexedDto : XBaseIndexedDto { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XDeviceDto.cs - -using xModels.Base; -using xCommons.Constants; - -namespace xModels.Dtos { - public class XDeviceDto : XBaseDto { - /// - /// Operating System - /// - /// device operating system identifier - public string Os { get; set; } - /// - /// Operating System Version - /// - /// which version of operatin system is in use - public string OsVersion { get; set; } - /// - /// Device Browser - /// - /// the Browser identifier - public string Browser { get; set; } - /// - /// Browser Engine Agent - /// - /// browser engine Agent - public string UserAgent { get; set; } - /// - /// Type of client Device - /// - /// represent device type XDeviceType - public XDeviceType DeviceType { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XFileDto.cs - -using System; -using xModels.Base; -using xCommons.Constants; -using System.ComponentModel.DataAnnotations; - -namespace xModels.Dtos { - public partial class XFileDto : XBaseDto { - [Required] - public string AuthorId { get; set; } - - public XFileType Type { get; set; } - - [Required] - [StringLength (255)] - public string Name { get; set; } - - [StringLength (255)] - public string Thumb { get; set; } - - [Required] - [StringLength (255)] - public string Path { get; set; } - - [StringLength (255)] - public string ThumbPath { get; set; } - - [Required] - public DateTime UploadedOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XObjectResponseResult.cs - -namespace xModels.Dtos { - /// - /// Some Requests Get Object Response Result of Data ... - /// - public struct XObjectResponseResult { - - public XObjectResponseResult (T responseObject, string responseText) { - this.Object = responseObject; - this.Text = responseText; - } - - public T Object { get; } - - public string Text { get; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XPersonDto.cs - -using xModels.Base; - -namespace xModels.Dtos -{ - /// - /// Since in Many Cases we have to Retrieve Specified User's Minimal - /// Infos for Handle Data Transfering, this Dto is Used ... - /// - public class XPersonDto : XBaseDto - { - public string Avatar { get; set; } - public string UserId { get; set; } - public string Username { get; set; } - public string Lastname { get; set; } - public string Firstname { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XQuery.cs - -using xModels.Base; - -namespace xModels.Dtos { - /// - /// Request a Page of Data Based on Query ... - /// this can used in every Data Providers ... - /// - public class XQuery : XBaseDto { - /// - /// an string for filtering results - /// - /// - public string Filter { get; set; } = null; - - /// - /// determines fully load object with it's relational fields or not - /// - /// - public bool ContainsDetail { get; set; } = false; - - /// - /// specifiy sorting of items - /// - /// - public string SortBy { get; set; } = nameof (XBaseIntIDEntity.Id); - - /// - /// specify sorting direction - /// - /// - public bool IsAscending { get; set; } = true; - - /// - /// specify page number - /// - /// - public int Page { get; set; } = 1; - - /// - /// specify page size - /// - /// - public int PageSize { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XQueryResult.cs - -using xModels.Base; -using System.Collections.Generic; - -namespace xModels.Dtos { - /// - /// Result of a Requested Page of Data Based on Query ... - /// this can used in every Data Providers ... - /// - public class XQueryResult : XBaseDto { - /// - /// a collection of items for a page ... - /// - /// - public IEnumerable Items { get; set; } - - /// - /// Current Page Number ... - /// - /// - public long Page { get; set; } - - /// - /// Current Page Size ... - /// - /// - public long PageSize { get; set; } - - /// - /// Total Pages ... - /// - /// - public long TotalPages { get; set; } - - /// - /// Total Filtered Items Pages Count ... - /// - /// - public int TotalFilteredPages { get; set; } - - /// - /// Total Filtered Items ... - /// - /// - public long TotalFilteredItems { get; set; } - - /// - /// Total Exists Items ... - /// - /// - public long TotalItems { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XResourceDto.cs - -using xModels.Base; -using System.Collections.Generic; - -namespace xModels.Dtos -{ - public class XLocaleResourceDto : XBaseDto - { - public string Language { get; set; } - public string Value { get; set; } - } - - public class XResourceDto : XBaseDto - { - public string Resource { get; set; } - public IEnumerable Locales { get; set; } = new HashSet(); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Dtos\XValidateRevisionRequest.cs - -using System.ComponentModel.DataAnnotations; - -namespace xModels.Dtos { - /// - /// in some cases we have to validate a revision of request, this is a model - /// which used to request a revision validator ... - /// - public class XValidateRevisionRequest { - [Required] - public string Revision { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Extensions\DIExtensions.cs - -using xModels.Base; -using xModels.Interfaces; -using xCommons.Extensions; -using xExceptions.Constants; -using Microsoft.Extensions.DependencyInjection; - -namespace xModels.Extensions { - public static class DIExtensions { - /// - /// Register an Specific Store in DI ... - /// - /// DI service collection ... - /// an implementation of inetrface of store ... - /// service lifetime - /// implementation of TType ... - /// an inetrface which implements IXBaseStore - /// type of an instance of XBaseStorable - /// type of key of StorableItem - /// - public static void AddXStore ( - this IServiceCollection services, - TImplementation store, - ServiceLifetime lifeTime = ServiceLifetime.Singleton - ) - where TImplementation : TType - where TType : IXBaseStore - where TStoreItemDto : XBaseStorableDto { - // - // Validate Args ... - if (store.IsNull ()) { - throw XException.InvalidArgs - .ToException (); - } - - // - // Register Service in DI ... - services.Add (new ServiceDescriptor (typeof (TType), typeof (TImplementation), lifeTime)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Extensions\XModelExtensions.cs - -using System.Linq; -using xModels.Dtos; -using xCommons.Extensions; -using System.Collections.Generic; - -namespace xModels.Extensions -{ - public static class XModelExtensions - { - /// - /// Check to XDevice instance to be same or not - /// - /// - /// - /// - public static bool IsSameAs(this XDeviceDto source, XDeviceDto dest) - { - // - if (source.IsNull() || - dest.IsNull()) - { - return false; - } - - // - var isSame = source.Os.ToNormalString() == dest.Os.ToNormalString() && - source.OsVersion.ToNormalString() == dest.OsVersion.ToNormalString() && - source.Browser.ToNormalString() == dest.Browser.ToNormalString() && - source.UserAgent.ToNormalString() == dest.UserAgent.ToNormalString() && - source.DeviceType == dest.DeviceType; - - // - return isSame; - } - - public static IEnumerable AsEnumerable( - this IEnumerable> source - ) - { - return source.Select(i => i.Item); - } - - public static string GetFullname(this XPersonDto source) - { - // - var result = string.Empty; - - // - if (!source.IsNullOrDefault()) - { - result = $"{source.Firstname} {source.Lastname}"; - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Interfaces\IXAuditable.cs - -using System; - -namespace xModels.Interfaces { - /// - /// Some times we need to wrap Entities by some logs or audits ... - /// this class provide Audit fields for an Auditable Entity ... - /// - public interface IXAuditable { - string UserAgent { get; } - string UserIp { get; } - DateTime TransactionTime { get; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Interfaces\IXBaseStore.cs - -using System; -using xModels.Base; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; - -namespace xModels.Interfaces { - public interface IXBaseStore where T : XBaseStorableDto { - // - #region Retrieve ... - /// - /// Retrieve all Exists Items ... - /// - /// - Task> GetAll (); - - /// - /// Retrieve specific Item by key ... - /// - /// - /// - Task Get (TKey key); - - /// - /// retrieve items based on specific condition ... - /// - /// - /// - Task> FindMany (Expression> condition); - - /// - /// retrieve item based on specific condition ... - /// - /// - /// - Task FindOne (Expression> condition); - #endregion - - // - #region Add ... - /// - /// add specific item to Store ... - /// - /// - /// - Task Add (T item); - - /// - /// Add a Collection of Items on Store ... - /// - /// - /// - Task AddMany (XBaseRangeRequest items); - #endregion - - // - #region Remove ... - /// - /// Remove an item from store ... - /// - /// - /// - Task Remove (T item); - - /// - /// remove an item by it's Key ... - /// - /// - /// - Task RemoveByKey (TKey key); - - /// - /// remove a collection of items at once ... - /// - /// - /// - Task RemoveMany(XBaseRangeRequest items); - #endregion - - // - #region Update ... - /// - /// Update Exists Item in store ... - /// - /// - /// - /// - /// - /// - /// - Task Update ( - T item, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueProviders = null, - bool updateWithNullOrEmptyValues = false - ); - - /// - /// Update a Collection of Exists Items ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateMany ( - XBaseRangeRequest items, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueProviders = null, - bool updateWithNullOrEmptyValues = false - ); - #endregion - - // - #region Exists ... - /// - /// retrieve item(s) exists based on specific condition ... - /// - /// - /// - Task IsExists (Expression> condition); - - /// - /// is exists an item by providing it's key ... - /// - /// - /// - Task IsExistsByKey (TKey key); - #endregion - - // - #region Count ... - /// - /// Count Exists items ... - /// - /// - Task Count (); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Interfaces\IXBaseStoreEvents.cs - -using System; -using xModels.Base; -using System.Collections.Generic; - -namespace xModels.Interfaces -{ - public interface IXBaseStoreEvents where T : XBaseStorableDto - { - // - void AddEvent(XBaseStorableDtoEventModel model); - void UpdateEvent(XBaseStorableDtoEventModel model); - void RemoveEvent(XBaseStorableDtoEventModel model); - - // - void AddManyEvent(XBaseStorableDtoEventModel> model); - void UpdateManyEvent(XBaseStorableDtoEventModel> model); - void RemoveManyEvent(XBaseStorableDtoEventModel> model); - - // - IObservable> OnAddObservable { get; } - IObservable> OnUpdateObservable { get; } - IObservable> OnRemoveObservable { get; } - - // - IObservable>> OnAddManyObservable { get; } - IObservable>> OnUpdateManyObservable { get; } - IObservable>> OnRemoveManyObservable { get; } - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xModels\Providers\XBaseInMemoryStore.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Interfaces; -using xCommons.Extensions; -using System.Threading.Tasks; -using System.Linq.Expressions; -using System.Collections.Generic; -using System.Collections.Concurrent; - -namespace xModels.Providers -{ - public abstract class XBaseInMemoryStore : IXBaseStore - where T : XBaseStorableDto - { - /// - /// this is main store of items ... - /// - /// - /// - private static ConcurrentBag STORE = new ConcurrentBag(); - - // - private readonly IXBaseStoreEvents events; - - // - #region Constructor ... - protected XBaseInMemoryStore( - IXBaseStoreEvents events = null - ) - { - this.events = events; - } - #endregion - - // - #region Retrieve ... - /// - /// Retrieve all Exists Items ... - /// - /// - public Task> GetAll() - { - // - var result = STORE.AsEnumerable(); - return Task.FromResult(result); - } - - /// - /// Retrieve specific Item by key ... - /// - /// - /// - public Task Get(TKey key) - { - // - return IsExistsByKey(key) - .ContinueWith(isExistsTask => - { - // - var isExists = isExistsTask - .RunTask(); - - // - if (!isExists) - { - return null; - } - - // - try - { - var result = STORE - .FirstOrDefault(i => GetKey(i).Equals(key)); - return result; - } - catch - { - return null; - } - }); - } - - /// - /// retrieve items based on specific condition ... - /// - /// - /// - public Task> FindMany(Expression> condition) - { - // - // Validate Args ... - if (condition.IsNull()) - { - return Task.FromResult(new List().AsEnumerable()); - } - - // - var whereFunc = condition.Compile(); - var result = STORE.Where(whereFunc); - - // - return Task.FromResult(result); - } - - /// - /// retrieve item based on specific condition ... - /// - /// - /// - public Task FindOne(Expression> condition) - { - // - // Validate Args ... - if (condition.IsNull()) - { - return null; - } - - // - var whereFunc = condition.Compile(); - var result = STORE.FirstOrDefault(whereFunc); - - // - return Task.FromResult(result); - } - #endregion - - // - #region Add ... - /// - /// add specific item to Store ... - /// - /// - /// - public Task Add(T item) - { - // - // Validate Args ... - if (item.IsNull() || GetKey(item).IsNull()) - { - return Task.FromResult(false); - } - - // - // Try to add item ... - return IsExistsByKey(GetKey(item)) - .ContinueWith(isExistsTask => - { - // - // Check item exists in Store or not ... - var isExists = isExistsTask.RunTask(); - if (isExists) - { - return false; - } - - // - // Add Item to Store ... - STORE.Add(item); - OnAdd(item); - - // - return true; - }); - } - - /// - /// Add a Collection of Items on Store ... - /// - /// - /// - public Task AddMany(XBaseRangeRequest items) - { - // - // Validate Args ... - if ( - items.IsNull() || - !items.Items.HasChild() - ) - { - return Task.FromResult(false); - } - - // - // Retrieve Must Add Items ... - var mustAddItems = items.Items - .Where(i => !GetKey(i) - .IsNull() && !STORE - .Any(si => GetKey(i).Equals(GetKey(si))) - ); - if (!mustAddItems.HasChild()) - { - return Task.FromResult(false); - } - - // - // Add Items ... - try - { - // - mustAddItems - .ToList() - .ForEach(mi => STORE.Add(mi)); - - // - OnAddMany(mustAddItems); - - // - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } - } - #endregion - - // - #region Remove ... - /// - /// Remove an item from store ... - /// - /// - /// - public Task Remove(T item) - { - // - // Validate Args ... - if ( - item.IsNull() || - !STORE - .Any(i => GetKey(i) - .Equals(GetKey(item))) - ) - { - return Task.FromResult(false); - } - - // - try - { - // - RemoveItemFromStore(item); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } - } - - /// - /// remove an item by it's Key ... - /// - /// - /// - public Task RemoveByKey(TKey key) - { - return Get(key) - .ContinueWith(getTask => - { - // - // retrieve item by it's Key ... - var item = getTask - .RunTask(); - - // - // Check item exists ... - if (item.IsNull()) - { - return false; - } - - // - // Try to remove item ... - var result = false; - try - { - // - result = Remove(item) - .RunTask(); - } - catch - { - result = false; - } - - // - return result; - }); - } - - /// - /// remove a collection of items at once ... - /// - /// - /// - public Task RemoveMany(XBaseRangeRequest items) - { - // - // Validate Args ... - if ( - items.IsNull() || - !items.Items.HasChild() - ) - { - return Task.FromResult(false); - } - - // - var mustRemovedItems = items.Items - .Where(i => STORE - .Any(si => GetKey(si).Equals(GetKey(i))) - ); - if (!mustRemovedItems.HasChild()) - { - return Task.FromResult(false); - } - - // - try - { - // - RemoveItemsFromStore(mustRemovedItems); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } - } - #endregion - - // - #region Update ... - /// - /// Update Exists Item in store ... - /// - /// - /// - /// - /// - /// - /// - public Task Update( - T item, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueProviders = null, - bool updateWithNullOrEmptyValues = false - ) - { - return Get(GetKey(item)) - .ContinueWith(getTask => - { - // - var existsItem = getTask - .RunTask(); - - // - // Validate item Exists ... - if (existsItem.IsNull()) - { - return null; - } - - // - try - { - // - var updatedItem = existsItem; - updatedItem.UpdateData( - updateWith: item, - propertyWhiteList: propertyWhiteList, - propertyBlackList: propertyBlackList, - propertyValueProviders: propertyValueProviders, - updateWithNullOrEmptyValues: updateWithNullOrEmptyValues, - throwExceptionOnFails: true - ); - - // - RemoveItemFromStore(existsItem); - STORE.Add(updatedItem); - OnUpdate(item); - - // - return updatedItem; - } - catch - { - return null; - } - }); - } - - /// - /// Update a Collection of Exists Items ... - /// - /// - /// - /// - /// - /// - /// - public Task UpdateMany( - XBaseRangeRequest items, - ICollection propertyWhiteList = null, - ICollection propertyBlackList = null, - ICollection>> propertyValueProviders = null, - bool updateWithNullOrEmptyValues = false - ) - { - // - // Validate Args ... - if ( - items.IsNull() || - !items.Items.HasChild() - ) - { - return Task.FromResult(false); - } - - // - // retrieve must updated items ... - var mustUpdateItems = items - .Items - .Where(i => STORE - .Any( - si => GetKey(i).Equals(GetKey(si))) - ); - if (!mustUpdateItems.HasChild()) - { - return Task.FromResult(false); - } - - // - // Do Tasks ... - var mustUpdateTasks = mustUpdateItems.Select(i => Update( - i, - propertyWhiteList: propertyWhiteList, - propertyBlackList: propertyBlackList, - propertyValueProviders: propertyValueProviders, - updateWithNullOrEmptyValues: updateWithNullOrEmptyValues - )); - return Task.WhenAll(mustUpdateTasks) - .ContinueWith(updateTasks => - { - // - var updatedItems = updateTasks - .RunTask(); - - // - if (!updatedItems.HasChild()) - { - return false; - } - else - { - // - OnUpdateMany(mustUpdateItems); - return true; - } - }); - } - #endregion - - // - #region Exists ... - /// - /// retrieve item(s) exists based on specific condition ... - /// - /// - /// - public Task IsExists(Expression> condition) - { - // - // Validate Args ... - if (condition.IsNull()) - { - return Task.FromResult(false); - } - - // - var whereFunc = condition.Compile(); - var result = STORE.Any(whereFunc); - - // - return Task.FromResult(result); - } - - /// - /// is exists an item by providing it's key ... - /// - /// - /// - public Task IsExistsByKey(TKey key) - { - return Task.Run(() => - { - return STORE.Any(i => GetKey(i).Equals(key)); - }); - } - #endregion - - // - #region Count ... - /// - /// Count Exists items ... - /// - /// - public Task Count() - { - // - var result = STORE.Count(); - return Task.FromResult(result); - } - #endregion - - // - #region Keys ... - /// - /// set Object Key ... - /// - /// - /// - public void SetKey( - ref T item, - TKey id - ) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - if (keyProp.IsNull()) - { - return; - } - - // - Type t = Nullable.GetUnderlyingType(keyProp.PropertyType) ?? keyProp.PropertyType; - object safeValue = (id == null) ? null : Convert.ChangeType(id, t); - keyProp.SetValue(item, safeValue, null); - } - - /// - /// Get Object Key ... - /// - /// - /// - public TKey GetKey(T item) - { - // - var props = item.GetType().GetProperties(); - var keyProp = props.FirstOrDefault(p => p.Name == "Id"); - - // - var keyString = string.Empty; - if (keyProp.IsNull()) - { - keyString = string.Empty; - } - else - { - keyString = keyProp.GetValue(item).ToString(); - } - - // - if (keyString.IsNullOrEmpty()) - { - return default(TKey); - } - - // - // Prevent Deserializing issues throug JsonReader ... - if (keyString.IsGuid() && typeof(TKey) == typeof(Guid)) - { - return item.Id; - } - - // - TKey result; - try - { - result = keyString.FromJSON(); - } - catch - { - result = keyString.ConvertTo(); - } - return result; - } - #endregion - - // - #region Private ... - private void RemoveItemFromStore(T item) - { - // - STORE = new ConcurrentBag( - STORE.Except(new[] { item }) - ); - - // - OnRemove(item); - } - - private void RemoveItemsFromStore(IEnumerable items) - { - // - STORE = new ConcurrentBag( - STORE.Except(items) - ); - - // - OnRemoveMany(items); - } - - // - #region Event Notifiers ... - private void OnAdd(T item) - { - // - if (!events.IsNull()) - { - events.AddEvent(new XBaseStorableDtoEventModel(item)); - } - } - private void OnUpdate(T item) - { - // - if (!events.IsNull()) - { - events.UpdateEvent(new XBaseStorableDtoEventModel(item)); - } - } - - private void OnRemove(T item) - { - // - if (!events.IsNull()) - { - events.RemoveEvent(new XBaseStorableDtoEventModel(item)); - } - } - - private void OnAddMany(IEnumerable items) - { - // - if (!events.IsNull()) - { - events.AddManyEvent(new XBaseStorableDtoEventModel>(items)); - } - } - - private void OnUpdateMany(IEnumerable items) - { - // - if (!events.IsNull()) - { - events.UpdateManyEvent(new XBaseStorableDtoEventModel>(items)); - } - } - - private void OnRemoveMany(IEnumerable items) - { - // - if (!events.IsNull()) - { - events.RemoveManyEvent(new XBaseStorableDtoEventModel>(items)); - } - } - #endregion - #endregion - } -} diff --git a/Documents/GeneratedContext/xDashboard-xPushService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xPushService-20261109_152620.txt deleted file mode 100644 index 46d847d..0000000 --- a/Documents/GeneratedContext/xDashboard-xPushService-20261109_152620.txt +++ /dev/null @@ -1,6502 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseDtoHub.cs - -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using xPushService.Interfaces; -using System.Collections.Generic; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.Logging; - -namespace xPushService.Base -{ - public abstract class XBaseDtoHub : XBaseHub, IXBaseDtoHub - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Constructor ... - protected XBaseDtoHub(ILogger logger) : base(logger) - { } - #endregion - - // - #region Actions ... - /// - /// Notify a New Item added ... - /// - /// - /// - /// - public async Task Add( - TDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Add.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify a New Item added ... - /// - /// - /// - /// - public async Task AddOrUpdate( - TDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Add Many Items ... - /// - /// - /// - /// - public async Task AddMany( - IEnumerable items, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - items.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Deleted ... - /// - /// - /// - /// - public async Task Delete( - TDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Delete.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Delete Many Items ... - /// - /// - /// - /// - public async Task DeleteMany( - IEnumerable items, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.DeleteMany.GetStringValue(), - items.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task Update( - TDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Update.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Update Many Items ... - /// - /// - /// - /// - public async Task UpdateMany( - IEnumerable items, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.UpdateMany.GetStringValue(), - items.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseDtoProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using System.Linq.Expressions; -using xDataService.Interfaces; -using xPushService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using System.Runtime.CompilerServices; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Base -{ - public abstract class XBaseDtoProvider : IXBaseDtoProvider - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Properties ... - public IHubContext Hub { get; } - public IXIdentityProvider IdentityProvider { get; } - public XDataServiceConfiguration DataConfiguration { get; } - public IXBaseRepositoryService Service { get; } - #endregion - - // - #region Constructor ... - protected XBaseDtoProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXBaseRepositoryService service, - IXIdentityProvider identityProvider = null - ) - { - // - Hub = hub; - Service = service; - IdentityProvider = identityProvider; - DataConfiguration = dataConfiguration; - } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddAsync( - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.UpdateAsync( - id: id, - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Update.GetStringValue() - ); - } - - // - return result; - } - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Delete.GetStringValue() - ); - } - - // - return result; - } - - /// - /// count all exists Items ... - /// - /// - /// - /// - public virtual async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - public virtual async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.GetAsync( - id: id, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - public virtual async IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default - ) - { - // - var enumerable = Service.GetAllAsAsyncEnumerable( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - await foreach (var dto in enumerable) - { - // - if (cancellationToken.IsCancellationRequested) - { - yield break; - } - - // - yield return dto; - } - } - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.FindOneAsync( - predicate: predicate, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.FindManyAsync( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.QueryAsync( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - public async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var actions = new List - { - XBaseEntityHubAction.Add.GetStringValue(), - XBaseEntityHubAction.Update.GetStringValue(), - XBaseEntityHubAction.Delete.GetStringValue(), - XBaseEntityHubAction.AddMany.GetStringValue(), - XBaseEntityHubAction.DeleteMany.GetStringValue(), - XBaseEntityHubAction.UpdateMany.GetStringValue(), - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - }; - - // - // Validate ... - var isValid = - !Hub.IsNull() && - !action.IsNullOrEmpty() && - !payLoad.IsNullOrEmpty() && - actions.Contains(action); - if (!isValid) - { - return; - } - - // - // Retrieve Connection Id ... - var clients = Hub.Clients.All; - if (!connectionId.IsNullOrEmpty()) - { - clients = Hub.Clients.AllExcept(connectionId); - } - - // - await clients.SendAsync( - action, - payLoad, - connectionId, - cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseEntityHub.cs - -using xModels.Base; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using xPushService.Interfaces; -using System.Collections.Generic; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.Logging; - -namespace xPushService.Base -{ - public abstract class XBaseEntityHub : XBaseHub, IXBaseEntityHub - where TEntity : XBaseEntity - { - // - #region Constructor ... - protected XBaseEntityHub(ILogger logger) : base(logger) - { } - #endregion - - // - #region Actions ... - /// - /// Notify a New Entity added ... - /// - /// - /// - /// - public async Task Add( - TEntity entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Add.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify a New Entity added ... - /// - /// - /// - /// - public async Task AddOrUpdate( - TEntity entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Add Many Entities ... - /// - /// - /// - /// - public async Task AddMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - entities.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Entity Deleted ... - /// - /// - /// - /// - public async Task Delete( - TEntity entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Delete.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Delete Many Entities ... - /// - /// - /// - /// - public async Task DeleteMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.DeleteMany.GetStringValue(), - entities.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Entity Updated ... - /// - /// - /// - /// - public async Task Update( - TEntity entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Update.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify Update Many Entities ... - /// - /// - /// - /// - public async Task UpdateMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.UpdateMany.GetStringValue(), - entities.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseEntityProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using System.Linq.Expressions; -using xDataService.Interfaces; -using xPushService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Base -{ - public abstract class XBaseEntityProvider : IXBaseEntityProvider - where TEntity : XBaseEntity - where THub : XBaseEntityHub - { - // - #region Properties ... - public IHubContext Hub { get; } - public IXIdentityProvider IdentityProvider { get; } - public IXBaseRepository Repository { get; } - public XDataServiceConfiguration DataConfiguration { get; } - #endregion - - // - #region Constructor ... - protected XBaseEntityProvider( - IHubContext hub, - IXBaseRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) - { - // - Hub = hub; - Repository = repository; - IdentityProvider = identityProvider; - DataConfiguration = dataConfiguration; - } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddAsync( - TEntity item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Add.GetStringValue() - ); - } - - // - return result; - } - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task UpdateAsync( - TKey id, - TEntity item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.UpdateAsync( - id: id, - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Update.GetStringValue() - ); - } - - // - return result; - } - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - var isValid = !result.IsNullOrDefault(); - if (isValid) - { - // - await SendPush( - connectionId: connectionId, - cancellationToken: cancellationToken, - payLoad: result.ToJSON(camelCase: true), - action: XBaseEntityHubAction.Delete.GetStringValue() - ); - } - - // - return result; - } - - /// - /// count all exists Items ... - /// - /// - /// - /// - public virtual async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - public virtual async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - public virtual async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.GetAsync( - id: id, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - public virtual async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.FindOneAsync( - predicate: predicate, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.FindManyAsync( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Repository.QueryAsync( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - public async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var actions = new List - { - XBaseEntityHubAction.Add.GetStringValue(), - XBaseEntityHubAction.Update.GetStringValue(), - XBaseEntityHubAction.Delete.GetStringValue(), - XBaseEntityHubAction.AddMany.GetStringValue(), - XBaseEntityHubAction.DeleteMany.GetStringValue(), - XBaseEntityHubAction.UpdateMany.GetStringValue(), - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - }; - - // - // Validate ... - var isValid = - !Hub.IsNull() && - !action.IsNullOrEmpty() && - !payLoad.IsNullOrEmpty() && - actions.Contains(action); - if (!isValid) - { - return; - } - - // - // Retrieve Connection Id ... - var clients = Hub.Clients.All; - if (!connectionId.IsNullOrEmpty()) - { - clients = Hub.Clients.AllExcept(connectionId); - } - - // - await clients.SendAsync( - action, - payLoad, - connectionId, - cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseHub.cs - -using System; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using xPushService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.Logging; - -namespace xPushService.Base -{ - public abstract class XBaseHub : Hub, IXBaseHub - { - // - #region Props ... - protected readonly ILogger logger; - #endregion - - // - #region Constructor ... - public XBaseHub( - ILogger logger - ) - { - this.logger = logger; - } - #endregion - - // - #region Overrides ... - public override async Task OnConnectedAsync() - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - // Notify Other Clients Which a new Connection Joins ... - await Clients.AllExcept(connectionId).SendAsync(XBaseHubAction.NewConnection.GetStringValue(), connectionId); - } - - // - await base.OnConnectedAsync(); - } - - public override async Task OnDisconnectedAsync(Exception exception) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - // Notify Other Clients Which a Connection Closed ... - await Clients.AllExcept(connectionId).SendAsync(XBaseHubAction.ConnectionClosed.GetStringValue(), connectionId); - } - await base.OnDisconnectedAsync(exception); - } - #endregion - - // - #region Actions ... - public async Task SendCustomAction( - string actionName, - string payLoad, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - await Clients.AllExcept(connectionId).SendAsync( - actionName, - payLoad, - connectionId, - cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using System.Linq.Expressions; -using xDataService.Interfaces; -using xPushService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Base -{ - public abstract class XBaseProvider : IXBaseProvider - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Props ... - public IXIdentityProvider IdentityProvider { get; } - public XDataServiceConfiguration DataConfiguration { get; } - public IHubContext> Hub { get; } - public IXBaseRepositoryService RepositoryService { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - /// - public async Task AddAsync( - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.AddAsync( - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - await SendPush( - action: XBaseEntityHubAction.Add.GetStringValue(), - payLoad: result.ToJSON(camelCase: true), - connectionId: connectionId - ); - } - - // - return result; - } - - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - /// - public async Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.UpdateAsync( - id: id, - item: item, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - await SendPush( - action: XBaseEntityHubAction.Update.GetStringValue(), - payLoad: result.ToJSON(camelCase: true), - connectionId: connectionId - ); - } - - // - return result; - } - - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - /// - public async Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - cancellationToken: cancellationToken - ); - - // - if (!result.IsNullOrDefault()) - { - // - await SendPush( - action: XBaseEntityHubAction.Update.GetStringValue(), - payLoad: result.ToJSON(camelCase: true), - connectionId: connectionId - ); - } - - // - return result; - } - - /// - /// count all exists Dtos ... - /// - /// - /// - /// - public async Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - public async Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - public async Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.GetAsync( - id: id, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - public async Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.GetAllAsync( - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public async Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.FindOneAsync( - predicate: predicate, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - public async Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.FindManyAsync( - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await RepositoryService.QueryAsync( - query: query, - predicate: predicate, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - public async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var actions = new List - { - XBaseEntityHubAction.Add.GetStringValue(), - XBaseEntityHubAction.Update.GetStringValue(), - XBaseEntityHubAction.Delete.GetStringValue(), - XBaseEntityHubAction.AddMany.GetStringValue(), - XBaseEntityHubAction.DeleteMany.GetStringValue(), - XBaseEntityHubAction.UpdateMany.GetStringValue(), - XBaseEntityHubAction.AddOrUpdate.GetStringValue(), - }; - - // - // Validate ... - var isValid = - !Hub.IsNull() && - !action.IsNullOrEmpty() && - actions.Contains(action); - if (!isValid) - { - return; - } - - // - var clients = Hub.Clients.All; - if (!connectionId.IsNullOrEmpty()) - { - clients = Hub.Clients.AllExcept(connectionId); - } - - // - try - { - // - await clients.SendAsync( - action, - payLoad, - connectionId, - cancellationToken - ); - } - catch { } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Base\XBaseWebRTCHub.cs - -using System.Threading; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using xPushService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.SignalR; - -namespace xPushService.Base -{ - public abstract class XBaseWebRTCHub : XBaseHub, IXBaseWebRTCHub - { - // - #region Props ... - #endregion - - // - #region Constructor ... - protected XBaseWebRTCHub( - ILogger logger - ) : base(logger) - { } - #endregion - - // - #region WebRTCActions ... - /// - /// Sending WebRTC Offer To Specified Connection ... - /// - /// - /// - /// - /// - public async Task Offer( - string offer, - string to, - CancellationToken cancellationToken = default - ) - { - // - await Clients.Client(to).SendAsync( - XWebRTCAction.Offer.GetStringValue(), - offer, - cancellationToken - ); - } - - /// - /// Sending WebRTC Answer to Specified Connection ... - /// - /// - /// - /// - public async Task Answer( - string answer, - CancellationToken cancellationToken = default - ) - { - // - await Clients.All.SendAsync( - XWebRTCAction.Answer.GetStringValue(), - answer, - Context.ConnectionId, - cancellationToken - ); - } - - /// - /// Sending WebRTC Candidate to Specified Connecton ... - /// - /// - /// - /// - /// - public async Task Candidate( - string candidate, - string to, - CancellationToken cancellationToken = default - ) - { - // - string actionName = XWebRTCAction.Candidate.GetStringValue(); - if (!string.IsNullOrEmpty(to)) - { - // - await Clients.Client(to).SendAsync( - actionName, - candidate, - Context.ConnectionId, - cancellationToken - ); - } - else - { - // - await Clients.All.SendAsync( - actionName, - candidate, - Context.ConnectionId, - cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Configurations\XPushServiceConfiguration.cs - -namespace xPushService.Configurations { - public partial class XPushServiceConfiguration { - /// - /// Base route of WebSocket Server ... - /// - /// string - public string BaseRoute { get; set; } - - /// - /// determines log level of signalR ... - /// - /// - public object ConnectionLogLevel { get; set; } - - /// - /// when client disconnected it's automatically try to reconnect, this - /// determines max number of try to connect ... - /// - /// - public int PushConnectionMaxRetry { get; set; } - - /// - /// add support for message protocol ... - /// - /// - public bool AddSupportMessageProtocol { get; set; } - - /// - /// the delay between two connection try .. - /// - /// - public int PushConnectionReconnectDelay { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Constants\XPushAction.cs - -using xExceptions.Attributes; - -namespace xPushService.Constants -{ - public enum XBaseHubAction - { - /// - /// new Connection Join ... - /// - [StringValue("NewConnection")] - NewConnection, - /// - /// an Exists Connection Closed ... - /// - [StringValue("ConnectionClosed")] - ConnectionClosed, - } - - /// - /// All Actions in WebRTC Hubs ... - /// - public enum XWebRTCAction - { - // - [StringValue("Offer")] - Offer, - - [StringValue("Answer")] - Answer, - - [StringValue("Candidate")] - Candidate, - } - - /// - /// Provides All Actions Based on Entities ... - /// - public enum XBaseEntityHubAction - { - [StringValue("Add")] - Add, - [StringValue("AddOrUpdate")] - AddOrUpdate, - [StringValue("AddMany")] - AddMany, - [StringValue("Update")] - Update, - [StringValue("UpdateMany")] - UpdateMany, - [StringValue("Delete")] - Delete, - [StringValue("DeleteMany")] - DeleteMany, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Constants\XPushServiceConstants.cs - -namespace xPushService.Constants { - public partial class XPushServiceConstants { - public partial struct XConfigurationNodes { - public const string XPushServiceConfiguration = "PushServiceConfiguration"; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Controllers\XBaseProvidedController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Controllers -{ - [AllowAnonymous] - public abstract class XBaseProvidedController : XBaseIdentityApiV1Controller, IXBaseProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly IXBaseProvided provider; - private readonly Func, IOrderedQueryable> defaultOrderBuilder; - private readonly Func, IIncludableQueryable> defaultIncludeBuilder; - - protected XBaseProvidedController( - ILogger> logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXBaseProvided provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.provider = provider; - this.defaultOrderBuilder = defaultOrderBuilder; - this.defaultIncludeBuilder = defaultIncludeBuilder; - } - - // - #region Retrieve ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(id); - - // - var result = await provider.Get( - id: id, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - [HttpGet("")] - public virtual async Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetAll( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - [HttpGet("Find/One")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindOne( - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find a collection of Items by proving a Query Search ... - /// - /// - /// - /// - /// - /// - [HttpGet("Find/Many")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindMany( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var result = await provider.Query( - query: query, - predicate: null, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Owned Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query/Owned")] - public virtual async Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryOwned( - query: query, - predicate: null, - userInfo: userInfo, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Add/Update/Remove ... - /// - /// Add an item ... - /// - /// - /// - /// - [HttpPost("")] - public virtual async Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove an Item ... - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Controllers\XBaseRepositoryProviderController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xCommons.Configurations; -using xDataService.Extensions; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Controllers -{ - [AllowAnonymous] - public abstract class XBaseRepositoryProviderController : XBaseIdentityApiV1Controller, IXBaseRepositoryProviderController - where TEntity : XBaseEntity - where THub : XBaseEntityHub - { - // - #region Properties ... - public IXBaseEntityProvider Provider { get; } - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - protected XBaseRepositoryProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXBaseEntityProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger: logger, - appConfiguration: appConfiguration, - identityProvider: identityProvider, - validationProvider: validationProvider - ) - { - // - Provider = provider; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TEntity item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.AddAsync( - item: item, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.UpdateAsync( - id: id, - item: item, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - [HttpGet("{id}/[action]")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// count all exists Items ... - /// - /// - /// - /// - [HttpGet("Count")] - public virtual async Task> Count( - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.GetAsync( - id: id, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.GetAllAsync( - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(query); - - // - Expression> predicate = x => x.PropValuesContains(query); - var result = await Provider.FindOneAsync( - predicate: predicate, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// find a collection of Items by proving a Query Search ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(query); - - // - Expression> predicate = x => x.PropValuesContains(query); - var result = await Provider.FindManyAsync( - predicate: predicate, - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (query.IsNullOrDefault()) - { - query = query.NormalizeQuery(Provider.DataConfiguration); - } - - // - var result = await Provider.QueryAsync( - query: query, - predicate: null, - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region NonActions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - [NonAction] - public virtual async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - await Provider.SendPush( - action: action, - payLoad: payLoad, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Controllers\XBaseServiceProviderController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xCommons.Configurations; -using xDataService.Extensions; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Controllers -{ - [AllowAnonymous] - public abstract class XBaseServiceProviderController : XBaseIdentityApiV1Controller, IXBaseServiceProviderController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Properties ... - public IXBaseDtoProvider Provider { get; } - public Func, IOrderedQueryable> DefaultOrderBuilder { get; } - public Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Constructor ... - public XBaseServiceProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXBaseDtoProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - // - Provider = provider; - DefaultOrderBuilder = defaultOrderBuilder; - DefaultIncludeBuilder = defaultIncludeBuilder; - } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - [HttpPost] - public virtual async Task> Add( - [FromBody] TDto item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.AddAsync( - item: item, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(item); - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.UpdateAsync( - id: id, - item: item, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var connectionId = GetConnectionId(); - - // - var result = await Provider.RemoveAsync( - id: id, - softDelete: softDelete, - saveChanges: saveChanges, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - [HttpGet("{id}/[action]")] - public virtual async Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.IsExistsAsync( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// count all exists Items ... - /// - /// - /// - /// - [HttpGet("Count")] - public virtual async Task> Count( - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.CountAsync( - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.GetAsync( - id: id, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - [HttpGet] - public virtual async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Provider.GetAllAsync( - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(query); - - // - Expression> predicate = x => x.PropValuesContains(query); - var result = await Provider.FindOneAsync( - predicate: predicate, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotEmpty(query); - - // - Expression> predicate = x => x.PropValuesContains(query); - var result = await Provider.FindManyAsync( - predicate: predicate, - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (query.IsNullOrDefault()) - { - query = query.NormalizeQuery(Provider.DataConfiguration); - } - - // - var result = await Provider.QueryAsync( - query: query, - predicate: null, - orderBuilder: !useDefaultOrders - ? null - : DefaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : DefaultIncludeBuilder, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region NonActions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - [NonAction] - public virtual async Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - await Provider.SendPush( - action: action, - payLoad: payLoad, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using Newtonsoft.Json; -using System.Reflection; -using xCommons.Extensions; -using xPushService.Helpers; -using xExceptions.Constants; -using xPushService.Constants; -using xPushService.Providers; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xPushService.Configurations; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.SignalR; -using Newtonsoft.Json.Serialization; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xPushService.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Extract Module Configuration from provided IConfiguration - /// - /// - /// an instance of XPushServiceConfiguration - public static XPushServiceConfiguration GetXPushServiceConfiguration(this IConfiguration config) - { - // - var xPushConfigSection = config.GetSection(XPushServiceConstants.XConfigurationNodes.XPushServiceConfiguration); - return xPushConfigSection.Get(); - } - - /// - /// Register XPushServiceHelper ... - /// - /// - /// - public static void AddXPushServiceHelper( - this IServiceCollection services, - XPushServiceHelper helper - ) - { - // - // Validate Args ... - if (helper.IsNull()) - { - // - Log("AddXPushServiceHelper failed, helper not provided ..."); - throw XException.InvalidArgs.ToException(); - } - - // - // Register Helper ... - services.AddSingleton(helper); - } - - /// - /// Register Module Provided Service on DI - /// - /// - /// - /// - public static void AddXPushService( - this IServiceCollection services, - IConfiguration config, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - AddPushService( - services, - config.GetXPushServiceConfiguration(), - lifeTime - ); - } - - /// - /// Register Module Provided Service on DI - /// - /// - /// - /// - public static void AddXPushService( - this IServiceCollection services, - XPushServiceConfiguration config, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - AddPushService( - services, - config, - lifeTime - ); - } - - /// - /// Use Module Middlewares on Application Builder - /// - /// - /// - public static void UseXPushService( - this IApplicationBuilder app, - XPushServiceHelper helper - ) - { - // - // Validate Args ... - var isHelperExists = !helper.IsNull(); - if (!isHelperExists) - { - // - Log("AddXPushServiceHelper failed, helper not provided ..."); - throw XException.InvalidArgs.ToException(); - } - - // - // Create an Scope for Accessing Registered Services ... - using (var scope = app.ApplicationServices.CreateScope()) - { - // - // try to Retrieve Configuration .... - var config = scope.ServiceProvider.GetService(); - if ( - config.IsNull() || - config.BaseRoute.IsNullOrEmpty() || - config.BaseRoute.Trim().IsNullOrEmpty() - ) - { - // - Log("AddXPushServiceHelper failed, Configuration not provided ..."); - throw XException.InvalidConfiguration.ToException(); - } - - // - #region Normalize Routes ... - // - // Base Reoute ... - config.BaseRoute = config.BaseRoute.ToNormalString(); - if (!config.BaseRoute.StartsWith("/")) - { - config.BaseRoute = "/" + config.BaseRoute; - } - #endregion - - // - // add XPushService Hub to Helper ... - // - var hubRoutes = new List(); - - // - // Try to Register Hubs ... - // - // Use SignalR in App ... - app.UseSignalR(routes => - { - // - helper.GetHubs().ForEach(hubDescriptor => - { - // - var hubRoute = config.BaseRoute + "/" + hubDescriptor.Route; - hubRoutes.Add(hubRoute); - - // - try - { - // - Type routesType = routes.GetType(); - MethodInfo mapHubMethod = routesType - .GetMethods() - .SingleOrDefault(m => - m.Name == "MapHub" && - m.GetParameters().Length == 1 - ); - if (mapHubMethod.IsNull()) - { - throw XException.ActionFailed.ToException(); - } - - // - object[] genericMapHubMethodArgs = { new PathString(hubRoute) }; - MethodInfo genericMapHubMethod = mapHubMethod.MakeGenericMethod(hubDescriptor.Hub); - genericMapHubMethod.Invoke(routes, genericMapHubMethodArgs); - - // - Log($"Register {hubDescriptor.Hub} Hub: {hubRoute}"); - } - catch - { - throw; - } - }); - }); - } - } - - // - #region Private ... - /// - /// a LogTag for XPushService ... - /// - private static string XLogTag = "XPushService"; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Push Service ... - /// - /// - /// - /// - private static void AddPushService( - IServiceCollection services, - XPushServiceConfiguration config, - ServiceLifetime lifeTime - ) - { - // - #region Validate Args ... - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("AddXPushServiceHelper failed, services not provided ..."); - throw exception; - } - - // - // Config ... - var isConfigExists = !config.IsNull(); - if (!isConfigExists) - { - // - Log("AddXPushServiceHelper failed, configuration not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("AddXPushServiceHelper failed, lifetime not provided ..."); - throw exception; - } - #endregion - - // - // Register XPushService Configuration ... - services.AddSingleton(config); - - // - // Register SignalR ... - var builder = services.AddSignalR(options => - { - options.KeepAliveInterval = TimeSpan.FromSeconds(10); - options.ClientTimeoutInterval = TimeSpan.FromSeconds(10); - }); - - // - // Add NewtonSoftJson Protocol ... - builder.AddNewtonsoftJsonProtocol(x => - { - x.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - x.PayloadSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - }); - - // - // Register XPushServiceUserNameProvider ... - services.AddSingleton(); - - // - // add Message Protocol Support ... - if (config.AddSupportMessageProtocol) - { - builder.AddMessagePackProtocol(); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Extensions\ClaimsPrincipalExtensions.cs - -using System; -using System.Linq; -using xCommons.Helpers; -using xCommons.Constants; -using xCommons.Extensions; -using xPushService.Models; -using xIdentityModels.Constants; -using System.Collections.Generic; -using Microsoft.AspNetCore.SignalR; - -namespace xPushService.Extensions -{ - public static class ClaimsPrincipalExtensions - { - /// - /// Generate User Info based on HubCallerContext ... - /// - /// - /// - public static XHubUserInfo GetUserInfo(this HubCallerContext source) - { - // - XHubUserInfo result = null; - - // - if (source.IsNull() || source.User.IsNull() || !source.User.Claims.HasChild()) - { - return result; - } - - // - result = new XHubUserInfo - { - UserId = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? "", - UserName = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? "", - FirstName = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? "", - LastName = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? "", - Picture = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? "", - Email = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.Email)?.Value ?? null, - PhoneNumber = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.PhoneNumber)?.Value ?? null, - }; - - // - #region Handle Gender ... - var genders = ObjectHelper.ToEnumerableKeys(); - var genderStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.Gender).Value ?? null; - if (genderStr.IsNullOrEmpty()) - { - result.Gender = XGender.Male; - } - else - { - result.Gender = genderStr.GetValue(); - } - #endregion - - // - #region Handle IsBanned ... - var isBannedStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.IsBanned).Value ?? null; - if (isBannedStr.IsNullOrEmpty()) - { - result.IsBanned = false; - } - else - { - // - var isBanned = false; - Boolean.TryParse(isBannedStr, out isBanned); - - // - result.IsBanned = isBanned; - } - #endregion - - // - #region Handle IsEnabled ... - var isEnabledStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.IsEnabled).Value ?? null; - if (isEnabledStr.IsNullOrEmpty()) - { - result.IsEnabled = false; - } - else - { - // - var isEnabled = false; - Boolean.TryParse(isEnabledStr, out isEnabled); - - // - result.IsEnabled = isEnabled; - } - #endregion - - // - #region Handle Email Confirmed ... - var emailConfirmedStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.EmailVerified).Value ?? null; - if (emailConfirmedStr.IsNullOrEmpty()) - { - result.EmailConfirmed = false; - } - else - { - // - var emailConfirmed = false; - Boolean.TryParse(emailConfirmedStr, out emailConfirmed); - - // - result.EmailConfirmed = emailConfirmed; - } - #endregion - - // - #region Handle PhoneNumber Confirmed ... - var phoneNumberConfirmedStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.PhoneNumberVerified).Value ?? null; - if (phoneNumberConfirmedStr.IsNullOrEmpty()) - { - result.PhoneNumberConfirmed = false; - } - else - { - // - var phoneNumberConfirmed = false; - Boolean.TryParse(phoneNumberConfirmedStr, out phoneNumberConfirmed); - - // - result.PhoneNumberConfirmed = phoneNumberConfirmed; - } - #endregion - - // - #region Handle ExpiredOn ... - var expiredOnStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.ExpiredOn).Value ?? null; - if (expiredOnStr.IsNullOrEmpty()) - { - result.ExpiredOn = null; - } - else - { - // - long expiredOn = 0; - long.TryParse(expiredOnStr, out expiredOn); - - // - result.ExpiredOn = expiredOn; - } - #endregion - - // - #region Handle AuthenticatedOn ... - var authenticatedOnStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.AuthenticatedOn).Value ?? null; - if (authenticatedOnStr.IsNullOrEmpty()) - { - result.AuthenticatedOn = null; - } - else - { - // - long authenticatedOn = 0; - long.TryParse(authenticatedOnStr, out authenticatedOn); - - // - result.AuthenticatedOn = authenticatedOn; - } - #endregion - - // - #region Handle BrithDate ... - var brithDateStr = source.User.Claims.FirstOrDefault(c => c.Type == XCustomClaims.BrithDate)?.Value ?? ""; - if (brithDateStr.IsNullOrEmpty()) - { - // BrithDate = null; - } - else - { - // - DateTime bDate; - DateTime.TryParse(brithDateStr, out bDate); - - // - result.BrithDate = bDate; - } - #endregion - - // - result.Issuers = source.User.Claims.Where(c => c.Type == XCustomClaims.Issuer)? - .Select(c => c.Value) ?? new HashSet(); - result.Audiences = source.User.Claims.Where(c => c.Type == XCustomClaims.Audience)? - .Select(c => c.Value) ?? new HashSet(); - result.ClientIds = source.User.Claims.Where(c => c.Type == XCustomClaims.ClientId)? - .Select(c => c.Value) ?? new HashSet(); - result.Scopes = source.User.Claims.Where(c => c.Type == XCustomClaims.Scope)? - .Select(c => c.Value) ?? new HashSet(); - result.Roles = source.User.Claims.Where(c => c.Type == XCustomClaims.Role)? - .Select(c => c.Value) ?? new HashSet(); - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Helpers\XPushServiceHelper.cs - -using System.Linq; -using xPushService.Base; -using xCommons.Extensions; -using xPushService.Models; -using xExceptions.Constants; -using System.Collections.Generic; - -namespace xPushService.Helpers { - public class XPushServiceHelper { - /// - /// a collection of Hubs for Registring ... - /// - /// - private List hubs = new List (); - - /// - /// add specified hub to provided hubs for registration ... - /// - /// - /// - public void AddHub (string route) where TXHub : XBaseHub { - // - #region Validate Args ... - // - // check route not null ... - if ( - route.IsNullOrEmpty () || - route.Trim ().IsNullOrEmpty () - ) { - throw XException.InvalidArgs.ToException (); - } - - // - // Normalize Route ... - route = route.ToNormalString (); - - // - // check route and hub must be unique ... - var isRouteExists = hubs.Any (hd => hd.Route == route); - var isHubExists = hubs.Any (hd => hd.Hub == typeof (TXHub)); - if ( - isHubExists || - isRouteExists - ) { - throw XException.Duplicate.ToException (); - } - #endregion - - // - // Add Provided Hub to List ... - hubs.Add (new XHubDescriptor { - Route = route, - Hub = typeof (TXHub) - }); - } - - /// - /// remove an specific hub from provided list ... - /// - /// - public void RemoveHub () where TXHub : XBaseHub { - // - var existsHubDescriptor = hubs.SingleOrDefault (hd => hd.Hub == typeof (TXHub)); - if (!existsHubDescriptor.IsNull ()) { - hubs.Remove (existsHubDescriptor); - } - } - - /// - /// retrieve provided hubs count ... - /// - /// - public int Count () { - return hubs.Count; - } - - /// - /// retrieve all provided hubs for registration ... - /// - /// - public List GetHubs () { - return hubs; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseDtoHub.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xPushService.Interfaces -{ - public interface IXBaseDtoHub - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - /// - /// Notify a New Item added ... - /// - /// - /// - /// - Task Add( - TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Notify a New Item added ... - /// - /// - /// - /// - Task AddOrUpdate( - TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Add Many Items ... - /// - /// - /// - /// - Task AddMany( - IEnumerable items, - CancellationToken cancellationToken = default - ); - - /// - /// Notify an Item Deleted ... - /// - /// - /// - /// - Task Delete( - TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Delete Many Items ... - /// - /// - /// - /// - Task DeleteMany( - IEnumerable items, - CancellationToken cancellationToken = default - ); - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - Task Update( - TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Update Many Items ... - /// - /// - /// - /// - Task UpdateMany( - IEnumerable items, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseDtoProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - public interface IXBaseDtoProvider - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Props ... - IHubContext Hub { get; } - IXIdentityProvider IdentityProvider { get; } - XDataServiceConfiguration DataConfiguration { get; } - IXBaseRepositoryService Service { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - /// - Task AddAsync( - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Items ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos - /// as Async Enumerable ... - /// - /// - /// - /// - /// - /// - IAsyncEnumerable GetAllAsAsyncEnumerable( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseEntityHub.cs - -using xModels.Base; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace xPushService.Interfaces -{ - public interface IXBaseEntityHub - where TEntity : XBaseEntity - { - /// - /// Notify a New Entity added ... - /// - /// - /// - /// - Task Add( - TEntity entity, - CancellationToken cancellationToken = default - ); - - /// - /// Notify a New Entity added ... - /// - /// - /// - /// - Task AddOrUpdate( - TEntity entity, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Add Many Entities ... - /// - /// - /// - /// - Task AddMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ); - - /// - /// Notify an Entity Deleted ... - /// - /// - /// - /// - Task Delete( - TEntity entity, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Delete Many Entities ... - /// - /// - /// - /// - Task DeleteMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ); - - /// - /// Notify an Entity Updated ... - /// - /// - /// - /// - Task Update( - TEntity entity, - CancellationToken cancellationToken = default - ); - - /// - /// Notify Update Many Entities ... - /// - /// - /// - /// - Task UpdateMany( - IEnumerable entities, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseEntityProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - /// - /// a Provider is a way to Manipulate Data using Repository or Services and Contains Push - /// notifications ability ... - /// - /// - /// - public interface IXBaseEntityProvider - where TEntity : XBaseEntity - where THub : XBaseEntityHub - { - // - #region Props ... - IHubContext Hub { get; } - IXIdentityProvider IdentityProvider { get; } - IXBaseRepository Repository { get; } - XDataServiceConfiguration DataConfiguration { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - /// - Task AddAsync( - TEntity item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - TEntity item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Items ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseHub.cs - -using System.Threading; -using System.Threading.Tasks; - -namespace xPushService.Interfaces -{ - public interface IXBaseHub - { - Task SendCustomAction( - string actionName, - string payLoad, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseProvided.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - /// - /// a Provided Service Used for Providing Data Based on Validations of Users ... - /// - /// - /// - /// - /// - public interface IXBaseProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - Task Get( - TKey id, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - Task> GetAll( - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - Task FindOne( - Expression> predicate, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task> FindMany( - Expression> predicate, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - Task> Query( - XQuery query, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Owned Items based on XQuery Pagination structure ... - /// if supported ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryOwned( - XQuery query, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - Task Add( - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - /// - /// - Task Update( - TKey id, - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Item ... - /// - /// - /// - /// - /// - /// - Task Remove( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Items ... - /// - /// - /// - Task Count( - CancellationToken cancellationToken = default - ); - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - Task IsExists( - TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseProvidedController.cs - -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; - -namespace xPushService.Interfaces -{ - /// - /// a Provided Controller Used for Providing a Provided Service Actions ... - /// - /// - /// - /// - /// - public interface IXBaseProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Retrieve ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - [HttpGet("{id}")] - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - [HttpGet("")] - Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// Find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - [HttpGet("Find/One")] - Task> FindOne( - [FromQuery] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// Find a collection of Items by proving a Query Search ... - /// - /// - /// - /// - /// - /// - [HttpGet("Find/Many")] - Task>> FindMany( - [FromQuery] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Owned Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query/Owned")] - Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Add/Update/Remove ... - /// - /// Add an item ... - /// - /// - /// - /// - [HttpPost("")] - Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ); - - /// - /// Remove an Item ... - /// - /// - /// - /// - [HttpDelete("{id}")] - Task> Remove( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseProvider.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using System.Linq.Expressions; -using xDataService.Interfaces; -using System.Collections.Generic; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - /// - /// a Provider is a way to Manipulate Data using Repository or Services and Contains Push - /// notifications ability ... - /// - /// - /// - /// - public interface IXBaseProvider - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - { - // - #region Props ... - // - IXIdentityProvider IdentityProvider { get; } - XDataServiceConfiguration DataConfiguration { get; } - IHubContext> Hub { get; } - IXBaseRepositoryService RepositoryService { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Dto ... - /// - /// - /// - /// - /// - /// - Task AddAsync( - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Dto values ... - /// - /// - /// - /// - /// - /// - /// - Task UpdateAsync( - TKey id, - TDto item, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - /// - Task RemoveAsync( - TKey id, - bool softDelete = true, - bool saveChanges = true, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Dtos ... - /// - /// - /// - /// - Task CountAsync( - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// Check a Dto exists or not ... - /// - /// - /// - /// - /// - Task IsExistsAsync( - TKey id, - bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve an Dto by it's Id ... - /// - /// - /// - /// - /// - /// - Task GetAsync( - TKey id, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Dtos ... - /// - /// - /// - /// - /// - /// - Task> GetAllAsync( - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find an Dto by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - Task FindOneAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Dtos by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - Task> FindManyAsync( - Expression> predicate, - bool ignoreSoftDeleteds = true, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Dtos based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - /// - Task> QueryAsync( - XQuery query, - bool ignoreSoftDeleteds = true, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Hub Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseRepositoryProviderController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - public interface IXBaseRepositoryProviderController - where TEntity : XBaseEntity - where THub : XBaseEntityHub - { - // - #region Properties ... - IXBaseEntityProvider Provider { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - [HttpPost] - Task> Add( - [FromBody] TEntity item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - Task> Update( - [FromRoute] TKey id, - [FromBody] TEntity item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - [HttpGet("{id}/[action]")] - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Items ... - /// - /// - /// - /// - [HttpGet("Count")] - Task> Count( - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - [HttpGet] - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne")] - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany")] - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Non Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - [NonAction] - Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseServiceProviderController.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Interfaces -{ - public interface IXBaseServiceProviderController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Properties ... - IXBaseDtoProvider Provider { get; } - Func, IOrderedQueryable> DefaultOrderBuilder { get; } - Func, IIncludableQueryable> DefaultIncludeBuilder { get; } - #endregion - - // - #region Actions ... - /// - /// add a new Item ... - /// - /// - /// - /// - /// - [HttpPost] - Task> Add( - [FromBody] TDto item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Update an Item values ... - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// remove an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - Task> Remove( - [FromRoute] TKey id, - [FromQuery] bool softDelete = true, - [FromQuery] bool saveChanges = true, - CancellationToken cancellationToken = default - ); - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - /// - [HttpGet("{id}/[action]")] - Task> IsExists( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// count all exists Items ... - /// - /// - /// - /// - [HttpGet("Count")] - Task> Count( - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve an Item by it's Id ... - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - Task> Get( - [FromRoute] TKey id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve all exists Items ... - /// - /// - /// - /// - /// - /// - [HttpGet] - Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// find an Item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne")] - Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany")] - Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Non Actions ... - /// - /// Send Custom Push Message ... - /// - /// - /// - /// - /// - /// - [NonAction] - Task SendPush( - string action, - string payLoad, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXBaseWebRTCHub.cs - -using System.Threading; -using System.Threading.Tasks; - -namespace xPushService.Interfaces -{ - public interface IXBaseWebRTCHub : IXBaseHub - { - /// - /// Sending WebRTC Offer To Specified Connection ... - /// - /// - /// - /// - /// - Task Offer( - string offer, - string to, - CancellationToken cancellationToken = default - ); - - /// - /// Sending WebRTC Answer to Specified Connection ... - /// - /// - /// - /// - Task Answer( - string answer, - CancellationToken cancellationToken = default - ); - - /// - /// Sending WebRTC Candidate to Specified Connecton ... - /// - /// - /// - /// - /// - Task Candidate( - string candidate, - string to, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Interfaces\IXHubContextFactory.cs - -using Microsoft.AspNetCore.SignalR; - -namespace xPushService.Interfaces -{ - public interface IXHubContextFactory - { - IHubContext Create() where THub : Hub; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Models\XHubConnectionDto.cs - -using xModels.Base; - -namespace xPushService.Models -{ - public class XHubConnectionDto : XBaseDto - { - public string ConnectionId { get; set; } - public string UserId { get; set; } - public string Username { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Models\XHubDescriptor.cs - -using System; - -namespace xPushService.Models { - /// - /// Describe a Hub to Register ... - /// - public class XHubDescriptor { - /// - /// Specified the Hub Route ... - /// - /// - public string Route { get; set; } - - /// - /// Specified the Hub Class Type ... - /// - /// - public Type Hub { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Models\XHubUserInfo.cs - -using System; -using xModels.Base; -using xIdentityModels.Constants; -using System.Collections.Generic; - -namespace xPushService.Models -{ - public class XHubUserInfo : XBaseDto - { - // - #region Properties ... - public string UserId { get; set; } - public string UserName { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Picture { get; set; } - public string Email { get; set; } - public string PhoneNumber { get; set; } - public XGender Gender { get; set; } - public bool IsBanned { get; set; } - public bool IsEnabled { get; set; } - public bool EmailConfirmed { get; set; } - public bool PhoneNumberConfirmed { get; set; } - public long? ExpiredOn { get; set; } - public long? AuthenticatedOn { get; set; } - public DateTime? BrithDate { get; set; } - public IEnumerable Issuers { get; set; } = new HashSet(); - public IEnumerable Audiences { get; set; } = new HashSet(); - public IEnumerable ClientIds { get; set; } = new HashSet(); - public IEnumerable Scopes { get; set; } = new HashSet(); - public IEnumerable Roles { get; set; } = new HashSet(); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Providers\XBaseProvided.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Linq.Expressions; -using xPushService.Interfaces; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore.Query; - -namespace xPushService.Providers -{ - /// - /// a Provided Service Used for Providing Data Based on Validations of Users ... - /// - /// - /// - /// - /// - public abstract class XBaseProvided : IXBaseProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - // - #region Props ... - private readonly string[] permittedRoles; - private readonly IXBaseDtoProvider provider; - #endregion - - // - #region Constructor ... - protected XBaseProvided( - IXBaseDtoProvider provider, - string[] permittedRoles = null - ) - { - this.provider = provider; - this.permittedRoles = permittedRoles; - } - #endregion - - /// - /// Check an Items is Owned for User or not ... - /// - /// - /// - /// - public abstract bool IsOwned( - TDto item, - XUserClaimsInfoDto userInfo - ); - public abstract bool IsOwned( - TEntity item, - XUserClaimsInfoDto userInfo - ); - - /// - /// Check User Has Permission for Manipulate Data or not ... - /// - /// - /// - public bool HasPermision( - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !permittedRoles.HasChild() || - (!userInfo.IsNullOrDefault() && - userInfo.HasAccess(permittedRoles)); - - // - return result; - } - - // - #region Provided Actions ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - public virtual async Task Get( - TKey id, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - public virtual async Task> GetAll( - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAllAsync( - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - public virtual async Task FindOne( - Expression> predicate, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindOneAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task> FindMany( - Expression> predicate, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindManyAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> Query( - XQuery query, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.QueryAsync( - query: query, - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Owned Items based on XQuery Pagination structure ... - /// if supported ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryOwned( - XQuery query, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicateor = null; - if (!predicate.IsNull()) - { - // - var predicateFnc = predicate.Compile(); - predicateor = x => - predicateFnc(x) && - IsOwned(x, userInfo); - } - else - { - predicateor = x => IsOwned(x, userInfo); - } - - // - var result = await provider.QueryAsync( - query: query, - predicate: predicateor, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - public virtual async Task Add( - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task Update( - TKey id, - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.UpdateAsync( - id: id, - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove an Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Remove( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var item = await Get( - id: id, - cancellationToken: cancellationToken - ); - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.RemoveAsync( - id: id, - saveChanges: true, - softDelete: false, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// count all exists Items ... - /// - /// - /// - public virtual async Task Count( - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.CountAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - public virtual async Task IsExists( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.IsExistsAsync( - id: id, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Providers\XHubContextFactory.cs - -using System; -using xPushService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.DependencyInjection; - -namespace xPushService.Providers -{ - public class XHubContextFactory : IXHubContextFactory - { - private readonly IServiceProvider services; - - public XHubContextFactory(IServiceProvider services) - { - this.services = services; - } - - public IHubContext Create() - where THub : Hub - { - return services.GetRequiredService>(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xPushService\Providers\XPushServiceUserNameProvider.cs - -using Microsoft.AspNetCore.SignalR; - -namespace xPushService.Providers { - public class XPushServiceUserNameProvider : IUserIdProvider { - public string GetUserId (HubConnectionContext connection) { - // - var result = connection.User?.Identity?.Name; - return result; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xServices-20261109_152618.txt b/Documents/GeneratedContext/xDashboard-xServices-20261109_152618.txt deleted file mode 100644 index 351e38c..0000000 --- a/Documents/GeneratedContext/xDashboard-xServices-20261109_152618.txt +++ /dev/null @@ -1,1516 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Base\IXBaseService.cs - -namespace xServices.Base -{ - public interface IXBaseService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Base\XBaseService.cs - -namespace xServices.Base -{ - public class XBaseService : IXBaseService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Base\XTestProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xServices.Providers; -using xServices.Interfaces; -using xServices.Models.Dtos; -using xCommons.Configurations; -using xPushService.Controllers; -using xServices.Models.Entities; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Base -{ - /// - /// an Abstract Implementation of Provided Actions for XTest ... - /// - public abstract class XTestProviderControllerBase : XBaseProvidedController, IXTestProviderController - { - protected XTestProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTestProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Configurations\XServicesConfiguration.cs - -namespace xServices.Configurations -{ - public partial class XServicesConfiguration - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Configurations\XTestTypeConfiguration.cs - -using System; -using xDataService.Providers; -using xServices.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xServices.Configurations -{ - public class XTestTypeConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Constants\ConfigurationNodeNames.cs - -namespace xServices.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string SERVICES_NODE = "ServicesConfiguration"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Constants\xServicesConstancts.cs - -using xExceptions.Attributes; - -namespace xServices.Constants -{ - public class xServicesConstancts - { - } - - public enum XQueryServiceEndPoints - { - /// - /// Specified Endpoint for Users Fetching as Query ... - /// - [StringValue("Account/Users/Query")] - QueryUsers, - - /// - /// Refresh Tokens ... - /// - [StringValue("Account/RefreshTokens")] - RefreshTokens, - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\CategoryProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xCategoryService.Interfaces; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Controllers; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - public class CategoryProviderController : XCategoryProviderControllerBase, IXCategoryProviderController - { - public CategoryProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXCategoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\ContentProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xContentService.Interfaces; -using xContentService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xContentService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; -using xContentService.Interfaces.Controllers; - -namespace xServices.Controllers -{ - public class ContentProviderController : XContentProviderControllerBase, IXContentProviderController - { - public ContentProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXContentProvider provider, - IXContentTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - tagProvided, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\FileProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xFileService.Interfaces; -using xFileService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xFileService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - public class FileProviderController : XFileProviderControllerBase, IXFileProviderController - { - public FileProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXFileProvider provider, - IXFileTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - tagProvided, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\StringProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Attributes; -using xCommons.Configurations; -using xStringService.Interfaces; -using xStringService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xStringService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - /// - /// an endpoint for Providing String Resource Management Actions ... - /// - [RequireXPowered(IgnoreAnonymous: false)] - public class StringProviderController : XStringProviderControllerBase, IXStringProviderController - { - public StringProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXStringProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\SubCategoryProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xCategoryService.Interfaces; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xCategoryService.Controllers; -using xCategoryService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - public class SubCategoryProviderController : XSubCategoryProviderControllerBase, IXSubCategoryProviderController - { - public SubCategoryProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXSubCategoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\TagProviderController.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xTagService.Interfaces; -using xCommons.Configurations; -using xTagService.Controllers; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - public class TagProviderController : XTagProviderControllerBase, IXTagProviderController - { - public TagProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\TermsAndConditionsProviderController.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xTermsAndConditionsService.Interfaces; -using xTermsAndConditionsService.Controllers; - -namespace xServices.Controllers -{ - public class TermsAndConditionsProviderController : XTermsAndConditionsControllerBase, IXTermsAndConditionsController - { - public TermsAndConditionsProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTermsAndConditionsProvider provider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Controllers\TestProviderController.cs - -using System; -using System.Linq; -using xServices.Base; -using xCommons.Providers; -using xServices.Interfaces; -using xCommons.Configurations; -using xServices.Models.Entities; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xServices.Controllers -{ - public class TestProviderController : XTestProviderControllerBase, IXTestProviderController - { - public TestProviderController( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTestProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Databases\XApiDatabaseDescriptor.cs - -using System; -using GraphQL.Types; -using xDataService.Models; -using xServices.Providers; -using xServices.Interfaces; -using xDataService.Interfaces; -using xServices.Models.GraphQL; -using xServices.Models.Entities; -using System.Collections.Generic; - -namespace xServices.Databases -{ - public class XApiDatabaseDescriptor : XDatabaseDescriptor, IXDatabaseDescriptor - { - public XApiDatabaseDescriptor() : base( - name: "xApiDb", - repositories: new List - { - // - // XTest Entity ... - new XEFRepositoryDescriptor< - XTest, - Guid, - IXTestKeyGenerator, - XTestKeyGenerator, - IXTestRepositoryEvents, - XTestRepositoryEvents, - XTestGraphType, - GuidGraphType, - XTestGraphQuery, - IXTestGraphQLTypeHelper, - XTestGraphQLTypeHelper, - XTestGraphSchema, - IXTestRepository, - XTestEFRepository, - XApiDbContext, - IXTestSeeder, - XTestSeeder - > - {} - } - ) - { - OptionsBuilder = b => b.MigrationsAssembly("xApi"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Databases\XApiDbContext.cs - -using xDataService.Db; -using xTagService.Providers; -using xDataService.Providers; -using xFileService.Providers; -using xStringService.Providers; -using xContentService.Providers; -using xServices.Models.Entities; -using xWebinarService.Providers; -using xCategoryService.Providers; -using xDataService.Configuration; -using Microsoft.EntityFrameworkCore; - -namespace xServices.Databases -{ - public class XApiDbContext : XDbContext - { - // - #region DbSets ... - public DbSet Tests { get; set; } - #endregion - - // - #region Navigation Property Entities ... - #endregion - - public XApiDbContext( - DbContextOptions options, - XDataServiceConfiguration config, - XEntityRegisterarHandlerService dynamicEntityHandlers - ) : base( - "xApiDb", - options, - config, - dynamicEntityHandlers, - new string[] { - nameof(XTagEntityRegisterar), - nameof(XFileEntityRegisterar), - nameof(XStringEntityRegisterar), - nameof(XContentEntityRegisterar), - nameof(XWebinarEntityRegisterar), - nameof(XCategoryEntityRegisterar), - nameof(XSubCategoryEntityRegisterar), - nameof(XWebinarSubscriberEntityRegisterar), - } - ) - { } - - // - public override void OnXModelCreating(ModelBuilder modelBuilder) - { } - - // - public override void OnXConfiguring(DbContextOptionsBuilder optionsBuilder) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\DI\XDIHelperExtension.cs - -using System.Linq; -using xTagService.DI; -using xDataService.DI; -using xFileService.DI; -using xPushService.DI; -using xStringService.DI; -using xContentService.DI; -using xMessageService.DI; -using xStorageService.DI; -using xWebinarService.DI; -using xCategoryService.DI; -using xCommons.Extensions; -using xDataService.Models; -using xIdentityService.DI; -using xServices.Constants; -using xServices.Databases; -using xServices.Providers; -using xPushService.Helpers; -using xServices.Interfaces; -using xServices.Configurations; -using System.Collections.Generic; -using Microsoft.AspNetCore.Builder; -using xTermsAndConditionsService.DI; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace xServices.DI -{ - public static partial class XDIHelperExtension - { - /// - /// Retrive Services Configurations ... - /// - /// - /// - public static XServicesConfiguration GetXServicesConfiguration( - this IConfiguration source - ) - { - // - var xConfig = source - .GetSection(ConfigurationNodeNames.SERVICES_NODE); - var result = xConfig.Get(); - - // - return result; - } - - /// - /// Register Service Configuration ... - /// - /// - /// - public static void AddXServicesConfiguration( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - var config = configuration - .GetXServicesConfiguration(); - if (config.IsNull()) - { - config = new XServicesConfiguration(); - } - - // - services.AddSingleton(config); - } - - /// - /// Register Service Configuration ... - /// - /// - /// - public static void AddXServicesConfiguration( - this IServiceCollection services, - XServicesConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - configuration = new XServicesConfiguration(); - } - - // - services.AddSingleton(configuration); - } - - /// - /// Register Services ... - /// - /// - /// - /// - /// - public static void AddXServices( - this IServiceCollection services, - IConfiguration configuration, - IEnumerable databases = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var config = configuration.GetXServicesConfiguration(); - - // - AddServices( - config: config, - services: services, - lifeTime: lifeTime, - databases: databases, - configuration: configuration - ); - } - - /// - /// Register Services ... - /// - /// - /// - /// - /// - /// - public static void AddXServices( - this IServiceCollection services, - IConfiguration configuration, - XServicesConfiguration config, - IEnumerable databases = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - AddServices( - config: config, - services: services, - lifeTime: lifeTime, - databases: databases, - configuration: configuration - ); - } - - /// - /// Use All Required Middlewares ... - /// - /// - /// - /// - public static void UseXServices( - this IApplicationBuilder app, - IEnumerable databases = null, - bool isDevelopmentEnvironment = false - ) - { - // - // Use Storage Service ... - app.UseXStorageService(); - - // - #region Use Data Data Service ... - if (databases.HasChild()) - { - // - databases - .ToList() - .ForEach(database => - { - // - app.UseXDatabase( - descriptor: database, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - }); - } - #endregion - - // - #region Use Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub("testDto"); - pushHelper.AddHub("testEntity"); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using String Service ... - app.UseXStringService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using Terms and Conditions Service ... - app.UseXTermsAndConditionsService(); - - // - // Using Tag Service ... - app.UseXTagService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using File Service ... - app.UseXFileService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using Category Service ... - app.UseXCategoryService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using Content Service ... - app.UseXContentService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - - // - // Using XWebinar Service ... - app.UsexWebinarService( - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - #region Private ... - /// - /// Register Required Services ... - /// - /// - /// - /// - /// - /// - private static void AddServices( - this IServiceCollection services, - IConfiguration configuration, - XServicesConfiguration config = null, - IEnumerable databases = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - // Check config ... - if (config.IsNull()) - { - config = new XServicesConfiguration(); - } - - // - // Storage Service ... - services.AddXStorageService(configuration); - - // - // Message Service ... - services.AddXMessageService(config: configuration); - - // - #region Register Identity Service ... - services.AddXIdentityService( - configuration: configuration, - lifeTime: ServiceLifetime.Scoped - ); - #endregion - - // - #region Register Data Service ... - // - if (databases.HasChild()) - { - // - databases - .ToList() - .ForEach(database => - { - // - // Register DataBase ... - services.AddXDatabase( - lifeTime: lifeTime, - descriptor: database, - configuration: configuration - ); - }); - } - - // - // Register Repository Services ... - services.AddScoped(); - services.AddScoped(); - #endregion - - // - #region Register Push Service ... - // - // Push Service ... - services.AddXPushService( - config: configuration, - lifeTime: ServiceLifetime.Scoped - ); - - // - // Register Provider Services ... - // since Hubs required Identity Provider, you Have to Register IdentityService as Requirements ... - // a Provider Service, Provides Repository (Entity) or Service (Dto) based - // Data Manipulation Actions by Supporting Hub Contexts Events ... - services.AddScoped(); - services.AddScoped(); - #endregion - - // - var repositoryType = xDataService.Constants.XRepositoryType.EF; - - // - // Register String Service ... - services.AddXStringService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Terms and Conditions Service ... - services.AddXTermsConditionsService( - lifeTime: lifeTime, - configuration: configuration - ); - - // - // Register Tag Service ... - services.AddXTagService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register File Service ... - services.AddXFileService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Category Service ... - services.AddXCategoryServiceConfiguration(configuration); - services.AddXCategoryService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Content Service ... - // services.AddXContentServiceConfiguration(configuration); - services.AddXContentService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - - // - // Register Webinar Service ... - services.AddXWebinarService( - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Extensions\xServicesExtensions.cs - -namespace xServices.Extensions -{ - public static class xServicesExtensions - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestDtoHub.cs - -using System; -using xServices.Models.Dtos; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestEntityHub.cs - -using System; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.Interfaces; -using xServices.Models.GraphQL; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestGraphQuery : IXBaseGraphQLQuery - {} -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestProvider.cs - -using System; -using xServices.Providers; -using xServices.Models.Dtos; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestProvider : IXBaseProvided - {} -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestProviderController.cs - -using System; -using xServices.Providers; -using xServices.Models.Dtos; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestProviderController : IXBaseProvidedController - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestRepository.cs - -using System; -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestRepositoryEvents.cs - -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestRepositoryProvider.cs - -using System; -using xServices.Providers; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestRepositoryService.cs - -using System; -using xServices.Models.Dtos; -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestSeeder.cs - -using System; -using xDataService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Interfaces\IXTestServiceProvider.cs - -using System; -using xServices.Providers; -using xServices.Models.Dtos; -using xPushService.Interfaces; -using xServices.Models.Entities; - -namespace xServices.Interfaces -{ - public interface IXTestServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Models\XGroupedData.cs - -using System; -using xModels.Base; -using System.Collections.Generic; - -namespace xServices.Models -{ - public class XGroupedDataEntity - where T : XBaseEntity - { - public TGroupedKey GroupedBy { set; get; } - public IEnumerable Members { set; get; } - public DateTime TimeStamp { set; get; } - } - - public class XGroupedDataDto - where T : XBaseDto - { - public TGroupedKey GroupedBy { set; get; } - public IEnumerable Members { set; get; } - public DateTime TimeStamp { set; get; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Models\Dtos\XTestDto.cs - -using System; -using xModels.Base; - -namespace xServices.Models.Dtos -{ - public class XTestDto : XBaseEntityDto - { - public string Firstname { get; set; } - public string Lastname { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Models\Entities\XTest.cs - -using System; -using xModels.Base; - -namespace xServices.Models.Entities -{ - public class XTest : XBaseEntity - { - public string Firstname { get; set; } - public string Lastname { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Models\GraphQL\XTestGraphType.cs - -using System; -using xDataService.GraphQL; -using xServices.Models.Entities; - -namespace xServices.Models.GraphQL -{ - public class XTestGraphType : XBaseGraphObjectType - { - public XTestGraphType() : base() - { - Field(x => x.Firstname); - Field(x => x.Lastname); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestDtoHub.cs - -using System; -using xPushService.Base; -using xServices.Interfaces; -using xServices.Models.Dtos; -using xServices.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xServices.Providers -{ - public class XTestDtoHub : XBaseDtoHub, IXTestDtoHub - { - public XTestDtoHub(ILogger logger) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestEFRepository.cs - -using System; -using xServices.Databases; -using xServices.Interfaces; -using xDataService.Providers; -using xDataService.Interfaces; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestEFRepository : XBaseEFRepository, IXTestRepository - { - public XTestEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXTestKeyGenerator keyGenerator = null, - IXTestRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestEntityHub.cs - -using System; -using xPushService.Base; -using xServices.Interfaces; -using xServices.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xServices.Providers -{ - public class XTestEntityHub : XBaseEntityHub, IXTestEntityHub - { - public XTestEntityHub(ILogger logger) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestGraphQLTypeHelper.cs - -using System; -using xDataService.GraphQL; -using xServices.Interfaces; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXTestGraphQLTypeHelper - { - public XTestGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { - } - - public override string GetInQueryCollectionName() - { - return "tests"; - } - - public override string GetInQuerySingleName() - { - return "test"; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xServices.Interfaces; -using xServices.Models.GraphQL; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestGraphQuery : XBaseGraphQLQuery - { - public XTestGraphQuery( - XDataServiceConfiguration configuration, - IXTestRepository repository, - IXTestGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xServices.Providers -{ - public class XTestGraphSchema : Schema - { - public XTestGraphSchema(IServiceProvider services) : base(services) - { - Query = (XTestGraphQuery)services.GetService(typeof(XTestGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestInMemoryRepository.cs - -using System; -using xServices.Interfaces; -using xDataService.Providers; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestInMemoryRepository : XBaseInMemoryRepository - { - public XTestInMemoryRepository( - XDataServiceConfiguration configuration, - IXTestKeyGenerator keyGenerator = null, - IXTestRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestKeyGenerator.cs - -using xServices.Interfaces; -using xDataService.Providers; -using xServices.Models.Entities; - -namespace xServices.Providers -{ - public class XTestKeyGenerator : XGuidKeyGenerator, IXTestKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestMongoRepository.cs - -using System; -using xServices.Interfaces; -using xDataService.Providers; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestMongoRepository : XBaseMongoRepository - { - public XTestMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXTestKeyGenerator keyGenerator = null, - IXTestRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestProvider.cs - -using System; -using xCommons.Extensions; -using xServices.Interfaces; -using xServices.Models.Dtos; -using xIdentityModels.Models; -using xPushService.Providers; -using xServices.Models.Entities; - -namespace xServices.Providers -{ - public class XTestProvider : XBaseProvided, IXTestProvider - { - public XTestProvider( - IXTestServiceProvider provider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { } - - public override bool IsOwned( - XTestDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XTest item, - XUserClaimsInfoDto userInfo - ) - { - return item.IsNullOrDefault(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestRepositoryEvents.cs - -using xServices.Interfaces; -using xDataService.Providers; -using xServices.Models.Entities; - -namespace xServices.Providers -{ - public class XTestRepositoryEvents : XBaseRepositoryEvents, IXTestRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestRepositoryProvider.cs - -using System; -using xPushService.Base; -using xServices.Interfaces; -using xServices.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xServices.Providers -{ - public class XTestRepositoryProvider : XBaseEntityProvider, IXTestRepositoryProvider - { - public XTestRepositoryProvider( - IXTestRepository repository, - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub: hub, - repository: repository, - identityProvider: identityProvider, - dataConfiguration: dataConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestRepositoryService.cs - -using System; -using AutoMapper; -using xServices.Interfaces; -using xServices.Models.Dtos; -using xDataService.Providers; -using xServices.Models.Entities; -using System.Collections.Generic; - -namespace xServices.Providers -{ - public class XTestRepositoryService : XBaseRepositoryService, IXTestRepositoryService - { - public XTestRepositoryService( - IXTestRepository repository, - IEnumerable mapperProfiles = null - ) : base(repository, mapperProfiles) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestSeeder.cs - -using System; -using xServices.Interfaces; -using xDataService.Providers; -using xServices.Models.Entities; -using xDataService.Configuration; - -namespace xServices.Providers -{ - public class XTestSeeder : XBaseDbSeeder, IXTestSeeder - { - public XTestSeeder( - IXTestRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - database: "xApiDb", - entity: nameof(XTest), - repository: repository, - dataServiceConfiguration: dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xServices\Providers\XTestServiceProvider.cs - -using System; -using xPushService.Base; -using xServices.Interfaces; -using xServices.Models.Dtos; -using xServices.Models.Entities; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; - -namespace xServices.Providers -{ - public class XTestServiceProvider : XBaseDtoProvider, IXTestServiceProvider - { - public XTestServiceProvider( - IHubContext hub, - IXTestRepositoryService service, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub: hub, - service: service, - identityProvider: identityProvider, - dataConfiguration: dataConfiguration - ) - { } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xStorageService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xStorageService-20261109_152621.txt deleted file mode 100644 index 2dbc2a2..0000000 --- a/Documents/GeneratedContext/xDashboard-xStorageService-20261109_152621.txt +++ /dev/null @@ -1,1653 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Constants\ConfigurationNodeNames.cs - -namespace xStorageService.Constants { - public partial struct ConfigurationNodeNames { - public const string STORAGE_SERVICE_NODE_NAME = "StorageConfiguration"; - } - -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\DI\XDIHelperExtension.cs - -using System.IO; -using xCommons.Extensions; -using xExceptions.Constants; -using xStorageService.Models; -using xStorageService.Helpers; -using xStorageService.Constants; -using xStorageService.Providers; -using xStorageService.Interfaces; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.DependencyInjection; - -namespace xStorageService.DI { - public static partial class XDIHelperExtension { - /// - /// Retrieve XStorage Configuration from AppSettings - /// - /// - /// - public static XStorageConfiguration GetXStorageConfiguration (this IConfiguration configuration) { - // - var storageConfigurationSection = configuration.GetSection (ConfigurationNodeNames.STORAGE_SERVICE_NODE_NAME); - return storageConfigurationSection.Get (); - } - - /// - /// Register XStorage Configuration - /// - /// - /// - public static void AddXStorageConfiguration ( - this IServiceCollection services, - IConfiguration configuration - ) { - // - // Check wwwroot Folder ... - if (!Directory.Exists ("wwwroot")) { - Directory.CreateDirectory ("wwwroot"); - } - - // - // Retrieve and Register XStorage Configurations ... - var xStorageConfiguration = configuration.GetXStorageConfiguration (); - if (xStorageConfiguration.IsNull ()) { - XException.InvalidConfiguration.Throw (); - } - - // - xStorageConfiguration.BaseFolder = Path.Combine (Directory.GetCurrentDirectory (), "wwwroot"); - xStorageConfiguration.RootFolder = Directory.GetDirectoryRoot (xStorageConfiguration.BaseFolder); - - // - services.AddSingleton (xStorageConfiguration); - } - - /// - /// Register XStorage Service - /// - /// - /// - public static void AddXStorageService ( - this IServiceCollection services, - IConfiguration configuration - ) { - // - // Register and Retrieve XStorage Configuration - services.AddXStorageConfiguration (configuration); - var xStorageConfiguration = services.GetRegisteredService (); - - // - // Add File Provider ... - services.AddSingleton ( - new PhysicalFileProvider (xStorageConfiguration.BaseFolder) - ); - - // - // Register XStorageHelper Service ... - services.AddSingleton (); - - // - // Register ThumbnailHelper ... - services.AddSingleton (); - - // - // Register Storage Provider ... - services.AddScoped (); - - // - // StorageService Preperation... - var xStorageService = services.GetRegisteredService (); - xStorageService.Prepare (); - } - - /// - /// Use XStorage Service - /// - /// - public static void UseXStorageService (this IApplicationBuilder app) { - // - // Get Instance of Scope and Service and Prepare Folder Structure ... - using (var scope = app.ApplicationServices.CreateScope ()) { - // - var storageProvider = scope.ServiceProvider.GetService (); - - // - storageProvider.Prepare (); - } - - // - // available Static Files ... - app.UseStaticFiles (); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Helpers\XStorageHelper.cs - -using System; -using System.IO; -using System.Linq; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Constants; - -namespace xStorageService.Helpers { - public partial class XStorageHelper { - - private int[] DocumentTypeThreshold = new int[] { 99, 307 }; - private int[] ImageTypeThreshold = new int[] { 599, 606 }; - private int[] AudioTypeThreshold = new int[] { 499, 504 }; - private int[] VideoTypeThreshold = new int[] { 399, 405 }; - - public XStorageHelper () { } - - /// - /// Retrieve FileType - /// - /// - /// - public XFileType GetType (int fileExtension) { - // - // Compare File Extension Integer Value and - // Find Propper Type for it ... - if (fileExtension > DocumentTypeThreshold[0] && fileExtension < DocumentTypeThreshold[1]) { - return XFileType.Document; - } else if (fileExtension > VideoTypeThreshold[0] && fileExtension < VideoTypeThreshold[1]) { - return XFileType.Video; - } else if (fileExtension > AudioTypeThreshold[0] && fileExtension < AudioTypeThreshold[1]) { - return XFileType.Audio; - } else if (fileExtension > ImageTypeThreshold[0] && fileExtension < ImageTypeThreshold[1]) { - return XFileType.Image; - } else { - // - // if not in case return Document Type - return XFileType.Document; - } - } - - /// - /// Retrieve a File Type - /// - /// - /// - public XFileType GetType (string fileName) { - // - if (fileName.IsNullOrEmpty ()) { - XException.InavlidFile.Throw (); - } - - // - var ext = GetFileExtension (fileName); - var extType = GetExtensionType (ext); - return GetType (extType); - } - - /// - /// used for validating Extension in Widget Upload ... - /// - /// an string array - public string[] GetAllowedExtensionsForWidgetUpload () { - return new [] { - XFileExtensions.SAHER_DASHBOARD_WIDGET.GetStringValue () - }; - } - - /// - /// Get a Files Extension string - /// - /// - /// - public string GetFileExtension (string fileName) { - // - // Validate Args ... - if (fileName.IsNullOrEmpty ()) { - return null; - } - - // - var fileExt = ""; - try { - fileExt = Path.GetExtension (fileName); - } catch { } - - // - return fileExt; - } - - /// - /// Get a File Name Without it's Extension - /// - /// - /// - public string GetFileNameWithoutExtension (string fileName) { - // - // Validate Args ... - if (fileName.IsNullOrEmpty ()) { - return null; - } - - // - var fileNameWithoutExt = ""; - try { - fileNameWithoutExt = Path - .GetFileNameWithoutExtension (fileName); - } catch { } - - // - return fileNameWithoutExt; - } - - /// - /// Get File Extension Type - /// - /// - /// - public int GetExtensionType (string fileExtension) { - // - foreach (var extItem in Enum - .GetValues (typeof (XFileExtensions)) - .Cast ()) { - if (extItem.GetStringValue () - .Contains (fileExtension.ToLower ())) { - return (int) extItem; - } - } - - // - return -1; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Interfaces\IXStorageProvider.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xCommons.Constants; -using System.Threading.Tasks; -using xStorageService.Models; -using xStorageService.Helpers; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Microsoft.Extensions.FileProviders; - -namespace xStorageService.Interfaces -{ - public partial interface IXStorageProvider - { - XStorageConfiguration Configuration { get; } - XStorageHelper StorageHelper { get; } - IFileProvider FileProvider { get; } - IXThumbnailProvider ThumbnailProvider { get; } - - // - #region Special Folders Path Getter (s) ... - string GetStorageFolderPath(); - string GetTempFolderPath(); - string GetThumbFolderPath(); - string GetUploadsFolderPath(); - string GetWidgetsFolderPath(); - string GetImageFolderPath(); - string GetAudioFolderPath(); - string GetVideoFolderPath(); - string GetDocumentFolderPath(); - string FilePathResolver(string fullPath); - string ConvertToFileUrl(string fullPath); - #endregion - - // - #region Prepare Storage Structure ... - void Prepare(); - #endregion - - // - #region Validators ... - bool IsFolderExists(string path); - bool IsFileExists(string filePath); - bool IsSupportThumb(string fileName); - bool IsSupportThumb(XFileType type); - void ValidateFileExists(string filePath); - void ValidateFileModel(XFileDto file); - void ValidateFile(IFormFile file); - void ValidateProfileImage(IFormFile file); - #endregion - - // - #region Generators ... - string NewFileName(); - string GenerateThumbName(string fileName); - string GetNewFileName(string fileName); - #endregion - - // - #region Tools Actions ... - - string GetFileExtension(string fileName); - string GetFileNameWithoutExtension(string fileName); - XFileExtensions GetFileExtensionType(string fileName); - XFileType GetFileType(string fileName); - XFileType GetFileType(XFileExtensions fileExtension); - string GetThumbnailFileFullPath(string thumFileName); - string GetRelatedThumbnailFullPath(string fileName); - string GetFileTypeFolderPath(XFileType type); - string GetFileFolderPath( - string fileName, - bool isTemp = false, - bool isWidget = false - ); - string GetFileFullPath( - string fileName, - bool isTemp = false, - bool isWidget = false - ); - Task SaveFileAsync( - IFormFile file, - bool isTemp = false, - bool isWidget = false, - CancellationToken cancellationToken = default - ); - void DeleteFile( - string fileFullPath, - bool forceFileExists = true, - Exception exception = null - ); - ICollection DeleteFiles( - ICollection fileFullPaths, - bool forceFileExists = true, - Exception exception = null - ); - // Task CreateThumbnail (XFile file); - Task CreateThumbnail( - XFileDto file, - CancellationToken cancellationToken = default - ); - Task CreateThumbnail( - string fileName, - CancellationToken cancellationToken = default - ); - Task HandleProfileImageSave( - IFormFile file, - CancellationToken cancellationToken = default - ); - Task HandleFileSave( - IFormFile file, - CancellationToken cancellationToken = default - ); - Task> HandleFilesSave( - IFormFileCollection files, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Interfaces\IXThumbnailProvider.cs - -using xStorageService.Models; - -namespace xStorageService.Interfaces { - public partial interface IXThumbnailProvider { - void SetTempFolder (string folder); - XImageInfo GetImageInfo (string filePath); - void ResizeImage ( - string filePath, - string resizedFilePath, - int size, - int quality - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Models\XFileResult.cs - -namespace xStorageService.Models { - public partial class XFileResult { - public string Name { get; set; } - public string FileName { get; set; } - public string FilePath { get; set; } - public string Thmbnail { get; set; } - public string ThmbnailPath { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Models\XImageInfo.cs - -using ImageMagick; - -namespace xStorageService.Models { - public partial class XImageInfo { - public Interlace Interlace { get; } - public int Height { get; } - public MagickFormat Format { get; } - public string FileName { get; } - public Density Density { get; } - public CompressionMethod Compression { get; } - public ColorSpace ColorSpace { get; } - public int Width { get; } - public int Quality { get; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Models\XStorageConfiguration.cs - -namespace xStorageService.Models { - public partial class XStorageConfiguration { - /// - /// Base Path of Identity Host Server - /// - /// - public string IdentityAuthority { get; set; } - - /// - /// Base Path of Host Server - /// - /// - public string Authority { get; set; } - - /// - /// Root Directory Of File Storage - /// - /// - public string RootFolder { get; set; } - - /// - /// Base Root of Usable Folder for Files - /// - /// - public string BaseFolder { get; set; } - - /// - /// Storage Folder Label - /// - /// - public string Storage { get; set; } - - /// - /// Temp Folder Label - /// - /// - public string Temp { get; set; } - - /// - /// Thumb Folder Label - /// - /// - public string Thumb { get; set; } - - /// - /// Uploads Folder Label - /// - /// - public string Uploads { get; set; } - - /// - /// Widgets Folder Label - /// - /// - public string Widgets { get; set; } - - /// - /// Images Folder Label - /// - /// - public string Image { get; set; } - - /// - /// Audios Folder Label - /// - /// - public string Audio { get; set; } - - /// - /// Videos Folder Label - /// - /// - public string Video { get; set; } - - /// - /// Documents Folder Label - /// - /// - public string Document { get; set; } - - /// - /// new Files Prefix - /// - /// - public string FilePrefix { get; set; } - - /// - /// Thumb Files Prefix - /// - /// - public string ThumbPrefix { get; set; } - - /// - /// Thumbnail File Sizes - /// - /// - public int ThumbSize { get; set; } - - /// - /// Thumbnail File Quality - /// - /// - public int ThumbQuality { get; set; } - - /// - /// Max File Size - /// - /// - public long MaxFileSize { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Providers\XStorageProvider.cs - -using System; -using System.IO; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Constants; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xStorageService.Models; -using xStorageService.Helpers; -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using xStorageService.Interfaces; -using System.Collections.ObjectModel; -using Microsoft.Extensions.FileProviders; - -namespace xStorageService.Providers -{ - public partial class XStorageProvider : IXStorageProvider - { - - public readonly string BasePath; - private readonly XFileType[] ThumbSupprtedTypes = new XFileType[] { - XFileType.Image, XFileType.CoverImage, XFileType.ProfileImasge - }; - - public IFileProvider FileProvider { get; } - public XStorageHelper StorageHelper { get; } - public IXThumbnailProvider ThumbnailProvider { get; } - public XStorageConfiguration Configuration { get; } - - public XStorageProvider( - IFileProvider fileProvider, - XStorageHelper storageHelper, - IXThumbnailProvider thumbnailProvider, - XStorageConfiguration configuration - ) - { - // - FileProvider = fileProvider; - Configuration = configuration; - StorageHelper = storageHelper; - ThumbnailProvider = thumbnailProvider; - - // - BasePath = Path - .Combine(Directory - .GetCurrentDirectory(), Configuration.BaseFolder); - } - - // - #region Special Folders Path Getter (s) ... - /// - /// Get Storage Folder Path - /// - /// - public string GetStorageFolderPath() - { - return Path.Combine(BasePath, Configuration.Storage); - } - - /// - /// Get Temp Folder Path - /// - /// - public string GetTempFolderPath() - { - return Path.Combine(GetStorageFolderPath(), Configuration.Temp); - } - - /// - /// Get Uploads Folder Path - /// - /// - public string GetUploadsFolderPath() - { - return Path.Combine(GetStorageFolderPath(), Configuration.Uploads); - } - - /// - /// Get Widgets Folder Path - /// - /// - public string GetWidgetsFolderPath() - { - return Path.Combine(GetStorageFolderPath(), Configuration.Widgets); - } - - /// - /// Get Thumb Folder Path - /// - /// - public string GetThumbFolderPath() - { - return Path.Combine(GetUploadsFolderPath(), Configuration.Thumb); - } - - /// - /// Get Images Folder Path - /// - /// - public string GetImageFolderPath() - { - return Path.Combine(GetUploadsFolderPath(), Configuration.Image); - } - - /// - /// Get Audios Folder Path - /// - /// - public string GetAudioFolderPath() - { - return Path.Combine(GetUploadsFolderPath(), Configuration.Audio); - } - - /// - /// Get Videos Folder Path - /// - /// - public string GetVideoFolderPath() - { - return Path.Combine(GetUploadsFolderPath(), Configuration.Video); - } - - /// - /// Get Documents Folder Path - /// - /// - public string GetDocumentFolderPath() - { - return Path.Combine(GetUploadsFolderPath(), Configuration.Document); - } - - /// - /// Prepare Full Path to Use for Static Files - /// - /// - /// - public string FilePathResolver(string fullPath) - { - return fullPath.Replace(BasePath, ""); - } - - /// - /// Convert a File Path to Url - /// - /// - /// - public string ConvertToProfileImageUrl(string fullPath) - { - // - var authority = !Configuration.IdentityAuthority.IsNullOrEmpty() && - Configuration.IdentityAuthority.EndsWith("/") ? - Configuration.IdentityAuthority.Substring(0, Configuration.IdentityAuthority.Length - 1) : - Configuration.IdentityAuthority; - - // - return $"{authority}{FilePathResolver(fullPath)}"; - } - - /// - /// Convert a File Path to Url - /// - /// - /// - public string ConvertToFileUrl(string fullPath) - { - // - var authority = !Configuration.Authority.IsNullOrEmpty() && - Configuration.Authority.EndsWith("/") ? - Configuration.Authority.Substring(0, Configuration.Authority.Length - 1) : - Configuration.Authority; - - // - return $"{authority}/{FilePathResolver(fullPath)}"; - } - #endregion - - // - #region Prepare Storage Structure ... - /// - /// Check Folder Structure of Storage Area - /// and Create them if not Exists - /// - public void Prepare() - { - // - try - { - // - // Storage Folder Path Check ... - if (!IsFolderExists(GetStorageFolderPath())) - { - Directory.CreateDirectory(GetStorageFolderPath()); - } - - // - // Temp Folder Path Check ... - if (!IsFolderExists(GetTempFolderPath())) - { - Directory.CreateDirectory(GetTempFolderPath()); - } - - // - // Temp Folder Path Check ... - if (!IsFolderExists(GetThumbFolderPath())) - { - Directory.CreateDirectory(GetThumbFolderPath()); - } - - // - // Widgets Folder Path Chekc ... - if (!IsFolderExists(GetWidgetsFolderPath())) - { - Directory.CreateDirectory(GetWidgetsFolderPath()); - } - - // - // Uploads Folder Path Chekc ... - if (!IsFolderExists(GetUploadsFolderPath())) - { - Directory.CreateDirectory(GetUploadsFolderPath()); - } - - // - // Image Folder Path Chekc ... - if (!IsFolderExists(GetImageFolderPath())) - { - Directory.CreateDirectory(GetImageFolderPath()); - } - - // - // Music Folder Path Chekc ... - if (!IsFolderExists(GetAudioFolderPath())) - { - Directory.CreateDirectory(GetAudioFolderPath()); - } - - // - // Video Folder Path Chekc ... - if (!IsFolderExists(GetVideoFolderPath())) - { - Directory.CreateDirectory(GetVideoFolderPath()); - } - - // - // Document Folder Path Chekc ... - if (!IsFolderExists(GetDocumentFolderPath())) - { - Directory.CreateDirectory(GetDocumentFolderPath()); - } - } - catch - { - XException.StorageServiceInitialFailed.Throw(); - } - - // - // Set Temp Folder for Actions ... - ThumbnailProvider.SetTempFolder(GetTempFolderPath()); - } - #endregion - - // - #region Validators ... - /// - /// Detrmines a Path Exists or not - /// - /// - /// - public bool IsFolderExists(string path) - { - return Directory.Exists(path); - } - - /// - /// Check a File Exists or not - /// - /// - /// - public bool IsFileExists(string filePath) - { - return File.Exists(filePath); - } - - /// - /// Check a File Name Support Thumbnail or not - /// - /// - /// - public bool IsSupportThumb(string fileName) - { - // - if (!fileName.StartsWith(Configuration.FilePrefix)) - { - XException.InavlidFile.Throw(); - } - - // - var fileType = StorageHelper.GetType(fileName); - return IsSupportThumb(fileType); - } - - /// - /// Check a FileType Support Thumbnail or not - /// - /// - /// - public bool IsSupportThumb(XFileType type) - { - return ThumbSupprtedTypes.Contains(type); - } - - /// - /// Validate a File Exists or not - /// - /// - public void ValidateFileExists(string filePath) - { - // - if (!IsFileExists(filePath)) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate a File Model with it's Related Physical File - /// - /// - public void ValidateFileModel(XFileDto file) - { - // - // Validate Args ... - if (file == null) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Full File Path ... - var fileFullPath = file.Path; - if (fileFullPath.IsNullOrEmpty()) - { - XException.InavlidFile.Throw(); - } - - // - // Retrieve is File Exists or not ... - var isPhysicalFileExists = IsFileExists(file.Path); - if (!isPhysicalFileExists) - { - XException.NotFound.Throw(); - } - } - - /// - /// Validate File for Upload - /// - /// - public void ValidateFile(IFormFile file) - { - // - // Validate Args ... - if (file == null) - { - XException.InvalidArgs.Throw(); - } - - // - // Check File Size not Zero ... - if (file.Length == 0) - { - XException.EmptyFile.Throw(); - } - - // - // Check File Max Size ... - if (file.Length > Configuration.MaxFileSize) - { - XException.MaxFileSizeExceeded.Throw(); - } - } - - /// - /// Validate a Collection of IFormFile - /// - /// - public void ValidateFiles(IFormFileCollection files) - { - // - // Validate Args ... - if (!files.HasChild()) - { - XException.InvalidArgs.Throw(); - } - - // - files.ToList() - .ForEach(f => ValidateFile(f)); - } - - /// - /// Validate File for Profile Image - /// - /// - public void ValidateProfileImage(IFormFile file) - { - // - // Check File Validation ... - // since Args Checked in File Validation, there is no need to - // double check it ... - ValidateFile(file); - - // - // Check File Type ... - var fileType = GetFileType(file.FileName); - if (fileType != XFileType.Image) - { - XException.UnsupportedFileType.Throw(); - } - } - #endregion - - // - #region Generators ... - /// - /// Generate New File - /// - /// - public string NewFileName() - { - return Configuration.FilePrefix + Guid.NewGuid().ToString().ToLower(); - } - - /// - /// Retrieve Related Thumnail File - /// - /// - /// - public string GenerateThumbName(string fileName) - { - // - if (!IsSupportThumb(fileName)) - { - XException.UnsupportedFileType.Throw(); - } - - // - return fileName.Replace(Configuration.FilePrefix, Configuration.ThumbPrefix); - } - - /// - /// Get a New FileName with Extension based on Given fileName - /// - /// - /// - public string GetNewFileName(string fileName) - { - // - // Validate Args ... - if (fileName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var fileExt = GetFileExtension(fileName); - var newFileNameWithoutExt = NewFileName(); - - // - // Generate New File Name ... - var newFileName = string.Format("{0}{1}", newFileNameWithoutExt, fileExt); - - // - return newFileName; - } - #endregion - - // - #region Tools Actions ... - /// - /// Extract a FileName's Extension - /// - /// - /// - public string GetFileExtension(string fileName) - { - // - var result = StorageHelper.GetFileExtension(fileName); - if (result.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - return result; - } - - /// - /// Extract a FileName's Without it's Extension - /// - /// - /// - public string GetFileNameWithoutExtension(string fileName) - { - // - var result = StorageHelper.GetFileNameWithoutExtension(fileName); - if (result.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - return result; - } - - /// - /// Get file Extension of Specified File Name - /// - /// - /// - public XFileExtensions GetFileExtensionType(string fileName) - { - // - var fileExt = GetFileExtension(fileName); - if (fileExt.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - var result = StorageHelper.GetExtensionType(fileExt); - if (result == -1) - { - XException.UnsupportedFileType.Throw(); - } - - // - return (XFileExtensions)result; - } - - /// - /// Return File Type of Specific File Name - /// - /// - /// - public XFileType GetFileType(string fileName) - { - // - var fileExtension = GetFileExtensionType(fileName); - return GetFileType(fileExtension); - } - - /// - /// Return File Type of Specific Extension - /// - /// - /// - public XFileType GetFileType(XFileExtensions fileExtension) - { - return StorageHelper.GetType((int)fileExtension); - } - - /// - /// Retrieve Full Path of thumbnail File - /// - /// - /// - public string GetThumbnailFileFullPath(string thumFileName) - { - // - if (!thumFileName.StartsWith(Configuration.ThumbPrefix)) - { - XException.InavlidFile.Throw(); - } - - // - return Path.Combine(GetThumbFolderPath(), thumFileName); - } - - /// - /// Retrieve a File Thumbnail Path if Supported - /// - /// - /// - public string GetRelatedThumbnailFullPath(string fileName) - { - // - var thumbName = GenerateThumbName(fileName); - return GetThumbnailFileFullPath(thumbName); - } - - /// - /// Retrieve Special File Type's Folder Path - /// - /// - /// - public string GetFileTypeFolderPath(XFileType type) - { - // - // Retrieve Folder Path Based on file ... - switch (type) - { - case XFileType.Image: - case XFileType.CoverImage: - case XFileType.ProfileImasge: - return GetImageFolderPath(); - - case XFileType.Audio: - return GetAudioFolderPath(); - - case XFileType.Video: - return GetVideoFolderPath(); - - case XFileType.Document: - default: - return GetDocumentFolderPath(); - } - } - - /// - /// Retrieve a File's Folder path - /// - /// - /// - /// - /// - public string GetFileFolderPath( - string fileName, - bool isTemp = false, - bool isWidget = false - ) - { - // - // Validate Args ... - if (fileName.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - var fileType = GetFileType(fileName); - - // - var folderPath = ""; - - // - // if isTemp equals true - // ignore file type and return Temp Folder ... - if (isTemp) - { - folderPath = GetTempFolderPath(); - } - - // - // if isWidget equals true and isTemp equals false - // ignore file type and return Widget's Folder ... - if (isWidget && !isTemp) - { - folderPath = GetWidgetsFolderPath(); - } - - // - // if both isTemp and isWidget equals false - // which is the default state, retrieve proper folder path - // based on file type and return it ... - if (!isTemp && !isWidget) - { - folderPath = GetFileTypeFolderPath(fileType); - } - - // - // Check folderPath restrict to have Value ... - if (folderPath.IsNullOrEmpty()) - { - XException.InvalidData.Throw(); - } - - // - // return result ... - return folderPath; - } - - /// - /// Retrieve a Full path of a File - /// - /// - /// - /// - /// - public string GetFileFullPath( - string fileName, - bool isTemp = false, - bool isWidget = false - ) - { - // - var folderPath = GetFileFolderPath( - fileName, - isTemp: isTemp, - isWidget: isWidget - ); - - // - if (folderPath.IsNullOrEmpty()) - { - XException.ActionFailed.Throw(); - } - - // - return Path.Combine(folderPath, fileName); - } - - /// - /// Save a File into Storage Based on it's Type - /// - /// - /// - /// - /// - /// - public async Task SaveFileAsync( - IFormFile file, - bool isTemp = false, - bool isWidget = false, - CancellationToken cancellationToken = default - ) - { - // - // Validate Args ... - ValidateFile(file); - - // - // Extract and Generate required Data ... - var fileName = GetNewFileName(file.FileName); - var folderPath = GetFileFolderPath(file.FileName, isTemp, isWidget); - var fileFullPath = Path.Combine(folderPath, fileName); - - // - // Save File ... - using (var stream = new FileStream(fileFullPath, FileMode.Create)) - { - // - await file.CopyToAsync( - stream, - cancellationToken - ); - } - - // - // Since all Required data can be Generated based on - // a simple file Name, there is no need to return additional - // data as result ... - return fileName; - } - - /// - /// Delete a Physical File by Validate it's Exists - /// - /// - /// - /// - public void DeleteFile( - string fileFullPath, - bool forceFileExists = true, - Exception exception = null - ) - { - // - // Validate Args ... - if (!forceFileExists && - fileFullPath.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Prepare Default Exception ... - if (exception == null) - { - exception = XException.NotFound.ToException(); - } - - // - // Check File Exists ... - var isFileExists = File.Exists(fileFullPath); - if (forceFileExists && - !isFileExists) - { - XException.NotFound.Throw(); - } - - // - // Handle Prevent Error when forceFileExists false - // and File doesn't Exists ... - if (!forceFileExists && - !isFileExists) - { - return; - } - - // - File.Delete(fileFullPath); - } - - /// - /// Remove a List of Physical Files Path - /// and return Un Removable Files ... - /// - /// - /// - /// - /// - public ICollection DeleteFiles( - ICollection fileFullPaths, - bool forceFileExists = true, - Exception exception = null - ) - { - // - if (exception.IsNull()) - { - exception = XException.NotFound.ToException(); - } - - // - var result = fileFullPaths.Where(f => !IsFileExists(GetFileFullPath(f))).ToList(); - if (forceFileExists && result.HasChild()) - { - throw exception; - } - - // - var existsFile = fileFullPaths.Where(f => IsFileExists(f)).ToList(); - existsFile.ForEach(f => - { - DeleteFile( - f, - forceFileExists: forceFileExists, - exception: exception - ); - }); - - // - return fileFullPaths.Except(existsFile).ToList(); - } - - /// - /// Create Thumbnail based on FileName.Ext - /// - /// - /// - /// - public async Task CreateThumbnail( - string fileName, - CancellationToken cancellationToken = default - ) - { - // - if (fileName.IsNullOrEmpty()) - { - return; - } - - // - await Task.Run(() => - { - // - var fileFullPath = GetFileFullPath(fileName); - if (!IsFileExists(fileFullPath)) - { - XException.NotFound.Throw(); - } - - // - var thumbFileName = GenerateThumbName(fileName); - var thumbFullPath = GetThumbnailFileFullPath(thumbFileName); - - // - ThumbnailProvider.ResizeImage( - fileFullPath, - thumbFullPath, - Configuration.ThumbSize, - Configuration.ThumbQuality - ); - }, cancellationToken); - } - - /// - /// Create Thumbnail based on XFile model - /// - /// - /// - /// - public async Task CreateThumbnail( - XFileDto file, - CancellationToken cancellationToken = default - ) - { - // - await CreateThumbnail( - file.Name, - cancellationToken - ); - } - - /// - /// Save and Create a Thumbnail For Profile Image - /// - /// - /// - /// - public async Task HandleProfileImageSave( - IFormFile file, - CancellationToken cancellationToken = default - ) - { - // - ValidateProfileImage(file); - - // - var savedFileName = await SaveFileAsync( - file, - isTemp: false, - isWidget: false, - cancellationToken: cancellationToken - ); - var thumbFileName = GenerateThumbName(savedFileName); - - // - var savedFileFullPath = GetFileFullPath(savedFileName); - var thumbFullPath = GetThumbnailFileFullPath(thumbFileName); - - // - await CreateThumbnail( - savedFileName, - cancellationToken - ); - - // - return new XFileResult - { - Name = file.Name, - FileName = savedFileName, - FilePath = ConvertToProfileImageUrl(savedFileFullPath), - Thmbnail = thumbFileName, - ThmbnailPath = ConvertToProfileImageUrl(thumbFullPath) - }; - } - - /// - /// Handle File Upload with Support of Thumbnails ... - /// - /// - /// - /// - public async Task HandleFileSave( - IFormFile file, - CancellationToken cancellationToken = default - ) - { - // - ValidateFile(file); - - // - var savedFileName = await SaveFileAsync(file, isTemp: false, isWidget: false); - - // - var savedFileFullPath = GetFileFullPath(savedFileName); - - // - var thumbFileName = ""; - var thumbFullPath = ""; - var fileType = GetFileType(savedFileName); - if (fileType.IsImageKind()) - { - // - thumbFileName = GenerateThumbName(savedFileName); - thumbFullPath = GetThumbnailFileFullPath(thumbFileName); - - // - await CreateThumbnail(savedFileName); - } - - // - var result = - new XFileResult - { - Name = file.FileName, - FileName = savedFileName, - FilePath = ConvertToFileUrl(savedFileFullPath), - Thmbnail = thumbFileName, - ThmbnailPath = ConvertToFileUrl(thumbFullPath), - }; - - // - return result; - } - - /// - /// Handle File Upload with Support of Thumbnails ... - /// - /// - /// - /// - public async Task> HandleFilesSave( - IFormFileCollection files, - CancellationToken cancellationToken = default - ) - { - // - ValidateFiles(files); - - // - var result = new Collection(); - foreach (var file in files) - { - // - var savedFileName = await SaveFileAsync( - file, - isTemp: false, - isWidget: false, - cancellationToken: cancellationToken - ); - - // - var savedFileFullPath = GetFileFullPath(savedFileName); - - // - var thumbFileName = ""; - var thumbFullPath = ""; - var fileType = GetFileType(savedFileName); - if (fileType.IsImageKind()) - { - // - thumbFileName = GenerateThumbName(savedFileName); - thumbFullPath = GetThumbnailFileFullPath(thumbFileName); - - // - await CreateThumbnail( - savedFileName, - cancellationToken - ); - } - - // - result.Add( - new XFileResult - { - Name = file.FileName, - FileName = savedFileName, - FilePath = ConvertToFileUrl(savedFileFullPath), - Thmbnail = thumbFileName, - ThmbnailPath = ConvertToFileUrl(thumbFullPath), - }); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStorageService\Providers\XThumbnailProvider.cs - -using ImageMagick; -using xCommons.Extensions; -using xStorageService.Models; -using xStorageService.Interfaces; - -namespace xStorageService.Providers { - public partial class XThumbnailProvider : IXThumbnailProvider { - public void SetTempFolder (string folder) { - MagickNET.SetTempDirectory (folder); - } - - public XImageInfo GetImageInfo (string filePath) { - // - MagickImageInfo info = new MagickImageInfo (filePath); - return info.MapConvert (); - } - - public void ResizeImage ( - string filePath, - string resizedFilePath, - int size, - int quality - ) { - // - using (var image = new MagickImage (filePath)) { - // - image.Resize (size, size); - image.Strip (); - image.Quality = quality; - image.Write (resizedFilePath); - } - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xStringService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xStringService-20261109_152621.txt deleted file mode 100644 index 7be6437..0000000 --- a/Documents/GeneratedContext/xDashboard-xStringService-20261109_152621.txt +++ /dev/null @@ -1,7011 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Configurations\Entities\XStringEntityConfiguration.cs - -using xDataService.Providers; -using xStringService.Constants; -using Microsoft.EntityFrameworkCore; -using xStringService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xStringService.Configurations.Entities -{ - public class XStringEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XStringServiceConstants.XStringTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Constants\XStringServiceConstants.cs - -namespace xStringService.Constants -{ - public struct XStringServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XStringServiceDILogTag = "XStringService"; - - // - // Table Mapping Identifiers ... - public const string XStringTable = "Strings"; - - // - // GraphQL Collection Mappings ... - public const string XStringSingleName = "string"; - public const string XStringCollectionName = "strings"; - - // - // Hubs ... - public const string XStringDtoHub = "stringDto"; - public const string XStringEntityHub = "stringEntity"; - - // - // Custome Constants ... - - // - // EF Repositories Helper Extensions ... - public const string GetXStringEFRepositoryDescriptor = "GetXStringEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XBaseItemResourceProviderControllerBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; - -namespace xStringService.Controllers -{ - public abstract class XBaseItemResourceProviderControllerBase : XBaseIdentityApiV1Controller, IXBaseItemResourceProviderController - { - private readonly IXItemResourceProvider provider; - - protected XBaseItemResourceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXItemResourceProvider provider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.provider = provider; - } - - // - #region Actions ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// if null or empty, check all languages in Item Side - /// - /// - [HttpGet("Languages")] - public virtual async Task>> GetLanguages( - [FromQuery] object identifier, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = Enumerable.Empty(); - if (!identifier.IsNull()) - { - // - result = await provider.GetLanguages( - identifier: identifier, - cancellationToken: cancellationToken - ); - } - else - { - // - result = await provider.GetLanguages( - cancellationToken: cancellationToken - ); - } - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Exists Items ... - /// - /// Specified Resource Title - /// - /// - [HttpGet("ResourceLocales")] - public virtual async Task>> GetResourceLocales( - [FromQuery] object identifier, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = Enumerable.Empty(); - if (!identifier.IsNull()) - { - // - result = await provider.GetResourceLocales( - identifier: identifier, - cancellationToken: cancellationToken - ); - } - else - { - // - result = await provider.GetResourceLocales( - cancellationToken: cancellationToken - ); - } - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - [HttpGet("Locales/{identifier}")] - public virtual async Task>> GetLocales( - [FromRoute] object identifier, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - - // - return Ok(); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// if null or empty Remove all Locales - /// - /// - [HttpDelete("Locales/{identifier}")] - public virtual async Task> RemoveLocale( - [FromRoute] object identifier, - [FromQuery] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - var isValid = !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Connection ID ... - var connectionId = GetConnectionId(); - - // - XResourceDto result = null; - if (!language.IsNullOrEmpty()) - { - // - result = await provider.RemoveLocale( - language: language, - identifier: identifier, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - await provider.RemoveLocales( - identifier: identifier, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - [HttpGet("Locales/{identifier}/{language}/Has")] - public virtual async Task> HasLocale( - [FromRoute] object identifier, - [FromRoute] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(language) - .AddNotNull(identifier) - .ValidateGroupAsync(); - - // - // Calculate Result ... - var result = await provider.HasLocale( - language: language, - identifier: identifier, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - [HttpGet("Resource/{identifier}")] - public virtual async Task> GetResource( - [FromRoute] object identifier, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - ValidationProvider.NotNull(identifier); - - // - var result = await provider.GetResource( - identifier: identifier, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - [HttpPost("Locales/{identifier}")] - public virtual async Task> AddOrUpdateLocale( - [FromRoute] object identifier, - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(identifier) - .AddNotNull(locale) - .AddNotEmpty(locale.Value) - .AddNotEmpty(locale.Language) - .ValidateGroupAsync(); - - // - // Retrieve Connection ID ... - var connectionId = GetConnectionId(); - - // - var result = await provider.AddOrUpdateLocale( - locale: locale, - identifier: identifier, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - [HttpPost("Resource/{identifier}")] - public virtual async Task> AddOrUpdateResource( - [FromRoute] object identifier, - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(identifier) - .AddNotNull(resource) - .ValidateGroupAsync(); - - // - // Retrieve Connection ID ... - var connectionId = GetConnectionId(); - - // - var result = await provider.AddOrUpdateResource( - resource: resource, - identifier: identifier, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XBaseResourceProviderControllerBase.cs - -using System; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; - -namespace xStringService.Controllers -{ - public abstract class XBaseResourceProviderControllerBase : XBaseIdentityApiV1Controller, IXBaseResourceProviderController - where TResourceProvider : IXResourceProvider - { - private readonly TResourceProvider provider; - - protected XBaseResourceProviderControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - TResourceProvider provider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.provider = provider; - } - - #region Actions ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - [HttpGet("Languages")] - public virtual async Task>> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLanguages(cancellationToken); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Exists Items ... - /// - /// Specified Resource Title - /// - /// - [HttpGet("LocalesResource")] - public virtual async Task>> GetResourceLocales( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResourceLocales(cancellationToken); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Extract Translation of in Specified Language ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Translation")] - public virtual async Task> GetResourceTranslation( - [FromRoute] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResourceTranslation( - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Check Has Specified Translation or not ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Has")] - public virtual async Task> HasLocale( - [FromRoute] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .HasLocale( - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve as Locale Model ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Locale")] - public virtual async Task> GetLocale( - [FromRoute] string language, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLocale( - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Exists Locale Models ... - /// - /// - /// - [HttpGet("Locales")] - public virtual async Task>> GetLocales( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLocales(cancellationToken); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve as XResourceDto ... - /// - /// - /// - [HttpGet("Resource")] - public virtual async Task> GetResource( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResource(cancellationToken); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("")] - public virtual async Task> AddOrUpdateResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .AddOrUpdateResource( - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add Or Update Locale ... - /// - /// - /// - /// - [HttpPost("Locales")] - public virtual async Task> AddOrUpdateLocale( - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .AddOrUpdateLocale( - locale: locale, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Locale ... - /// - /// - /// - /// - [HttpPost("Locale/Remove")] - public virtual async Task> RemoveLocale( - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .RemoveLocale( - locale: locale, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("Resource/Remove")] - public virtual async Task RemoveResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - await provider - .RemoveResource( - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XStringProviderControllerBase.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xPushService.Controllers; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xStringService.Providers.Dtos; -using xStringService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xStringService.Controllers -{ - public abstract class XStringProviderControllerBase : XBaseProvidedController, IXStringProviderController - { - private readonly IXStringProvider provider; - - protected XStringProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXStringProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { - this.provider = provider; - } - - // - #region Tools ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - [HttpGet("Languages")] - public virtual async Task>> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLanguages(cancellationToken); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve a List of Resource Titles ... - /// - /// if provided, returns all language Specified resource titles, if not, all Resource Titles - /// - /// - [HttpGet("ResourceTitles")] - public virtual async Task>> GetResourceTitles( - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResourceTitles( - language: language, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Exists Items which belongs to Specified Resource Title ... - /// - /// Specified Resource Title - /// - /// - [HttpGet("ResourceLocales")] - public virtual async Task>> GetResourceLocales( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResourceLocales( - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Extract Translation of a Resource in Specified Language ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - [HttpGet("Translation")] - public virtual async Task> GetResourceTranslation( - [FromQuery] string language, - [FromQuery] string resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResourceTranslation( - language: language, - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve a Resource as Locale Model ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - [HttpGet("Locale")] - public virtual async Task> GetLocale( - [FromQuery] string language, - [FromQuery] string resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLocale( - language: language, - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Exists Resource Instances as Locale Models ... - /// - /// - /// - /// - [HttpGet("Locales")] - public virtual async Task>> GetLocales( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetLocales( - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve all Locales of Specified Resource and Represent as XResourceDto ... - /// - /// - /// - /// - [HttpGet("GetResource")] - public virtual async Task> GetResource( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - var result = await provider - .GetResource( - resource: resource, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("AddOrUpdateResource")] - public virtual async Task> AddOrUpdateResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(resource) - .AddNotEmpty(resource.Resource) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider - .AddOrUpdateResource( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("RemoveResource")] - public virtual async Task RemoveResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(resource) - .AddNotEmpty(resource.Resource) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - await provider - .RemoveResource( - resource: resource, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XStringRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using Microsoft.Extensions.Logging; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xStringService.Controllers -{ - public abstract class XStringRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XStringRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXStringRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XStringRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xStringService.Models.Entities; -using xStringService.Providers.Entities; -using xStringService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xStringService.Controllers -{ - public abstract class XStringRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XStringRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXStringRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XStringServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using xStringService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xStringService.Controllers -{ - public abstract class XStringServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XStringServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXStringRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Controllers\XStringServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xStringService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xStringService.Providers.Dtos; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xStringService.Controllers -{ - public abstract class XStringServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XStringServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXStringServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xPushService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xStringService.Helpers; -using xStringService.Providers; -using xStringService.Constants; -using xStringService.Interfaces; -using Microsoft.AspNetCore.Builder; -using xStringService.Providers.Dtos; -using xStringService.Interfaces.Dtos; -using xStringService.Providers.Entities; -using xStringService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xStringService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXStringService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddStringService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXStringService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddStringService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XStringService Middleware ... - /// - /// - /// - public static void UseXStringService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XString Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XStringServiceConstants.XStringDtoHub); - pushHelper.AddHub(XStringServiceConstants.XStringEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XString Repository Descriptor ... - if (!descriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XStringServiceConstants.XStringServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddStringService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch(repositoryType) - { - // - case XRepositoryType.EF: - // - descriptor = typeof(XStringServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XStringServiceConstants.GetXStringEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - descriptor = XStringServiceHelper.GetXStringMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - descriptor = XStringServiceHelper.GetXStringInMemoryRepositoryDescriptor(); - break; - } - - // - // Register XString Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: descriptor - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXStringServiceProvider), typeof(XStringServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXStringRepositoryService), typeof(XStringRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXStringRepositoryProvider), typeof(XStringRepositoryProvider), lifeTime) - ); - - // - // Register XString Provider ... - services.Add( - new ServiceDescriptor(typeof(IXStringProvider), typeof(XStringProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Extensions\XModelExtensions.cs - -using System.Linq; -using xModels.Dtos; -using xCommons.Extensions; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Extensions -{ - public static class XModelExtensions - { - /// - /// Converts an Entity to LocaleResource Dto ... - /// - /// - /// - public static XLocaleResourceDto ToXLocaleResourceDto(this XString source) - { - // - var result = new XLocaleResourceDto - { - Language = source.IsNull() ? "" : source.Language, - Value = source.IsNull() ? "" : source.TranslatedValue, - }; - - // - return result; - } - - /// - /// Converts an Dto to LocaleResource Dto ... - /// - /// - /// - public static XLocaleResourceDto ToXLocaleResourceDto(this XStringDto source) - { - // - var result = new XLocaleResourceDto - { - Language = source.IsNull() ? "" : source.Language, - Value = source.IsNull() ? "" : source.TranslatedValue, - }; - - // - return result; - } - - /// - /// Converts a Collection of Entities to Locale Resource Presentation ... - /// - /// - /// - public static IEnumerable ToXLocaleResourceDtos(this IEnumerable source) - { - // - var result = source.Select(e => ToXLocaleResourceDto(e)); - return result; - } - - /// - /// Converts a Collection of Dtos to Locale Resource Presentation ... - /// - /// - /// - public static IEnumerable ToXLocaleResourceDtos(this IEnumerable source) - { - // - var result = source.Select(e => ToXLocaleResourceDto(e)); - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Helpers\XStringServiceHelper.cs - -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xDataHelper.Providers.GraphQL; -using xStringService.Models.Entities; -using xStringService.Providers.GraphQL; -using xStringService.Providers.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Helpers -{ - public static class XStringServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringEFRepository, - TContext - > GetXStringEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringEFRepository, - TContext, - IXStringSeeder, - TSeederImplementation - > GetXStringEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringEFRepository, - TContext, - IXStringSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringMongoRepository - > GetXStringMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringMongoRepository, - IXStringSeeder, - TSeederImplementation - > GetXStringMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringMongoRepository, - IXStringSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringInMemoryRepository - > GetXStringInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringInMemoryRepository, - IXStringSeeder, - TSeederImplementation - > GetXStringInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XString, - int, - IXStringKeyGenerator, - XStringKeyGenerator, - IXStringRepositoryEvents, - XStringRepositoryEvents, - XStringGraphType, - IntGraphType, - XStringGraphQuery, - IXStringGraphQLTypeHelper, - XStringGraphQLTypeHelper, - XStringGraphSchema, - IXStringRepository, - XStringInMemoryRepository, - IXStringSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXBaseItemResourceProviderController.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xStringService.Interfaces -{ - public interface IXBaseItemResourceProviderController - { - /// - /// Retrieve a List of Exists Languages ... - /// - /// if null or empty, check all languages in Item Side - /// - /// - [HttpGet("Languages")] - Task>> GetLanguages( - [FromQuery] object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items ... - /// - /// Specified Resource Title - /// - /// - [HttpGet("ResourceLocales")] - Task>> GetResourceLocales( - [FromQuery] object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - [HttpGet("Locales/{identifier}")] - Task>> GetLocales( - [FromRoute] object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// if null or empty Remove all Locales - /// - /// - [HttpDelete("Locales/{identifier}")] - Task> RemoveLocale( - [FromRoute] object identifier, - [FromQuery] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - [HttpGet("Locales/{identifier}/{language}/Has")] - Task> HasLocale( - [FromRoute] object identifier, - [FromRoute] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - [HttpGet("Resource/{identifier}")] - Task> GetResource( - [FromRoute] object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - [HttpPost("Locales/{identifier}")] - Task> AddOrUpdateLocale( - [FromRoute] object identifier, - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ); - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - [HttpPost("Resource/{identifier}")] - Task> AddOrUpdateResource( - [FromRoute] object identifier, - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXBaseResourceProviderController.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xStringService.Interfaces -{ - public interface IXBaseResourceProviderController - { - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - [HttpGet("Languages")] - Task>> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items ... - /// - /// - /// - [HttpGet("LocalesResource")] - Task>> GetResourceLocales( - CancellationToken cancellationToken = default - ); - - /// - /// Extract Translation of in Specified Language ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Translation")] - Task> GetResourceTranslation( - [FromRoute] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Check Has Specified Translation or not ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Has")] - Task> HasLocale( - [FromRoute] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve as Locale Model ... - /// - /// Specified Language ... - /// - /// - [HttpGet("{language}/Locale")] - Task> GetLocale( - [FromRoute] string language, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Locale Models ... - /// - /// - /// - [HttpGet("Locales")] - Task>> GetLocales( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve as XResourceDto ... - /// - /// - /// - [HttpGet("Resource")] - Task> GetResource( - CancellationToken cancellationToken = default - ); - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("")] - Task> AddOrUpdateResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Locale ... - /// - /// - /// - /// - [HttpPost("Locales")] - Task> AddOrUpdateLocale( - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Locale ... - /// - /// - /// - /// - [HttpPost("Locale/Remove")] - Task> RemoveLocale( - [FromBody] XLocaleResourceDto locale, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("Resource/Remove")] - Task RemoveResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXItemResourceProvider.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xStringService.Interfaces -{ - public interface IXItemResourceProvider - { - // - #region Group Actions ... - /// - /// Retrieve a List of Exists Languages for Current Item ... - /// - /// - /// - Task> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items of type ... - /// - /// - /// - Task> GetResourceLocales( - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Exists Locales which Related to this Provider ... - /// - /// - /// - /// - Task RemoveResourceLocales( - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Item Actions ... - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - Task> GetResourceLocales( - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - Task> GetLocales( - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - Task GetResource( - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - /// - Task AddOrUpdateLocale( - object identifier, - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - /// - Task AddOrUpdateResource( - object identifier, - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// - /// - /// - /// - Task RemoveLocale( - object identifier, - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Exists Locales for Specified Identifier ... - /// - /// - /// - /// - /// - Task RemoveLocales( - object identifier, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - Task HasLocale( - object identifier, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Languages for Specified Identifier ... - /// - /// - /// - /// - Task> GetLanguages( - object identifier, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Resource Title Action ... - /// - /// Retrieve Resource Title ... - /// - /// - /// - string GetResourceTitle(object identifier = null); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXOwnedItemResourceProvider.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xStringService.Interfaces -{ - public interface IXOwnedItemResourceProvider - { - // - #region Group Actions ... - /// - /// Retrieve a List of Exists Languages for Current Item ... - /// - /// - /// - /// - Task> GetLanguages( - object owner, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items of type ... - /// - /// - /// - /// - Task> GetResourceLocales( - object owner, - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Exists Locales which Related to this Provider ... - /// - /// - /// - /// - /// - Task RemoveResourceLocales( - object owner, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Item Actions ... - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - /// - Task> GetResourceLocales( - object owner, - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - /// - Task> GetLocales( - object owner, - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - /// - Task GetResource( - object owner, - object identifier, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - /// - /// - Task AddOrUpdateLocale( - object owner, - object identifier, - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - /// - /// - Task AddOrUpdateResource( - object owner, - object identifier, - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// - /// - /// - /// - /// - Task RemoveLocale( - object owner, - object identifier, - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Exists Locales for Specified Identifier ... - /// - /// - /// - /// - /// - /// - Task RemoveLocales( - object owner, - object identifier, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - /// - Task HasLocale( - object owner, - object identifier, - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Get all Exists Languages for Specified Identifier ... - /// - /// - /// - /// - /// - Task> GetLanguages( - object owner, - object identifier = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Resource Title Action ... - /// - /// Retrieve Resource Title ... - /// - /// - /// - /// - string GetResourceTitle( - object owner = null, - object identifier = null - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXResourceProvider.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xStringService.Interfaces -{ - public interface IXResourceProvider - { - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - Task> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items ... - /// - /// - /// - Task> GetResourceLocales( - CancellationToken cancellationToken = default - ); - - /// - /// Extract Translation of in Specified Language ... - /// - /// Specified Language ... - /// - /// - Task GetResourceTranslation( - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Check Has Specified Translation or not ... - /// - /// Specified Language ... - /// - /// - Task HasLocale( - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve as Locale Model ... - /// - /// Specified Language ... - /// - /// - Task GetLocale( - string language, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Locale Models ... - /// - /// - /// - Task> GetLocales( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve as XResourceDto ... - /// - /// - /// - Task GetResource( - CancellationToken cancellationToken = default - ); - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - /// - Task AddOrUpdateResource( - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Locale ... - /// - /// - /// - /// - /// - Task AddOrUpdateLocale( - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Locale ... - /// - /// - /// - /// - /// - Task RemoveLocale( - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - /// - Task RemoveResource( - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXStringProvider.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xPushService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Providers.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces -{ - public interface IXStringProvider : IXBaseProvided - { - // - #region Tools ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - Task> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve a List of Resource Titles ... - /// - /// if provided, returns all language Specified resource titles, if not, all Resource Titles - /// - /// - Task> GetResourceTitles( - string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items which belongs to Specified Resource Title ... - /// - /// Specified Resource Title - /// - /// - Task> GetResourceLocales( - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Extract Translation of a Resource in Specified Language ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - Task GetResourceTranslation( - string language, - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve a Resource as Locale Model ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - Task GetLocale( - string language, - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Resource Instances as Locale Models ... - /// - /// - /// - /// - Task> GetLocales( - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Locales of Specified Resource and Represent as XResourceDto ... - /// - /// - /// - /// - Task GetResource( - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// Actor User for Permissions ... - /// - /// - /// - Task AddOrUpdateResource( - XResourceDto resource, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// Actor User for Permissions ... - /// - /// - /// - Task RemoveResource( - XResourceDto resource, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\IXStringProviderController.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Providers.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces -{ - public interface IXStringProviderController : IXBaseProvidedController - { - // - #region Tools ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - [HttpGet("Languages")] - Task>> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve a List of Resource Titles ... - /// - /// if provided, returns all language Specified resource titles, if not, all Resource Titles - /// - /// - [HttpGet("ResourceTitles")] - Task>> GetResourceTitles( - [FromQuery] string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Items which belongs to Specified Resource Title ... - /// - /// Specified Resource Title - /// - /// - [HttpGet("ResourceLocales")] - Task>> GetResourceLocales( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Extract Translation of a Resource in Specified Language ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - [HttpGet("Translation")] - Task> GetResourceTranslation( - [FromQuery] string language, - [FromQuery] string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve a Resource as Locale Model ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - [HttpGet("Locale")] - Task> GetLocale( - [FromQuery] string language, - [FromQuery] string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Exists Resource Instances as Locale Models ... - /// - /// - /// - /// - [HttpGet("Locales")] - Task>> GetLocales( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve all Locales of Specified Resource and Represent as XResourceDto ... - /// - /// - /// - /// - [HttpGet("GetResource")] - Task> GetResource( - [FromQuery] string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("AddOrUpdateResource")] - Task> AddOrUpdateResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - [HttpPost("RemoveResource")] - Task RemoveResource( - [FromBody] XResourceDto resource, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Dtos\IXStringDtoHub.cs - -using xPushService.Interfaces; -using xStringService.Models.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Dtos -{ - public interface IXStringDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Dtos\IXStringRepositoryService.cs - -using xDataService.Interfaces; -using xStringService.Models.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Dtos -{ - public interface IXStringRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Dtos\IXStringServiceProvider.cs - -using xModels.Dtos; -using System.Threading; -using System.Threading.Tasks; -using xCommons.Configurations; -using xPushService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Providers.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Dtos -{ - public interface IXStringServiceProvider : IXBaseDtoProvider - { - /// - /// Application Configuration ... - /// - XAppConfiguration AppConfiguration { get; } - - // - #region Retrievers ... - /// - /// Retrieve all Exists Languages ... - /// - /// - /// - Task> GetLanguages( - CancellationToken cancellationToken = default - ); - - /// - /// Check Specified Resource Exists or not ... - /// - /// - /// - /// - /// - Task IsResourceExists( - string resource, - string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Resource ... - /// - /// - /// - /// - /// - Task Get( - string resource, - string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Translation of Specified Resource ... - /// - /// - /// - /// - /// - Task GetResourceValue( - string resource, - string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve an Specified Resource Items ... - /// - /// - /// - /// - Task> GetResources( - string resource, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieve Specified Resource Items as XResourceDto Presentation ... - /// - /// - /// - /// - Task GetResource( - string resource, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Query ... - /// - /// Query Resource IDs ... - /// - /// - /// - /// - Task> QueryResourceIds( - XQuery query, - CancellationToken cancellationToken = default - ); - - /// - /// Query Specified Language Resources ... - /// - /// - /// - /// - /// - Task> QueryLanguageResources( - XQuery query, - string language = null, - CancellationToken cancellationToken = default - ); - - /// - /// Query Locale Resources ... - /// - /// - /// - /// - /// - Task> QueryLocaleResources( - XQuery query, - string language = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Add/Update Actions ... - /// - /// Add Specified Resource ... - /// - /// - /// - /// - /// - /// - /// - Task Add( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Resource ... - /// - /// - /// - /// - /// - /// - /// - Task Update( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Resource ... - /// - /// - /// - /// - /// - /// - /// - Task AddOrUpdate( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Specified Locale Resource ... - /// - /// - /// - /// - /// - /// - Task AddByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Update Specified Locale Resource ... - /// - /// - /// - /// - /// - /// - Task UpdateByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update Resource By Locale ... - /// - /// - /// - /// - /// - /// - Task AddOrUpdateByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Or Update all XResourceDto(s) Locales ... - /// - /// - /// - /// - /// - Task> AddByResource( - XResourceDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - - // - #region Remove Actions ... - /// - /// Remove all Specified Language's Resources ... - /// - /// - /// - /// - /// - Task RemoveLanguageResources( - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Specified Resource Ids instances ... - /// - /// - /// - /// - /// - Task> RemoveResource( - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Specified Resource ... - /// - /// - /// - /// - /// - /// - Task Remove( - string resource, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove all Resource of Specified XResourceDto ... - /// - /// - /// - /// - /// - Task RemoveByResource( - XResourceDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringEntityHub.cs - -using xPushService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringKeyGenerator.cs - -using xDataService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringRepository.cs - -using xDataService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringRepositoryEvents.cs - -using xDataService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringRepositoryProvider.cs - -using xPushService.Interfaces; -using xStringService.Models.Entities; -using xStringService.Providers.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Interfaces\Entities\IXStringSeeder.cs - -using xDataService.Interfaces; -using xStringService.Models.Entities; - -namespace xStringService.Interfaces.Entities -{ - public interface IXStringSeeder : IXBaseDbSeeder - {} -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Models\Dtos\XStringDto.cs - -using xModels.Base; - -namespace xStringService.Models.Dtos -{ - public class XStringDto : XBaseIntIDEntityDto - { - public string Language { get; set; } - public string ResourceTitle { get; set; } - public string TranslatedValue { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Models\Entities\XString.cs - -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xStringService.Models.Entities -{ - public class XString : XBaseIntIDEntity - { - [Required] - [StringLength (10)] - public string Language { get; set; } - - [Required] - [StringLength (255)] - public string ResourceTitle { get; set; } - - [Required] - public string TranslatedValue { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\XBaseItemResourceProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Interfaces.Dtos; - -namespace xStringService.Providers -{ - public abstract class XBaseItemResourceProvider : IXItemResourceProvider - { - // - #region Props ... - /// - /// Item Name for Resource Providing ... - /// - private readonly string item; - - /// - /// an Implementation of Item Resource Provider - /// - /// - private readonly XBaseResourceProvider provider; - - /// - /// String Provider Service ... - /// - private readonly IXStringServiceProvider stringProvider; - #endregion - - // - #region Constructor ... - protected XBaseItemResourceProvider( - string item, - IXStringServiceProvider stringProvider - ) - { - // - this.item = item; - this.stringProvider = stringProvider; - provider = new XBaseResourceProvider( - item, - stringProvider - ); - } - #endregion - - // - #region Group Actions ... - /// - /// Retrieve a List of Exists Languages for Current Item ... - /// - /// - /// - public virtual async Task> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - var result = (await ExtractItems(cancellationToken)) - .Select(x => x.Language) - .Distinct(); - - // - return result; - } - - /// - /// Retrieve all Exists Items of type ... - /// - /// - /// - public virtual async Task> GetResourceLocales( - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractItems(cancellationToken); - - // - return result; - } - - /// - /// Remove all Exists Locales which Related to this Provider ... - /// - /// - /// - /// - public virtual async Task RemoveResourceLocales( - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var isDelete = false; - XStringDto deleted = null; - var items = await ExtractItems(cancellationToken); - foreach (var item in items) - { - // - // Check Cancellation ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Remove Item ... - deleted = await stringProvider.RemoveAsync( - id: item.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Check Removation Succeed ... - isDelete = !deleted.IsNullOrDefault(); - if (!isDelete) - { - XException.ActionFailed.Throw(); - } - } - } - #endregion - - // - #region Item Actions ... - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - public virtual async Task> GetResourceLocales( - object identifier, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - // Retrieve Resource List ... - var result = await provider - .GetResourceLocales(cancellationToken); - - // - return result; - } - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - public virtual async Task> GetLocales( - object identifier, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - // Retrieve Resource List ... - var result = await provider - .GetLocales(cancellationToken); - - // - return result; - } - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - public virtual async Task GetResource( - object identifier, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - // Retrieve Resource List ... - var result = await provider - .GetResource(cancellationToken); - - // - return result; - } - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateLocale( - object identifier, - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !identifier.IsNull() && - !locale.IsNullOrDefault() && - !locale.Value.IsNullOrEmpty() && - !locale.Language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - // Retrieve Resource List ... - var result = await provider - .AddOrUpdateLocale( - locale: locale, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateResource( - object identifier, - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Identified Resource Title ... - var identifiedResource = GetResourceTitle(identifier); - isValid = - !resource.IsNullOrDefault() && - (resource.Resource.IsNullOrEmpty() || - resource.Resource == identifiedResource); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - if (resource.Resource.IsNullOrEmpty()) - { - resource.Resource = identifiedResource; - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - // Retrieve Resource List ... - var result = await provider - .AddOrUpdateResource( - resource: resource, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveLocale( - object identifier, - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !identifier.IsNull() && - !language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Locale Exists ... - isValid = await HasLocale( - language: language, - identifier: identifier, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var locale = (await GetLocales( - identifier: identifier, - cancellationToken: cancellationToken - )) - .FirstOrDefault(x => - x.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)); - isValid = !locale.IsNullOrDefault(); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - var result = await provider.RemoveLocale( - locale: locale, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove all Exists Locales for Specified Identifier ... - /// - /// - /// - /// - /// - public virtual async Task RemoveLocales( - object identifier, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var resource = await GetResource( - identifier: identifier, - cancellationToken: cancellationToken - ); - isValid = !resource.IsNullOrDefault(); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - await provider.RemoveResource( - resource: resource, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - public virtual async Task HasLocale( - object identifier, - string language, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !identifier.IsNull() && - !language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - var result = await provider.HasLocale( - language: language, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Get all Exists Languages for Specified Identifier ... - /// - /// - /// - /// - public virtual async Task> GetLanguages( - object identifier, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !identifier.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Setting Resource Title ... - SetResourceTitle(identifier); - - // - var result = await provider - .GetLanguages(cancellationToken); - - // - return result; - } - #endregion - - // - #region Resource Title Action ... - /// - /// Retrieve Resource Title ... - /// - /// - /// - public string GetResourceTitle(object identifier = null) - { - // - var result = item; - - // - if (!identifier.IsNull()) - { - result = $"{item}_{identifier}"; - } - - // - return result; - } - #endregion - - // - #region Private ... - /// - /// Set Resource Title ... - /// - /// - private void SetResourceTitle(object identifier = null) - { - // - var itemIdentifier = GetResourceTitle(identifier); - provider.SetField( - field: "resource", - value: $"{itemIdentifier}" - ); - } - - /// - /// xtract all Items which Belongs to Provider ... - /// - /// - /// - private async Task> ExtractItems( - CancellationToken cancellationToken = default - ) - { - // - var result = await stringProvider - .FindManyAsync( - includeBuilder: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => - x.ResourceTitle.StartsWith( - item, - StringComparison.InvariantCultureIgnoreCase) - ); - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\XBaseOwnedItemResourceProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xCommons.Configurations; -using xStringService.Extensions; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Interfaces.Dtos; - -namespace xStringService.Providers -{ - public abstract class XBaseOwnedItemResourceProvider : IXOwnedItemResourceProvider - { - // - #region Props ... - /// - /// Item Name for Resource Providing ... - /// - private readonly string item; - - /// - /// Application Configuration ... - /// - private readonly XAppConfiguration appConfig; - - /// - /// String Provider Service ... - /// - private readonly IXStringServiceProvider stringProvider; - #endregion - - // - #region Constructor ... - protected XBaseOwnedItemResourceProvider( - string item, - XAppConfiguration appConfig, - IXStringServiceProvider stringProvider - ) - { - // - this.item = item; - this.appConfig = appConfig; - this.stringProvider = stringProvider; - } - #endregion - - // - #region Group Actions ... - /// - /// Retrieve a List of Exists Languages for Current Item ... - /// - /// - /// - /// - public virtual async Task> GetLanguages( - object owner, - CancellationToken cancellationToken = default - ) - { - // - var items = await ExtractStrings( - owner: owner, - identifier: null, - cancellationToken: cancellationToken - ); - var result = - items - .Select(x => x.Language) - .Distinct(); - - // - return result; - } - - /// - /// Retrieve all Exists Items of type ... - /// - /// - /// - /// - public virtual async Task> GetResourceLocales( - object owner, - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractStrings( - owner: owner, - identifier: null, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove all Exists Locales which Related to this Provider ... - /// - /// - /// - /// - /// - public virtual async Task RemoveResourceLocales( - object owner, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var items = await ExtractStrings( - owner: owner, - identifier: null, - cancellationToken: cancellationToken - ); - - // - foreach (var item in items) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - // Try to Remove it ... - try - { - // - await stringProvider.RemoveAsync( - id: item.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - } - #endregion - - // - #region Item Actions ... - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - /// - public virtual async Task> GetResourceLocales( - object owner, - object identifier, - CancellationToken cancellationToken = default - ) - { - // - var resourceTitle = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var result = await stringProvider.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.ResourceTitle - .ToNormalString() - .Contains(resourceTitle.ToNormalString()) - ); - - // - return result; - } - - /// - /// Get all Exists Items for Specified identitifer ... - /// - /// - /// - /// - /// - public virtual async Task> GetLocales( - object owner, - object identifier, - CancellationToken cancellationToken = default - ) - { - // - var result = (await GetResourceLocales( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - )) - .Select(x => x.ToXLocaleResourceDto()); - - // - return result; - } - - /// - /// Get all Exists Locales Representaion based on Specified Identitifer - /// as XResourceDto ... - /// - /// - /// - /// - /// - public virtual async Task GetResource( - object owner, - object identifier, - CancellationToken cancellationToken = default - ) - { - // - var resource = GetResourceTitle( - owner: owner, - identifier: identifier - ); - var locales = await GetLocales( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - - // - var result = new XResourceDto - { - Locales = locales, - Resource = resource - }; - - // - return result; - } - - /// - /// Add Or Update Locale for Specified Identitifer ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateLocale( - object owner, - object identifier, - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var resource = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var resourceDto = await stringProvider.AddOrUpdateByLocaleResource( - item: locale, - resource: resource, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - // Retrieve XResourceDto ... - var result = await GetResource( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update a Resource State ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateResource( - object owner, - object identifier, - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var resourceTitle = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var isValid = - !resource.IsNullOrDefault() && - resource.Resource == resourceTitle; - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Resource ... - var result = await GetResource( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - isValid = - !result.IsNullOrDefault() && - result.Locales.HasChild(); - if (isValid) - { - await RemoveLocales( - owner: owner, - identifier: identifier, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - foreach (var locale in resource.Locales) - { - // - var item = new XStringDto - { - Language = locale.Language, - ResourceTitle = resourceTitle, - TranslatedValue = locale.Value, - }; - - // - await stringProvider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - result = await GetResource( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Specified Language Locale of Specified Identifier ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveLocale( - object owner, - object identifier, - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - XResourceDto result = null; - language = NormalizedLanguage(language); - - // - // Check Locale Exists ... - var isValid = await HasLocale( - owner: owner, - language: language, - identifier: identifier, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var resourceTitle = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var item = await stringProvider.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => - x.Language.Equals( - language, - StringComparison.InvariantCultureIgnoreCase) && - x.ResourceTitle.Equals( - resourceTitle, - StringComparison.InvariantCultureIgnoreCase) - ); - isValid = !item.IsNullOrDefault(); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Remove XStringDto ... - await stringProvider.RemoveAsync( - id: item.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - try - { - // - result = await GetResource( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - } - catch { } - - // - return result; - } - - /// - /// Remove all Exists Locales for Specified Identifier ... - /// - /// - /// - /// - /// - /// - public virtual async Task RemoveLocales( - object owner, - object identifier, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var resourceTitle = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var items = await stringProvider.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle.Equals( - resourceTitle, - StringComparison.InvariantCultureIgnoreCase) - ); - var isValid = !item.IsNull(); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - await stringProvider.RemoveResource( - resource: resourceTitle, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - /// - /// Check Specified ocale Exists for Specified Identifier ... - /// - /// - /// - /// - /// - /// - public virtual async Task HasLocale( - object owner, - object identifier, - string language, - CancellationToken cancellationToken = default - ) - { - // - language = NormalizedLanguage(language); - var locales = await GetLocales( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - var result = - language.HasChild() && - locales.Any(l => l.Language.Equals( - language, - StringComparison.InvariantCultureIgnoreCase) - ); - - // - return result; - } - - /// - /// Get all Exists Languages for Specified Identifier ... - /// - /// - /// - /// - /// - public virtual async Task> GetLanguages( - object owner, - object identifier = null, - CancellationToken cancellationToken = default - ) - { - // - var items = await ExtractStrings( - owner: owner, - identifier: identifier, - cancellationToken: cancellationToken - ); - var result = - items - .Select(x => x.Language) - .Distinct(); - - // - return result; - } - #endregion - - // - #region Resource Title Action ... - /// - /// Retrieve Resource Title ... - /// - /// - /// - /// - public virtual string GetResourceTitle( - object owner = null, - object identifier = null - ) - { - // - var result = item; - - // - // Normalization ... - var ownerStr = - !owner.IsNull() - ? $"{owner}" - : string.Empty; - var identifierStr = - !identifier.IsNull() - ? $"{identifier}" - : string.Empty; - - // - // Handle Owner Attach ... - if (!ownerStr.IsNullOrEmpty()) - { - result = $"{result}_{ownerStr}"; - } - - // - // Handle Identifier Attach ... - if (!identifierStr.IsNullOrEmpty()) - { - result = $"{result}_{identifierStr}"; - } - - // - return result; - } - #endregion - - // - #region Private ... - private string NormalizedLanguage( - string language = null - ) - { - // - var result = language; - if (result.IsNullOrEmpty()) - { - result = GetDefaultLanguage(); - } - - // - return result; - } - - private string GetDefaultLanguage() - { - // - var result = appConfig.DefaultLanguage; - - // - return result; - } - - private async Task> ExtractStrings( - string resourceTitle, - CancellationToken cancellationToken = default - ) - { - // - IEnumerable result = []; - - // - if (resourceTitle.IsNullOrEmpty()) - { - return result; - } - - // - result = await stringProvider.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => x.ResourceTitle - .ToNormalString() - .Contains(resourceTitle.ToNormalString()) - ); - - // - return result; - } - - private async Task> ExtractStrings( - object owner, - object identifier, - CancellationToken cancellationToken = default - ) - { - // - var resourceTitle = GetResourceTitle( - owner: owner, - identifier: identifier - ); - - // - var result = await ExtractStrings( - resourceTitle: resourceTitle, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\XBaseResourceProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xStringService.Extensions; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Interfaces.Dtos; - -namespace xStringService.Providers -{ - public class XBaseResourceProvider : IXResourceProvider - { - protected string resource; - private readonly IXStringServiceProvider provider; - - public XBaseResourceProvider( - string resource, - IXStringServiceProvider provider - ) - { - this.resource = resource; - this.provider = provider; - } - - // - #region Actions ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - public virtual async Task> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - var result = (await ExtractItems(cancellationToken)) - .Select(x => x.Language) - .Distinct() - .ToList(); - - // - return result; - } - - /// - /// Retrieve all Exists Items ... - /// - /// - /// - public virtual async Task> GetResourceLocales( - CancellationToken cancellationToken = default - ) - { - // - var result = await ExtractItems(cancellationToken); - - // - return result; - } - - /// - /// Extract Translation of in Specified Language ... - /// - /// Specified Language ... - /// - /// - public virtual async Task GetResourceTranslation( - string language, - CancellationToken cancellationToken = default - ) - { - // - var item = (await ExtractItems(cancellationToken)) - .FirstOrDefault(x => x.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)); - - // - var result = item?.TranslatedValue ?? string.Empty; - - // - return result; - } - - /// - /// Check Has Specified Translation or not ... - /// - /// Specified Language ... - /// - /// - public virtual async Task HasLocale( - string language, - CancellationToken cancellationToken = default - ) - { - // - var item = (await ExtractItems(cancellationToken)) - .FirstOrDefault(x => x.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)); - - // - var result = !item.IsNullOrDefault(); - - // - return result; - } - - /// - /// Retrieve as Locale Model ... - /// - /// Specified Language ... - /// - /// - public virtual async Task GetLocale( - string language, - CancellationToken cancellationToken = default - ) - { - // - var item = (await ExtractItems(cancellationToken)) - .FirstOrDefault(x => x.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)); - - // - var result = - !item.IsNullOrDefault() - ? item.ToXLocaleResourceDto() - : null; - - // - return result; - } - - /// - /// Retrieve all Exists Locale Models ... - /// - /// - /// - public virtual async Task> GetLocales( - CancellationToken cancellationToken = default - ) - { - // - var result = (await ExtractItems(cancellationToken)) - .Select(x => x.ToXLocaleResourceDto()) - .ToList(); - - // - return result; - } - - /// - /// Retrieve as XResourceDto ... - /// - /// - /// - public virtual async Task GetResource( - CancellationToken cancellationToken = default - ) - { - // - var locales = await GetLocales(); - - // - var result = new XResourceDto - { - Locales = locales, - Resource = resource, - }; - - // - return result; - } - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - /// - public virtual async Task AddOrUpdateResource( - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var isValid = - !resource.IsNullOrDefault() && - resource.Resource == this.resource; - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Exists Resource ... - var result = await GetResource(cancellationToken); - isValid = !result.IsNullOrDefault() && result.Locales.HasChild(); - if (isValid) - { - await RemoveResource( - resource: result, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - foreach (var locale in resource.Locales) - { - // - var item = new XStringDto - { - Language = locale.Language, - ResourceTitle = this.resource, - TranslatedValue = locale.Value, - }; - - // - await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - result = await GetResource(cancellationToken); - return result; - } - - /// - /// Add Or Update Locale ... - /// - /// - /// - /// - /// - public virtual async Task AddOrUpdateLocale( - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var item = (await ExtractItems(cancellationToken)) - .FirstOrDefault(x => - x.ResourceTitle == resource && - x.Language == locale.Language); - var isExists = !item.IsNullOrDefault(); - if (isExists) - { - item.TranslatedValue = locale.Value; - item = await provider.UpdateAsync( - item: item, - id: item.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - item = new XStringDto - { - ResourceTitle = resource, - Language = locale.Language, - TranslatedValue = locale.Value - }; - item = await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - var result = await GetResource(cancellationToken); - - // - return result; - } - - /// - /// Remove Locale ... - /// - /// - /// - /// - /// - public virtual async Task RemoveLocale( - XLocaleResourceDto locale, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var item = (await ExtractItems(cancellationToken)) - .FirstOrDefault(x => - x.ResourceTitle == resource && - x.Language == locale.Language); - var isExists = !item.IsNullOrDefault(); - if (isExists) - { - await provider.RemoveAsync( - id: item.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - var result = await GetResource(cancellationToken); - - // - return result; - } - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// - /// - /// - public virtual async Task RemoveResource( - XResourceDto resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate Resource ... - var isValid = - !resource.IsNullOrDefault() && - !resource.Resource.IsNullOrEmpty() && - resource.Resource == this.resource; - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var items = await ExtractItems(cancellationToken); - - // - foreach (var item in items) - { - // - await provider.RemoveAsync( - id: item.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - #endregion - - // - #region Private ... - private async Task> ExtractItems( - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - orderBuilder: x => x - .OrderBy(y => y.Language) - .ThenBy(y => y.ResourceTitle), - cancellationToken: cancellationToken, - predicate: x => - x.ResourceTitle.Equals(resource, StringComparison.InvariantCultureIgnoreCase) - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\XStringEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xStringService.Models.Entities; -using xStringService.Configurations.Entities; - -namespace xStringService.Providers -{ - /// - /// an Entity Registerar class for XStringService ... - /// - public class XStringEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XStringEntityRegisterar() - : base(nameof(XStringEntityRegisterar)) - { - // - // Add XString Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XStringEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\XStringProvider.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xPushService.Providers; -using xStringService.Extensions; -using xStringService.Interfaces; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Providers.Dtos; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Providers -{ - public class XStringProvider : XBaseProvided, IXStringProvider - { - public XStringProvider( - IXStringServiceProvider provider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { } - - public override bool IsOwned( - XStringDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XString item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - // - #region Tools ... - /// - /// Retrieve a List of Exists Languages ... - /// - /// - /// - public async Task> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - var result = (await GetAll( - includeBuilder: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Language) - )) - .Select(x => x.Language) - .Distinct() - .ToList(); - - // - return result; - } - - /// - /// Retrieve a List of Resource Titles ... - /// - /// if provided, returns all language Specified resource titles, if not, all Resource Titles - /// - /// - public async Task> GetResourceTitles( - string language = null, - CancellationToken cancellationToken = default - ) - { - // - var result = (await FindMany( - includeBuilder: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.ResourceTitle), - predicate: x => - string.IsNullOrWhiteSpace(language) || - x.Language.Equals(language, System.StringComparison.InvariantCultureIgnoreCase) - )) - .Select(x => x.ResourceTitle) - .Distinct() - .ToList(); - - // - return result; - } - - /// - /// Retrieve all Exists Items which belongs to Specified Resource Title ... - /// - /// Specified Resource Title - /// - /// - public async Task> GetResourceLocales( - string resource, - CancellationToken cancellationToken = default - ) - { - // - var result = await FindMany( - includeBuilder: null, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Language), - predicate: x => - !string.IsNullOrWhiteSpace(resource) && - resource.Equals(x.ResourceTitle, System.StringComparison.InvariantCultureIgnoreCase) - ); - - // - return result; - } - - /// - /// Extract Translation of a Resource in Specified Language ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - public async Task GetResourceTranslation( - string language, - string resource, - CancellationToken cancellationToken = default - ) - { - // - var result = (await FindOne( - includeBuilder: null, - cancellationToken: cancellationToken, - predicate: x => - !string.IsNullOrWhiteSpace(language) && - !string.IsNullOrWhiteSpace(resource) && - x.Language.Equals(language, System.StringComparison.InvariantCultureIgnoreCase) && - x.ResourceTitle.Equals(resource, System.StringComparison.InvariantCultureIgnoreCase) - ))? - .TranslatedValue ?? ""; - - // - return result; - } - - /// - /// Retrieve a Resource as Locale Model ... - /// - /// Specified Language ... - /// Specified Resource Title ... - /// - /// - public async Task GetLocale( - string language, - string resource, - CancellationToken cancellationToken = default - ) - { - // - var result = (await FindOne( - includeBuilder: null, - cancellationToken: cancellationToken, - predicate: x => - !string.IsNullOrWhiteSpace(language) && - !string.IsNullOrWhiteSpace(resource) && - x.Language.Equals(language, System.StringComparison.InvariantCultureIgnoreCase) && - x.ResourceTitle.Equals(resource, System.StringComparison.InvariantCultureIgnoreCase) - ))? - .ToXLocaleResourceDto() ?? null; - - // - return result; - } - - /// - /// Retrieve all Exists Resource Instances as Locale Models ... - /// - /// - /// - /// - public async Task> GetLocales( - string resource, - CancellationToken cancellationToken = default - ) - { - // - var result = (await GetResourceLocales( - resource: resource, - cancellationToken: cancellationToken - )) - .ToList() - .Select(x => x.ToXLocaleResourceDto()) - .ToList(); - - // - return result; - } - - /// - /// Retrieve all Locales of Specified Resource and Represent as XResourceDto ... - /// - /// - /// - /// - public async Task GetResource( - string resource, - CancellationToken cancellationToken = default - ) - { - // - XResourceDto result = null; - - // - // Validate Resource ... - if (resource.IsNullOrEmpty()) - { - return result; - } - - // - // Extract Locales of Resource ... - var locales = await GetLocales( - resource: resource, - cancellationToken: cancellationToken - ); - - // - // Prepare Result ... - result = new XResourceDto - { - Locales = locales, - Resource = resource, - }; - - // - return result; - } - - /// - /// Add or Update a Resource Model ... - /// - /// a XResourceDto Model ... - /// Actor User for Permissions ... - /// - /// - /// - public async Task AddOrUpdateResource( - XResourceDto resource, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - XResourceDto result = null; - - // - // Validate Args ... - var isValid = - !resource.IsNullOrDefault() && - !resource.Resource.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Permissions ... - isValid = - userInfo.IsNullOrDefault() || - HasPermision(userInfo); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - // Remove all Resources if Exists ... - result = await GetResource( - resource: resource.Resource, - cancellationToken: cancellationToken - ); - var isExists = !result.IsNullOrDefault(); - if (isExists) - { - // - await RemoveResource( - resource: result, - userInfo: userInfo, - cancellationToken: cancellationToken - ); - } - - // - // Loop through all Exists Locales and Add them ... - foreach (var locale in resource.Locales) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - var item = new XStringDto - { - Language = locale.Language, - TranslatedValue = locale.Value, - ResourceTitle = resource.Resource, - }; - await Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - // Reload Result after Updates ... - result = await GetResource( - resource: resource.Resource, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Specified Resource Model ... - /// - /// a XResourceDto Model ... - /// Actor User for Permissions ... - /// - /// - /// - public async Task RemoveResource( - XResourceDto resource, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !resource.IsNullOrDefault(); - if (!isValid) - { - return; - } - - // - var items = await GetResourceLocales( - resource: resource.Resource, - cancellationToken: cancellationToken - ); - isValid = - !items.IsNullOrDefault() && - items.HasChild(); - if (!isValid) - { - return; - } - - // - foreach (var item in items) - { - // - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await Remove( - id: item.Id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Dtos\XStringDtoHub.cs - -using xPushService.Base; -using xStringService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Providers.Dtos -{ - public class XStringDtoHub : XBaseDtoHub, IXStringDtoHub - { - public XStringDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Dtos\XStringRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xStringService.Models.Dtos; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Dtos -{ - public class XStringRepositoryService : XBaseRepositoryService, IXStringRepositoryService - { - public XStringRepositoryService( - IXStringRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Dtos\XStringServiceProvider.cs - -using System; -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xPushService.Constants; -using System.Linq.Expressions; -using xCommons.Configurations; -using xStringService.Extensions; -using System.Collections.Generic; -using xDataService.Configuration; -using xStringService.Models.Dtos; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xStringService.Interfaces.Dtos; -using xStringService.Models.Entities; - -namespace xStringService.Providers.Dtos -{ - public class XStringServiceProvider : XBaseDtoProvider, IXStringServiceProvider - { - public XAppConfiguration AppConfiguration { get; } - - public XStringServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXStringRepositoryService service, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { - AppConfiguration = appConfiguration; - } - - // - #region Retrievers ... - /// - /// Retrieve all Exists Languages ... - /// - /// - /// - public async Task> GetLanguages( - CancellationToken cancellationToken = default - ) - { - // - var result = (await Service.GetAllAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Language) - )) - .AsQueryable() - .Select(e => e.Language) - .Distinct() - .ToList(); - - // - // Check Configuration Default Language Exists ... - var hasDefaultLanguage = !AppConfiguration.DefaultLanguage.IsNullOrEmpty(); - if (hasDefaultLanguage) - { - // - // Find Default Language on Result ... - hasDefaultLanguage = result.Any(e => e.ToNormalString() == AppConfiguration.DefaultLanguage.ToNormalString()); - if (!hasDefaultLanguage) - { - result.Add(AppConfiguration.DefaultLanguage); - } - } - - // - result = result - .Distinct() - .ToList(); - - // - return result; - } - - /// - /// Check Specified Resource Exists or not ... - /// - /// - /// - /// - /// - public async Task IsResourceExists( - string resource, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !resource.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - XStringDto dto = null; - if (language.IsNullOrEmpty()) - { - // - dto = await Service - .FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: e => e.ResourceTitle == resource - ); - } - else - { - // - dto = await Service - .FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: - e => e.ResourceTitle == resource && - e.Language.ToNormalString() == language.ToNormalString() - ); - } - - // - result = !dto.IsNullOrDefault(); - - // - return result; - } - - /// - /// Retrieve Specified Resource ... - /// - /// - /// - /// - /// - public async Task Get( - string resource, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Validate ... - if (resource.IsNullOrEmpty() || language.IsNullOrEmpty()) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Resource Exists ... - var isExists = await IsResourceExists( - resource: resource, - language: language - ); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - var result = await Service - .FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: e => - e.ResourceTitle == resource && - e.Language.ToNormalString() == language.ToNormalString() - ); - if (result.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - - /// - /// Retrieve Specified Translation of Specified Resource ... - /// - /// - /// - /// - /// - public async Task GetResourceValue( - string resource, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - var result = ""; - - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Validate ... - var isValid = - !resource.IsNullOrEmpty() && - !language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Langauage Exists ... - var languages = await GetLanguages(cancellationToken); - isValid = languages.Any(l => l.ToNormalString() == language.ToNormalString()); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Check Resource Exists ... - isValid = await IsResourceExists( - resource: resource, - language: language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var dto = await Service.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: e => - e.ResourceTitle == resource && - e.Language.ToNormalString() == language.ToNormalString() - ); - isValid = !dto.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - result = dto.TranslatedValue; - - // - return result; - } - - /// - /// Retrieve an Specified Resource Items ... - /// - /// - /// - /// - public async Task> GetResources( - string resource, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = await IsResourceExists(resource); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = await Service - .FindManyAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: e => - e.ResourceTitle == resource, - orderBuilder: x => - x.OrderBy(y => y.ResourceTitle), - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Retrieve Specified Resource Items as XResourceDto Presentation ... - /// - /// - /// - /// - public async Task GetResource( - string resource, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isExists = await IsResourceExists( - language: null, - resource: resource, - cancellationToken: cancellationToken - ); - if (!isExists) - { - XException.NotFound.Throw(); - } - - // - // Retrieve String Dto (s) ... - var resources = await GetResources( - resource: resource, - cancellationToken: cancellationToken - ); - if (!resource.HasChild()) - { - XException.NotFound.Throw(); - } - - // - var result = new XResourceDto - { - Resource = resource, - Locales = resources.ToXLocaleResourceDtos() - }; - - // - return result; - } - #endregion - - // - #region Query ... - /// - /// Query Resource IDs ... - /// - /// - /// - /// - public async Task> QueryResourceIds( - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - var dtoResult = await Service.QueryAsync( - query: query, - predicate: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - orderBuilder: x => - x.OrderBy(y => y.ResourceTitle), - cancellationToken: cancellationToken - ); - - // - var result = new XQueryResult() - .UpdateData( - updateWith: dtoResult, - propertyBlackList: new List - { - nameof(XQueryResult.Items) - }); - - // - result.Items = dtoResult.Items.ToList().Select(dto => dto.ResourceTitle); - - // - return result; - } - - /// - /// Query Specified Language Resources ... - /// - /// - /// - /// - /// - public async Task> QueryLanguageResources( - XQuery query, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await Service.QueryAsync( - query: query, - includeBuilder: null, - ignoreSoftDeleteds: true, - orderBuilder: x => x - .OrderBy(y => y.Language) - .ThenBy(y => y.ResourceTitle), - cancellationToken: cancellationToken, - predicate: x => - x.Language.ToNormalString() == language.ToNormalString() - ); - - // - return result; - } - - /// - /// Query Locale Resources ... - /// - /// - /// - /// - /// - public async Task> QueryLocaleResources( - XQuery query, - string language = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicate = null; - if (!language.IsNullOrEmpty()) - { - // - predicate = x => - x.Language.ToNormalString() == language.ToNormalString(); - } - - // - var dtoResult = await Service.QueryAsync( - query: query, - includeBuilder: null, - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: x => x - .OrderBy(y => y.Language) - .ThenBy(y => y.ResourceTitle), - cancellationToken: cancellationToken - ); - - // - var result = new XQueryResult() - .UpdateData( - updateWith: dtoResult, - propertyBlackList: new List - { - nameof(XQueryResult.Items) - }); - - // - result.Items = dtoResult.Items.ToList().ToXLocaleResourceDtos(); - - // - return result; - } - #endregion - - // - #region Add/Update Actions ... - /// - /// Add Specified Resource ... - /// - /// - /// - /// - /// - /// - /// - public async Task Add( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - bool result = false; - - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Validate ... - result = - !value.IsNullOrEmpty() && - !resource.IsNullOrEmpty() && - !language.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - // Check Exists ... - bool isExists = await IsResourceExists( - resource: resource, - language: language, - cancellationToken: cancellationToken - ); - result = !isExists; - if (!result) - { - XException.Duplicate.Throw(); - } - - // - // Prepare Entity to Add ... - XStringDto item = new XStringDto - { - Language = language, - TranslatedValue = value, - ResourceTitle = resource, - }; - item = await AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !item.IsNullOrDefault(); - - // - return result; - } - - /// - /// Update Resource ... - /// - /// - /// - /// - /// - /// - /// - public async Task Update( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - bool result = false; - - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Validate ... - result = - !value.IsNullOrEmpty() && - !language.IsNullOrEmpty() && - !resource.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - // Check Value Must Exists ... - result = await IsResourceExists( - resource: resource, - language: language, - cancellationToken: cancellationToken - ); - if (!result) - { - XException.NotFound.Throw(); - } - - // - var item = await Get( - language: language, - resource: resource, - cancellationToken: cancellationToken - ); - item.TranslatedValue = value; - item = await UpdateAsync( - item: item, - id: item.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !item.IsNullOrDefault(); - - // - return result; - } - - /// - /// Add Or Update Resource ... - /// - /// - /// - /// - /// - /// - /// - public async Task AddOrUpdate( - string resource, - string value, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Check Existsance ... - bool isExists = await IsResourceExists( - resource: resource, - language: language - ); - - // - // Act Based on Existance ... - if (isExists) - { - // - result = await Update( - value: value, - resource: resource, - language: language, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - result = await Add( - value: value, - resource: resource, - language: language, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - /// - /// Add Specified Locale Resource ... - /// - /// - /// - /// - /// - /// - public async Task AddByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !item.IsNull() && - !resource.IsNullOrEmpty() && - !item.Value.IsNullOrEmpty() && - !item.Language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Specified Resource / Language Exists ... - isValid = await IsResourceExists( - resource: resource, - language: item.Language, - cancellationToken: cancellationToken - ); - if (isValid) - { - XException.Duplicate.Throw(); - } - - // - // Prepare Item to Add ... - var result = new XStringDto - { - Language = item.Language, - ResourceTitle = resource, - TranslatedValue = item.Value - }; - result = await AddAsync( - item: result, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update Specified Locale Resource ... - /// - /// - /// - /// - /// - /// - public async Task UpdateByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !item.IsNull() && - !resource.IsNullOrEmpty() && - !item.Value.IsNullOrEmpty() && - !item.Language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Specified Resource / Language Exists ... - isValid = await IsResourceExists( - resource: resource, - language: item.Language, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = await Get( - resource: resource, - language: item.Language, - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - // Update ... - result.TranslatedValue = item.Value; - result = await UpdateAsync( - item: result, - id: result.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - isValid = !result.IsNullOrDefault(); - if (!isValid) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - - /// - /// Add Or Update Resource By Locale ... - /// - /// - /// - /// - /// - /// - public async Task AddOrUpdateByLocaleResource( - XLocaleResourceDto item, - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !item.IsNull() && - !resource.IsNullOrEmpty() && - !item.Value.IsNullOrEmpty() && - !item.Language.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Specified Resource / Language Exists ... - isValid = await IsResourceExists( - resource: resource, - language: item.Language, - cancellationToken: cancellationToken - ); - - // - XStringDto result = null; - if (!isValid) - { - // - result = await AddByLocaleResource( - item: item, - resource: resource, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - result = await UpdateByLocaleResource( - item: item, - resource: resource, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - if (result.IsNullOrDefault()) - { - XException.ActionFailed.Throw(); - } - - // - return result; - } - - /// - /// Add Or Update all XResourceDto(s) Locales ... - /// - /// - /// - /// - /// - public async Task> AddByResource( - XResourceDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = - !item.IsNull() && - item.Locales.HasChild() && - !item.Resource.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Task - .WhenAll(item.Locales - .Select(async e => await AddOrUpdateByLocaleResource( - item: e, - resource: item.Resource, - connectionId: connectionId, - cancellationToken: cancellationToken))); - - // - return result; - } - #endregion - - // - #region Remove Actions ... - /// - /// Remove all Specified Language's Resources ... - /// - /// - /// - /// - /// - public async Task RemoveLanguageResources( - string language, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = !language.IsNullOrEmpty(); - if (!isValid) - { - return; - } - - // - var dtos = await Service - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: e => - e.Language.ToNormalString() == language.ToNormalString()); - - // - try - { - // - await Service.RemoveRangeAsync( - items: dtos, - softDelete: false, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - var ids = dtos.Select(e => e.Id); - await SendPush( - connectionId: connectionId, - payLoad: ids.ToJSON(camelCase: true), - cancellationToken: cancellationToken, - action: XBaseEntityHubAction.DeleteMany.GetStringValue() - ); - } - catch (Exception ex) - { - throw ex; - } - } - - /// - /// Remove all Specified Resource Ids instances ... - /// - /// - /// - /// - /// - public async Task> RemoveResource( - string resource, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - bool isValid = !resource.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await Service - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: e => - e.ResourceTitle.ToNormalString() == resource.ToNormalString()); - - // - try - { - // - await Service.RemoveRangeAsync( - items: result, - softDelete: false, - saveChanges: true, - cancellationToken: cancellationToken - ); - - // - var ids = result.Select(e => e.Id); - await SendPush( - connectionId: connectionId, - payLoad: ids.ToJSON(camelCase: true), - cancellationToken: cancellationToken, - action: XBaseEntityHubAction.DeleteMany.GetStringValue() - ); - } - catch (Exception ex) - { - throw ex; - } - - // - return result; - } - - /// - /// Remove Specified Resource ... - /// - /// - /// - /// - /// - /// - public async Task Remove( - string resource, - string language = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - bool result = false; - - // - // Normalize ... - if (language.IsNullOrEmpty()) - { - language = AppConfiguration.DefaultLanguage; - } - - // - // Validate ... - result = - !language.IsNullOrEmpty() && - !resource.IsNullOrEmpty(); - if (!result) - { - return result; - } - - // - // Check Resource Exists ... - result = await IsResourceExists( - language: language, - resource: resource, - cancellationToken: cancellationToken - ); - if (!result) - { - return result; - } - - // - var dto = await Get( - language: language, - resource: resource, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - if (!result) - { - return result; - } - - // - dto = await RemoveAsync( - id: dto.Id, - softDelete: false, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - - // - return result; - } - - /// - /// Remove all Resource of Specified XResourceDto ... - /// - /// - /// - /// - /// - public async Task RemoveByResource( - XResourceDto item, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - bool isValid = - !item.IsNullOrDefault() && - item.Locales.HasChild() && - !item.Resource.IsNullOrEmpty(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - foreach (var locale in item.Locales) - { - // - await Remove( - resource: item.Resource, - language: locale.Language, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringEFRepository : XBaseEFRepository, IXStringRepository - where TContext : XDbContext - { - public XStringEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXStringKeyGenerator keyGenerator = null, - IXStringRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringEntityHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringEntityHub : XBaseEntityHub, IXStringEntityHub - { - public XStringEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringInMemoryRepository : XBaseInMemoryRepository, IXStringRepository - { - public XStringInMemoryRepository( - XDataServiceConfiguration configuration, - IXStringKeyGenerator keyGenerator = null, - IXStringRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringKeyGenerator.cs - -using xDataService.Providers; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringKeyGenerator : XIntKeyGenerator, IXStringKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringMongoRepository : XBaseMongoRepository, IXStringRepository - { - public XStringMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXStringKeyGenerator keyGenerator = null, - IXStringRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringRepositoryEvents.cs - -using xDataService.Providers; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringRepositoryEvents : XBaseRepositoryEvents, IXStringRepositoryEvents - {} -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public class XStringRepositoryProvider : XBaseEntityProvider, IXStringRepositoryProvider - { - public XStringRepositoryProvider( - IHubContext hub, - IXStringRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\Entities\XStringSeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.Entities -{ - public abstract class XStringSeederBase : XBaseDbSeeder, IXStringSeeder - { - protected XStringSeederBase( - string entity, - string database, - IXStringRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\GraphQL\XStringGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xStringService.Constants; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xStringService.Providers.GraphQL -{ - public class XStringGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXStringGraphQLTypeHelper - { - public XStringGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XStringServiceConstants.XStringCollectionName; - } - - public override string GetInQuerySingleName() - { - return XStringServiceConstants.XStringSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\GraphQL\XStringGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xStringService.Models.Entities; -using xStringService.Interfaces.Entities; - -namespace xDataHelper.Providers.GraphQL -{ - public class XStringGraphQuery : XBaseGraphQLQuery - { - public XStringGraphQuery( - XDataServiceConfiguration configuration, - IXStringRepository repository, - IXStringGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\GraphQL\XStringGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xDataHelper.Providers.GraphQL -{ - public class XStringGraphSchema : Schema - { - public XStringGraphSchema(IServiceProvider services) : base(services) - { - Query = (XStringGraphQuery)services.GetService(typeof(XStringGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xStringService\Providers\GraphQL\XStringGraphType.cs - -using xDataService.GraphQL; -using xStringService.Models.Entities; - -namespace xDataHelper.Providers.GraphQL -{ - public class XStringGraphType : XBaseGraphObjectType - { - public XStringGraphType() : base() - { - Field(x => x.Language); - Field(x => x.ResourceTitle); - Field(x => x.TranslatedValue); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xTagService-20261109_152620.txt b/Documents/GeneratedContext/xDashboard-xTagService-20261109_152620.txt deleted file mode 100644 index 0725c8e..0000000 --- a/Documents/GeneratedContext/xDashboard-xTagService-20261109_152620.txt +++ /dev/null @@ -1,5044 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Configurations\Entities\XTagEntityConfiguration.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xTagService.Configurations.Entities -{ - public class XTagEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable("Tags"); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Constants\XTagServiceConstants.cs - -namespace xTagService.Constants -{ - public struct XTagServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XTagServiceDILogTag = "XTagService"; - - // - // Table Mapping Identifiers ... - public const string XTagTable = "Tags"; - - // - // GraphQL Collection Mappings ... - public const string XTagSingleName = "tag"; - public const string XTagCollectionName = "tags"; - - // - // Hubs ... - public const string XTagDtoHub = "tagDto"; - public const string XTagEntityHub = "tagEntity"; - - // - // Custome Constants ... - - // - // EF Repositories Helper Extensions ... - public const string GetXTagEFRepositoryDescriptor = "GetXTagEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XBaseProvidedHasTagControllerBase.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Interfaces; -using xCommons.Configurations; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - [AllowAnonymous] - public abstract class XBaseProvidedHasTagControllerBase : XBaseIdentityApiV1Controller, IXBaseProvidedHasTagController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly IXBaseProvided provider; - private readonly IXTagProvided tagProvided; - private readonly Func, IOrderedQueryable> defaultOrderBuilder; - private readonly Func, IIncludableQueryable> defaultIncludeBuilder; - - protected XBaseProvidedHasTagControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXBaseProvided provider, - IXTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.provider = provider; - this.tagProvided = tagProvided; - this.defaultOrderBuilder = defaultOrderBuilder; - this.defaultIncludeBuilder = defaultIncludeBuilder; - } - - // - #region Provided ... - // - #region Retrieve ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(id); - - // - var result = await provider.Get( - id: id, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - [HttpGet("")] - public virtual async Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetAll( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - [HttpGet("Find/One")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindOne( - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find a collection of Items by proving a Query Search ... - /// - /// - /// - /// - /// - /// - [HttpGet("Find/Many")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindMany( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var result = await provider.Query( - query: query, - predicate: null, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Owned Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query/Owned")] - public virtual async Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryOwned( - query: query, - predicate: null, - userInfo: userInfo, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Add/Update/Remove ... - /// - /// Add an item ... - /// - /// - /// - /// - [HttpPost("")] - public virtual async Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove an Item ... - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - - // - #region Tag ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - public virtual async Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - public virtual async Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .DetachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - public virtual async Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tags) - .AddNotZeroChilds(tags.Items) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - public virtual async Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - if (!tags.IsNull()) - { - // - await tagProvided - .DetachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - await tagProvided - .DetachTags( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - public virtual async Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await tagProvided.GetTags( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagProvidedControllerBase.cs - -using System; -using xModels.Base; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Interfaces; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; - -namespace xTagService.Controllers -{ - public abstract class XTagProvidedControllerBase : XBaseIdentityApiV1Controller, IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly IXTagProvided tagProvided; - - protected XTagProvidedControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXIdentityProvider identityProvider, - IXTagProvided tagProvided - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.tagProvided = tagProvided; - } - - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - public virtual async Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - public virtual async Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .DetachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - public virtual async Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tags) - .AddNotZeroChilds(tags.Items) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - public virtual async Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - if (!tags.IsNull()) - { - // - await tagProvided - .DetachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - await tagProvided - .DetachTags( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - public virtual async Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await tagProvided.GetTags( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xTagService.Interfaces; -using xCommons.Configurations; -using xTagService.Models.Dtos; -using xPushService.Controllers; -using xTagService.Providers.Dtos; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagProviderControllerBase : XBaseProvidedController, IXTagProviderController - { - protected XTagProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XTagRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXTagRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XTagRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xTagService.Models.Dtos; -using xDataService.Controllers; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XTagServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXTagRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xPushService.Controllers; -using xTagService.Providers.Dtos; -using xIdentityService.Interfaces; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XTagServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xTagService.Helpers; -using xPushService.Helpers; -using xExceptions.Constants; -using xTagService.Constants; -using xTagService.Providers; -using xDataService.Constants; -using xTagService.Interfaces; -using xTagService.Providers.Dtos; -using xTagService.Interfaces.Dtos; -using Microsoft.AspNetCore.Builder; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xTagService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXTagService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddTagService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXTagService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddTagService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XTagService Middleware ... - /// - /// - /// - public static void UseXTagService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XTag Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XTagServiceConstants.XTagDtoHub); - pushHelper.AddHub(XTagServiceConstants.XTagEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XTag Repository Descriptor ... - if (!descriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XTagServiceConstants.XTagServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddTagService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - descriptor = typeof(XTagServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XTagServiceConstants.GetXTagEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - descriptor = XTagServiceHelper.GetXTagMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - descriptor = XTagServiceHelper.GetXTagInMemoryRepositoryDescriptor(); - break; - } - - // - // Register XTag Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: descriptor - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXTagServiceProvider), typeof(XTagServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXTagRepositoryService), typeof(XTagRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXTagRepositoryProvider), typeof(XTagRepositoryProvider), lifeTime) - ); - - // - services.Add( - new ServiceDescriptor(typeof(IXTagProvider), typeof(XTagProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Extensions\XModelExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Extensions; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Models.Entities; - -namespace xTagService.Extensions -{ - public static class XModelExtensions - { - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XTag source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XTagDto source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XTag UpdateReferences( - this XTag source, - IList> references, - bool forceClean = true - ) - { - // - XTag result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XTagDto UpdateReferences( - this XTagDto source, - IList> references, - bool forceClean = true - ) - { - // - XTagDto result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Helpers\XTagServiceHelper.cs - -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Providers.GraphQL; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Helpers -{ - public static class XTagServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext - > GetXTagEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext, - IXTagSeeder, - TSeederImplementation - > GetXTagEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository - > GetXTagMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository, - IXTagSeeder, - TSeederImplementation - > GetXTagMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository - > GetXTagInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository, - IXTagSeeder, - TSeederImplementation - > GetXTagInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseProvidedHasTag.cs - -using xModels.Base; -using xPushService.Base; -using xPushService.Interfaces; - -namespace xTagService.Interfaces -{ - public interface IXBaseProvidedHasTag : IXBaseProvided, IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseProvidedHasTagController.cs - -using xModels.Base; -using xPushService.Base; -using xPushService.Interfaces; - -namespace xTagService.Interfaces -{ - public interface IXBaseProvidedHasTagController : IXBaseProvidedController, IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseTagProvider.cs - -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using xDataService.Interfaces; -using xTagService.Models.Dtos; - -namespace xTagService.Interfaces -{ - public interface IXBaseTagProvider : IXBaseReferencedProvider - { - // - #region Tools ... - /// - /// Add Reference a Tag to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task AddReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Tag to Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task AddReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Tag for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Tag for Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvided.cs - -using xModels.Base; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xTagService.Interfaces -{ - /// - /// a Tag Provided Service is a Model Provider Service which - /// can Contains Tags ... - /// - public interface IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach all Attached Tags of Specified Item ... - /// - /// - /// - /// - /// - /// - Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvidedController.cs - -using xModels.Base; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; - -namespace xTagService.Interfaces -{ - public interface IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ); - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces -{ - public interface IXTagProvider : IXBaseProvided - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProviderController.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces -{ - public interface IXTagProviderController : IXBaseProvidedController - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagDtoHub.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagRepositoryService.cs - -using xDataService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagServiceProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagEntityHub.cs - -using xPushService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagKeyGenerator.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepository.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepositoryEvents.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepositoryProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Entities; -using xTagService.Providers.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagSeeder.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Models\Dtos\XTagDto.cs - -using xModels.Base; - -namespace xTagService.Models.Dtos -{ - public class XTagDto : XBaseIntIDEntityDto - { - public string Tag { get; set; } - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Models\Entities\XTag.cs - -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xTagService.Models.Entities -{ - /// - /// a Tag Model ... - /// - public class XTag : XBaseIntIDEntity - { - /// - /// Tag Label ... - /// - /// - [Required] - [StringLength(255)] - public string Tag { get; set; } - - /// - /// Comma Separated List Which Provides Pointer to Specified - /// Model for Describe ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseProvidedHasTag.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xTagService.Interfaces; -using xPushService.Interfaces; -using System.Linq.Expressions; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Providers -{ - public abstract class XBaseProvidedHasTag : IXBaseProvidedHasTag - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly string[] permittedRoles; - private readonly IXBaseTagProvider tagProvider; - private readonly IXBaseDtoProvider provider; - - protected XBaseProvidedHasTag( - IXBaseTagProvider tagProvider, - IXBaseDtoProvider provider, - string[] permittedRoles = null - ) - { - this.provider = provider; - this.tagProvider = tagProvider; - this.permittedRoles = permittedRoles; - } - - /// - /// Check an Items is Owned for User or not ... - /// - /// - /// - /// - public abstract bool IsOwned( - TDto item, - XUserClaimsInfoDto userInfo - ); - public abstract bool IsOwned( - TEntity item, - XUserClaimsInfoDto userInfo - ); - - /// - /// Check User Has Permission for Manipulate Data or not ... - /// - /// - /// - public bool HasPermision( - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !userInfo.IsNullOrDefault() && - userInfo.HasAccess(permittedRoles); - - // - return result; - } - - // - #region Tag ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.AddReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Detach Tag fro Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Attach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await AttachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await DetachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach all Attached Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReferences( - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Get Specified Model's Item ... - /// - /// - /// - /// - public virtual async Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - isValid = await provider.IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = (await tagProvider.GetAllReferences( - providedForId: id, - cancellationToken: cancellationToken - )) - .Select(x => x.Tag) - .Distinct() - .ToList(); - - // - return result; - } - #endregion - - // - #region Provided ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - public virtual async Task Get( - TKey id, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - public virtual async Task> GetAll( - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAllAsync( - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - public virtual async Task FindOne( - Expression> predicate, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindOneAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task> FindMany( - Expression> predicate, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindManyAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> Query( - XQuery query, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.QueryAsync( - query: query, - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Owned Items based on XQuery Pagination structure ... - /// if supported ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryOwned( - XQuery query, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicateor = null; - if (!predicate.IsNull()) - { - // - var predicateFnc = predicate.Compile(); - predicateor = x => - predicateFnc(x) && - IsOwned(x, userInfo); - } - else - { - predicateor = x => IsOwned(x, userInfo); - } - - // - var result = await provider.QueryAsync( - query: query, - predicate: predicateor, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - public virtual async Task Add( - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task Update( - TKey id, - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.UpdateAsync( - id: id, - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove an Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Remove( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var item = await Get( - id: id, - cancellationToken: cancellationToken - ); - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.RemoveAsync( - id: id, - saveChanges: true, - softDelete: false, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// count all exists Items ... - /// - /// - /// - public virtual async Task Count( - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.CountAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - public virtual async Task IsExists( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.IsExistsAsync( - id: id, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseTagProvided.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xTagService.Interfaces; -using xPushService.Interfaces; -using System.Collections.Generic; -using xIdentityModels.Extensions; - -namespace xTagService.Providers -{ - public abstract class XBaseTagProvided : IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly string[] permittedRoles; - private readonly IXBaseTagProvider tagProvider; - private readonly IXBaseDtoProvider provider; - - protected XBaseTagProvided( - IXBaseTagProvider tagProvider, - IXBaseDtoProvider provider, - string[] permittedRoles = null - ) - { - this.provider = provider; - this.tagProvider = tagProvider; - this.permittedRoles = permittedRoles; - } - - /// - /// Check an Items is Owned for User or not ... - /// - /// - /// - /// - public abstract bool IsOwned( - TDto item, - XUserClaimsInfoDto userInfo - ); - public abstract bool IsOwned( - TEntity item, - XUserClaimsInfoDto userInfo - ); - - /// - /// Check User Has Permission for Manipulate Data or not ... - /// - /// - /// - public bool HasPermision( - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !userInfo.IsNullOrDefault() && - userInfo.HasAccess(permittedRoles); - - // - return result; - } - - // - #region Actions ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.AddReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Detach Tag fro Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Attach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await AttachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await DetachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach all Attached Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReferences( - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Get Specified Model's Item ... - /// - /// - /// - /// - public virtual async Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - isValid = await provider.IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = (await tagProvider.GetAllReferences( - providedForId: id, - cancellationToken: cancellationToken - )) - .Select(x => x.Tag) - .Distinct() - .ToList(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseTagProvider.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Extensions; -using xTagService.Interfaces; -using xDataService.Extensions; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Interfaces.Dtos; - -namespace xTagService.Providers -{ - public abstract class XBaseTagProvider : IXBaseTagProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - public string Provider { get; } - - /// - /// Tag Provider for Maipulating Tags ... - /// - public IXTagServiceProvider TagProvider { get; } - #endregion - - // - #region Constructor ... - public XBaseTagProvider( - string providedFor, - IXTagServiceProvider tagProvider - ) - { - // - Provider = providedFor; - TagProvider = tagProvider; - } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - public async Task GetReference( - TKey providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (forIndex < 0) - { - forIndex = 0; - } - - // - // Retrieve Last Index ... - var maxIndex = (await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - )) - .Max(); - if (forIndex > maxIndex) - { - XException.NotFound.Throw(); - } - - // - var indexedIdentifier = GetIndexedProvidedID( - forIndex: forIndex, - providedForId: providedForId - ); - var result = await TagProvider.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(indexedIdentifier) - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - public async Task> GetAllReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - public async Task>> GetAllReferencings( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - - // - var result = (await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Select(x => x.References) - .ToList() - .SelectMany(x => x.ParseXReferenceList()) - .Where(x => x.ProvidedFor == Provider && $"{x.ReferencedTo}" == $"{providedForId}") - .OrderBy(x => x.Index) - .AsEnumerable(); - - // - return result; - } - - /// - /// Count References ... - /// - /// - /// - /// - public async Task CountReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = (await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Count(); - - // - return result; - } - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - public async Task> QueryReferences( - XQuery query, - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (query.IsNull() || providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await TagProvider.QueryAsync( - query: query, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XTagDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !model.IsNullOrDefault() && - !model.Tag.IsNullOrEmpty() && - model.Id.IsValidIntId() && - !providedForId.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Model Exists ... - result = await TagProvider.IsExistsAsync(model.Id); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Update Model by Retrieving ... - model = await TagProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - // Retrieve all References ... - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check isReferenced or not ... - result = references - .Any(r => - r.Id == model.Id && - r.GetReferences() - .Any(rf => - rf.ProvidedFor == Provider && - rf.ReferencedTo == $"{providedForId}")); - if (result) - { - return result; - } - - // - // Here means there is not any reference to ProvidedForId ... - int forIndex = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - var modelReferences = model.GetReferences(); - modelReferences.Add(new XReference - { - Index = forIndex, - ProvidedFor = Provider, - ReferencedTo = $"{providedForId}" - }); - modelReferences = modelReferences - .OrderBy(r => r.Index) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update Data Base ... - model = await TagProvider.UpdateAsync( - id: model.Id, - item: model, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - - // - return result; - } - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XTagDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - // Since other Validations Handled in Calling, we Ignore them here ... - var result = - !model.IsNull() && - !reference.IsNullOrDefault() && - reference.ProvidedFor == Provider && - !reference.ReferencedTo.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await AddReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XTagDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !providedForId.IsNull() && - !model.IsNullOrDefault() && - model.Id.IsValidIntId(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Model ... - model = await TagProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Reading Referencing Indexes ... - var indexes = await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check Model Reference to ID ... - var referencesCount = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - result = referencesCount == 0; - if (result) - { - // - // There is not any Reference to Remove ... - return result; - } - - // - // Check Model is Trully Referenced to ProvidedForId or not ... - var reference = model - .GetReferences() - .FirstOrDefault(r => - r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}"); - result = !reference.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Remove Referenced Item from Model ... - var modelReferences = model - .GetReferences() - .Where(r => - !(r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}")) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update DataBase ... - model = await TagProvider.UpdateAsync( - item: model, - id: model.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - result = !model.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Get Max Exists Indexes ... - var maxIndex = indexes.Max(); - - // - // Here We Have to Re Arrange Indexed ... - if (reference.Index < maxIndex) - { - // - var startIndex = reference.Index + 1; - for (int i = startIndex; i <= maxIndex; i++) - { - // - var dto = await GetReference( - forIndex: i, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!dto.IsNullOrDefault()) - { - // - var dtoReferences = dto.GetReferences(); - dtoReferences - .ToList() - .ForEach(iref => - { - // - if ( - iref.Index == i && - iref.ProvidedFor == Provider && - iref.ReferencedTo == reference.ReferencedTo - ) - { - iref.Index = i - 1; - } - }); - dto = dto.UpdateReferences(dtoReferences); - - // - dto = await TagProvider.UpdateAsync( - item: dto, - id: dto.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - } - - // - return result; - } - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XTagDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - if (model.IsNullOrDefault() || - reference.IsNullOrDefault() || - reference.ReferencedTo.IsNull() || - reference.ProvidedFor != Provider) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await RemoveReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - public async Task RemoveReferences( - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = false; - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!references.IsNull() && references.HasChild()) - { - // - foreach (var reference in references) - { - // - // Remove Reference ... - var itemReferences = reference.GetReferences() - .Where(r => - r.ProvidedFor != Provider || - (r.ProvidedFor == Provider && - r.ReferencedTo != $"{providedForId}")) - .ToList(); - var updatedModel = reference.UpdateReferences(itemReferences); - updatedModel = await TagProvider.UpdateAsync( - saveChanges: true, - item: updatedModel, - id: updatedModel.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!updatedModel.IsNullOrDefault()) - { - result = true; - } - } - } - - // - return result; - } - #endregion - - // - #region Tools ... - /// - /// Add Reference a Tag to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !tag.IsNullOrEmpty(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Tag Exists ... - result = await IsExists( - tag: tag, - cancellationToken: cancellationToken - ); - if (!result) - { - // - // Create Tag if Not Exists ... - var tagDto = new XTagDto - { - Tag = tag, - }; - tagDto = await TagProvider.AddAsync( - item: tagDto, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !tagDto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - } - - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - result = await AddReference( - model: dto, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add Reference a Tag to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = - !tag.IsNullOrEmpty() && - !reference.IsNullOrDefault() && - reference.ProvidedFor == Provider && - !reference.ReferencedTo.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await AddReference( - tag: tag, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove Reference a Tag for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !tag.IsNullOrEmpty() && - !providedForId.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Tag Exists ... - result = await IsExists( - tag: tag, - cancellationToken: cancellationToken - ); - if (!result) - { - XException.NotFound.Throw(); - } - - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - result = await RemoveReference( - model: dto, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Reference a Tag for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !tag.IsNullOrEmpty() && - !reference.IsNullOrDefault() && - !reference.ReferencedTo.IsNull() && - reference.ProvidedFor == Provider; - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await RemoveReference( - tag: tag, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - #endregion - - // - #region Private ... - private string GetProvidedID( - TKey providedForId, - char splitter = '_' - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = $"{Provider}{splitter}{providedForId}"; - return result; - } - - private string GetIndexedProvidedID( - TKey providedForId, - int forIndex, - char splitter = '_' - ) - { - // - var result = $"{GetProvidedID(providedForId, splitter)}{splitter}{forIndex}"; - - // - return result; - } - - private async Task> GetReferencingIndexes( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = new List(); - var referencings = await GetAllReferencings( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - isValid = - !referencings.IsNull() && - referencings.HasChild(); - if (!isValid) - { - return result; - } - - // - result = - referencings - .OrderBy(r => r.Index) - .Select(r => r.Index) - .ToList(); - - // - return result; - } - - private async Task GetTagByTag( - string tag, - CancellationToken cancellationToken = default - ) - { - // - XTagDto result = null; - - // - if (!tag.IsNullOrEmpty()) - { - // - result = await TagProvider - .FindOneAsync( - predicate: x => x.Tag == tag, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - private async Task IsExists( - string tag, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - if (!tag.IsNullOrEmpty()) - { - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\XTagEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xTagService.Configurations.Entities; - -namespace xTagService.Providers -{ - public class XTagEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XTagEntityRegisterar() - : base(nameof(XTagEntityRegisterar)) - { - // - // Add XTag Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XTagEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\XTagProvider.cs - -using xCommons.Extensions; -using xIdentityModels.Models; -using xPushService.Providers; -using xTagService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Providers -{ - public class XTagProvider : XBaseProvided, IXTagProvider - { - public XTagProvider( - IXTagServiceProvider provider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { } - - public override bool IsOwned( - XTagDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XTag item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagDtoHub.cs - -using xPushService.Base; -using xTagService.Models.Dtos; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xTagService.Providers.Dtos -{ - public class XTagDtoHub : XBaseDtoHub, IXTagDtoHub - { - public XTagDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Dtos -{ - public class XTagRepositoryService : XBaseRepositoryService, IXTagRepositoryService - { - public XTagRepositoryService( - IXTagRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagServiceProvider.cs - -using xPushService.Base; -using xTagService.Models.Dtos; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.AspNetCore.SignalR; - -namespace xTagService.Providers.Dtos -{ - public class XTagServiceProvider : XBaseDtoProvider, IXTagServiceProvider - { - public XTagServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXTagRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagEFRepository : XBaseEFRepository, IXTagRepository - where TContext : XDbContext - { - public XTagEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagEntityHub.cs - -using xPushService.Base; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagEntityHub : XBaseEntityHub, IXTagEntityHub - { - public XTagEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagInMemoryRepository : XBaseInMemoryRepository, IXTagRepository - { - public XTagInMemoryRepository( - XDataServiceConfiguration configuration, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagKeyGenerator.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagKeyGenerator : XIntKeyGenerator, IXTagKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagMongoRepository : XBaseMongoRepository, IXTagRepository - { - public XTagMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagRepositoryEvents.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagRepositoryEvents : XBaseRepositoryEvents, IXTagRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.AspNetCore.SignalR; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagRepositoryProvider : XBaseEntityProvider, IXTagRepositoryProvider - { - public XTagRepositoryProvider( - IHubContext hub, - IXTagRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagSeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public abstract class XTagSeederBase : XBaseDbSeeder, IXTagSeeder - { - protected XTagSeederBase( - string entity, - string database, - IXTagRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xTagService.Constants; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXTagGraphQLTypeHelper - { - public XTagGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XTagServiceConstants.XTagCollectionName; - } - - public override string GetInQuerySingleName() - { - return XTagServiceConstants.XTagSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphQuery : XBaseGraphQLQuery - { - public XTagGraphQuery( - XDataServiceConfiguration configuration, - IXTagRepository repository, - IXTagGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphSchema : Schema - { - public XTagGraphSchema(IServiceProvider services) : base(services) - { - Query = (XTagGraphQuery)services.GetService(typeof(XTagGraphQuery)); - } - - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphType.cs - -using xDataService.GraphQL; -using xTagService.Models.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphType : XBaseGraphObjectType - { - public XTagGraphType() : base() - { - Field(x => x.Tag); - Field(x => x.References); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xTagService-20261111_121235.txt b/Documents/GeneratedContext/xDashboard-xTagService-20261111_121235.txt deleted file mode 100644 index 33cc8f3..0000000 --- a/Documents/GeneratedContext/xDashboard-xTagService-20261111_121235.txt +++ /dev/null @@ -1,5044 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Configurations\Entities\XTagEntityConfiguration.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xTagService.Configurations.Entities -{ - public class XTagEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable("Tags"); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Constants\XTagServiceConstants.cs - -namespace xTagService.Constants -{ - public struct XTagServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XTagServiceDILogTag = "XTagService"; - - // - // Table Mapping Identifiers ... - public const string XTagTable = "Tags"; - - // - // GraphQL Collection Mappings ... - public const string XTagSingleName = "tag"; - public const string XTagCollectionName = "tags"; - - // - // Hubs ... - public const string XTagDtoHub = "tagDto"; - public const string XTagEntityHub = "tagEntity"; - - // - // Custome Constants ... - - // - // EF Repositories Helper Extensions ... - public const string GetXTagEFRepositoryDescriptor = "GetXTagEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XBaseProvidedHasTagControllerBase.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Interfaces; -using xCommons.Configurations; -using xPushService.Interfaces; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - [AllowAnonymous] - public abstract class XBaseProvidedHasTagControllerBase : XBaseIdentityApiV1Controller, IXBaseProvidedHasTagController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly IXBaseProvided provider; - private readonly IXTagProvided tagProvided; - private readonly Func, IOrderedQueryable> defaultOrderBuilder; - private readonly Func, IIncludableQueryable> defaultIncludeBuilder; - - protected XBaseProvidedHasTagControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXBaseProvided provider, - IXTagProvided tagProvided, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.provider = provider; - this.tagProvided = tagProvided; - this.defaultOrderBuilder = defaultOrderBuilder; - this.defaultIncludeBuilder = defaultIncludeBuilder; - } - - // - #region Provided ... - // - #region Retrieve ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - [HttpGet("{id}")] - public virtual async Task> Get( - [FromRoute] TKey id, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - ValidationProvider.NotNull(id); - - // - var result = await provider.Get( - id: id, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - [HttpGet("")] - public virtual async Task>> GetAll( - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await provider.GetAll( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - [HttpGet("Find/One")] - public virtual async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindOne( - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Find a collection of Items by proving a Query Search ... - /// - /// - /// - /// - /// - /// - [HttpGet("Find/Many")] - public virtual async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotEmpty(query) - .ValidateGroupAsync(); - - // - var result = await provider.FindMany( - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken, - predicate: x => x.PropValuesContains(query) - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - public virtual async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var result = await provider.Query( - query: query, - predicate: null, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Retrieve Owned Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - [HttpGet("Query/Owned")] - public virtual async Task>> QueryOwned( - [FromQuery] XQuery query, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(query) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - - // - var result = await provider.QueryOwned( - query: query, - predicate: null, - userInfo: userInfo, - orderBuilder: !useDefaultOrders - ? null - : defaultOrderBuilder, - includeBuilder: !useDefaultIncludes - ? null - : defaultIncludeBuilder, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - - // - #region Add/Update/Remove ... - /// - /// Add an item ... - /// - /// - /// - /// - [HttpPost("")] - public virtual async Task> Add( - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Add( - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - [HttpPut("{id}")] - public virtual async Task> Update( - [FromRoute] TKey id, - [FromBody] TDto item, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(item) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Update( - id: id, - item: item, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Remove an Item ... - /// - /// - /// - /// - [HttpDelete("{id}")] - public virtual async Task> Remove( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - var result = await provider.Remove( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - #endregion - - // - #region Tag ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - public virtual async Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - public virtual async Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .DetachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - public virtual async Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tags) - .AddNotZeroChilds(tags.Items) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - public virtual async Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - if (!tags.IsNull()) - { - // - await tagProvided - .DetachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - await tagProvided - .DetachTags( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - public virtual async Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await tagProvided.GetTags( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagProvidedControllerBase.cs - -using System; -using xModels.Base; -using System.Threading; -using xPushService.Base; -using xCommons.Providers; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Interfaces; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using xIdentityService.Controllers; - -namespace xTagService.Controllers -{ - public abstract class XTagProvidedControllerBase : XBaseIdentityApiV1Controller, IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly IXTagProvided tagProvided; - - protected XTagProvidedControllerBase( - ILogger> logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXIdentityProvider identityProvider, - IXTagProvided tagProvided - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider - ) - { - this.tagProvided = tagProvided; - } - - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - public virtual async Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - public virtual async Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tag) - .AddNotEmpty(tag.Value) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .DetachTag( - id: id, - tag: tag.Value, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - public virtual async Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .AddNotNull(tags) - .AddNotZeroChilds(tags.Items) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - await tagProvided - .AttachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - public virtual async Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - var userInfo = await GetUserInfo(); - var connectionId = GetConnectionId(); - - // - // Get Result ... - if (!tags.IsNull()) - { - // - await tagProvided - .DetachTags( - id: id, - tags: tags.Items, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - else - { - // - await tagProvided - .DetachTags( - id: id, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - - // - return Ok(); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - public virtual async Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ) - { - // - try - { - // - // Validate Args ... - if (!ModelState.IsValid) - { - XException.InvalidArgs.Throw(); - } - await ValidationProvider - .GroupValidationBuilder() - .AddNotNull(id) - .ValidateGroupAsync(); - - // - // Get Result ... - var result = await tagProvided.GetTags( - id: id, - cancellationToken: cancellationToken - ); - - // - return Ok(result.ToDynamicObject()); - } - catch (Exception ex) - { - // - var result = GetExceptionActionResult(ex); - return result; - } - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xTagService.Interfaces; -using xCommons.Configurations; -using xTagService.Models.Dtos; -using xPushService.Controllers; -using xTagService.Providers.Dtos; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagProviderControllerBase : XBaseProvidedController, IXTagProviderController - { - protected XTagProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagRepositoryControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xDataService.Controllers; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagRepositoryControllerBase : XBaseRepositoryController, IXBaseRepositoryController - { - protected XTagRepositoryControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXTagRepository repository, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repository, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagRepositoryProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xPushService.Controllers; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagRepositoryProviderControllerBase : XBaseRepositoryProviderController, IXBaseRepositoryProviderController - { - protected XTagRepositoryProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagRepositoryProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagServiceControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xDataService.Interfaces; -using xTagService.Models.Dtos; -using xDataService.Controllers; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagServiceControllerBase : XBaseServiceController, IXBaseServiceController - { - protected XTagServiceControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXTagRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Controllers\XTagServiceProviderControllerBase.cs - -using System; -using System.Linq; -using xCommons.Providers; -using xCommons.Configurations; -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xPushService.Controllers; -using xTagService.Providers.Dtos; -using xIdentityService.Interfaces; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Controllers -{ - public abstract class XTagServiceProviderControllerBase : XBaseServiceProviderController, IXBaseServiceProviderController - { - protected XTagServiceProviderControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTagServiceProvider provider, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xTagService.Helpers; -using xPushService.Helpers; -using xExceptions.Constants; -using xTagService.Constants; -using xTagService.Providers; -using xDataService.Constants; -using xTagService.Interfaces; -using xTagService.Providers.Dtos; -using xTagService.Interfaces.Dtos; -using Microsoft.AspNetCore.Builder; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xTagService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXTagService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddTagService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXTagService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddTagService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XTagService Middleware ... - /// - /// - /// - public static void UseXTagService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XTag Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XTagServiceConstants.XTagDtoHub); - pushHelper.AddHub(XTagServiceConstants.XTagEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XTag Repository Descriptor ... - if (!descriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: descriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor descriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XTagServiceConstants.XTagServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddTagService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - descriptor = typeof(XTagServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XTagServiceConstants.GetXTagEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - descriptor = XTagServiceHelper.GetXTagMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - descriptor = XTagServiceHelper.GetXTagInMemoryRepositoryDescriptor(); - break; - } - - // - // Register XTag Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: descriptor - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXTagServiceProvider), typeof(XTagServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXTagRepositoryService), typeof(XTagRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXTagRepositoryProvider), typeof(XTagRepositoryProvider), lifeTime) - ); - - // - services.Add( - new ServiceDescriptor(typeof(IXTagProvider), typeof(XTagProvider), lifeTime) - ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Extensions\XModelExtensions.cs - -using System.Linq; -using xCommons.Extensions; -using xDataService.Models; -using xDataService.Extensions; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Models.Entities; - -namespace xTagService.Extensions -{ - public static class XModelExtensions - { - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XTag source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Extract References of a Model ... - /// - /// - /// - public static IList> GetReferences( - this XTagDto source - ) - { - // - var result = new List>(); - - // - if ( - !source.IsNullOrDefault() && - !source.References.IsNullOrEmpty() - ) - { - // - result = source.References - .ParseXReferenceList() - .ToList(); - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XTag UpdateReferences( - this XTag source, - IList> references, - bool forceClean = true - ) - { - // - XTag result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - - /// - /// Update a Model's References by Providing References List ... - /// - /// - /// - /// - /// - public static XTagDto UpdateReferences( - this XTagDto source, - IList> references, - bool forceClean = true - ) - { - // - XTagDto result = source; - - // - if (!source.IsNullOrDefault()) - { - // - result = source; - - // - if (forceClean) - { - result.References = string.Empty; - } - - // - if (!references.IsNull() && - references.HasChild()) - { - result.References = references.ToXReferenceString(); - } - } - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Helpers\XTagServiceHelper.cs - -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Providers.GraphQL; -using xTagService.Providers.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Helpers -{ - public static class XTagServiceHelper - { - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext - > GetXTagEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext, - IXTagSeeder, - TSeederImplementation - > GetXTagEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagEFRepository, - TContext, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository - > GetXTagMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository, - IXTagSeeder, - TSeederImplementation - > GetXTagMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagMongoRepository, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository - > GetXTagInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository, - IXTagSeeder, - TSeederImplementation - > GetXTagInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XTag, - int, - IXTagKeyGenerator, - XTagKeyGenerator, - IXTagRepositoryEvents, - XTagRepositoryEvents, - XTagGraphType, - IntGraphType, - XTagGraphQuery, - IXTagGraphQLTypeHelper, - XTagGraphQLTypeHelper, - XTagGraphSchema, - IXTagRepository, - XTagInMemoryRepository, - IXTagSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseProvidedHasTag.cs - -using xModels.Base; -using xPushService.Base; -using xPushService.Interfaces; - -namespace xTagService.Interfaces -{ - public interface IXBaseProvidedHasTag : IXBaseProvided, IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseProvidedHasTagController.cs - -using xModels.Base; -using xPushService.Base; -using xPushService.Interfaces; - -namespace xTagService.Interfaces -{ - public interface IXBaseProvidedHasTagController : IXBaseProvidedController, IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXBaseTagProvider.cs - -using System.Threading; -using xDataService.Models; -using System.Threading.Tasks; -using xDataService.Interfaces; -using xTagService.Models.Dtos; - -namespace xTagService.Interfaces -{ - public interface IXBaseTagProvider : IXBaseReferencedProvider - { - // - #region Tools ... - /// - /// Add Reference a Tag to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task AddReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Add Reference a Tag to Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task AddReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Tag for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Remove Reference a Tag for Specific XRefence ... - /// - /// - /// - /// - /// - /// - Task RemoveReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ); - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvided.cs - -using xModels.Base; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using xIdentityModels.Models; -using System.Collections.Generic; - -namespace xTagService.Interfaces -{ - /// - /// a Tag Provided Service is a Model Provider Service which - /// can Contains Tags ... - /// - public interface IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - /// - /// - Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Detach all Attached Tags of Specified Item ... - /// - /// - /// - /// - /// - /// - Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvidedController.cs - -using xModels.Base; -using System.Threading; -using xPushService.Base; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -using System.Collections.Generic; - -namespace xTagService.Interfaces -{ - public interface IXTagProvidedController - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attach")] - Task AttachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tag of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detach")] - Task DetachTag( - [FromRoute] TKey id, - [FromBody] XBaseValueContainer tag, - CancellationToken cancellationToken = default - ); - - /// - /// Attach Tags to Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/attachs")] - Task AttachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags, - CancellationToken cancellationToken = default - ); - - /// - /// Detach Tags of Specified Item ... - /// - /// - /// - /// - /// - [HttpPost("{id}/tags/detachs")] - Task DetachTags( - [FromRoute] TKey id, - [FromBody] XBaseRangeRequest tags = null, - CancellationToken cancellationToken = default - ); - - /// - /// Get Specified Item Tags ... - /// - /// - /// - /// - [HttpGet("{id}/tags")] - Task>> GetTags( - [FromRoute] TKey id, - CancellationToken cancellationToken = default - ); - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces -{ - public interface IXTagProvider : IXBaseProvided - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\IXTagProviderController.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces -{ - public interface IXTagProviderController : IXBaseProvidedController - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagDtoHub.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagRepositoryService.cs - -using xDataService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Dtos\IXTagServiceProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Dtos -{ - public interface IXTagServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagEntityHub.cs - -using xPushService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagKeyGenerator.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepository.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepositoryEvents.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagRepositoryProvider.cs - -using xPushService.Interfaces; -using xTagService.Models.Entities; -using xTagService.Providers.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Interfaces\Entities\IXTagSeeder.cs - -using xDataService.Interfaces; -using xTagService.Models.Entities; - -namespace xTagService.Interfaces.Entities -{ - public interface IXTagSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Models\Dtos\XTagDto.cs - -using xModels.Base; - -namespace xTagService.Models.Dtos -{ - public class XTagDto : XBaseIntIDEntityDto - { - public string Tag { get; set; } - public string References { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Models\Entities\XTag.cs - -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xTagService.Models.Entities -{ - /// - /// a Tag Model ... - /// - public class XTag : XBaseIntIDEntity - { - /// - /// Tag Label ... - /// - /// - [Required] - [StringLength(255)] - public string Tag { get; set; } - - /// - /// Comma Separated List Which Provides Pointer to Specified - /// Model for Describe ... - /// - /// - public string References { get; set; } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseProvidedHasTag.cs - -using System; -using System.Linq; -using xModels.Base; -using xModels.Dtos; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xTagService.Interfaces; -using xPushService.Interfaces; -using System.Linq.Expressions; -using System.Collections.Generic; -using xIdentityModels.Extensions; -using Microsoft.EntityFrameworkCore.Query; - -namespace xTagService.Providers -{ - public abstract class XBaseProvidedHasTag : IXBaseProvidedHasTag - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly string[] permittedRoles; - private readonly IXBaseTagProvider tagProvider; - private readonly IXBaseDtoProvider provider; - - protected XBaseProvidedHasTag( - IXBaseTagProvider tagProvider, - IXBaseDtoProvider provider, - string[] permittedRoles = null - ) - { - this.provider = provider; - this.tagProvider = tagProvider; - this.permittedRoles = permittedRoles; - } - - /// - /// Check an Items is Owned for User or not ... - /// - /// - /// - /// - public abstract bool IsOwned( - TDto item, - XUserClaimsInfoDto userInfo - ); - public abstract bool IsOwned( - TEntity item, - XUserClaimsInfoDto userInfo - ); - - /// - /// Check User Has Permission for Manipulate Data or not ... - /// - /// - /// - public bool HasPermision( - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !userInfo.IsNullOrDefault() && - userInfo.HasAccess(permittedRoles); - - // - return result; - } - - // - #region Tag ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.AddReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Detach Tag fro Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Attach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await AttachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await DetachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach all Attached Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReferences( - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Get Specified Model's Item ... - /// - /// - /// - /// - public virtual async Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - isValid = await provider.IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = (await tagProvider.GetAllReferences( - providedForId: id, - cancellationToken: cancellationToken - )) - .Select(x => x.Tag) - .Distinct() - .ToList(); - - // - return result; - } - #endregion - - // - #region Provided ... - /// - /// Get Specified Item by ID ... - /// - /// - /// - /// - /// - public virtual async Task Get( - TKey id, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Get All Exists Items ... - /// - /// - /// - /// - /// - public virtual async Task> GetAll( - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.GetAllAsync( - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find an item by providing a Conditional Expression ... - /// - /// - /// - /// - /// - public virtual async Task FindOne( - Expression> predicate, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindOneAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// find a collection of Items by proving a Conditional Expression ... - /// - /// - /// - /// - /// - /// - public virtual async Task> FindMany( - Expression> predicate, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.FindManyAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Items based on XQuery Pagination structure ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> Query( - XQuery query, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.QueryAsync( - query: query, - predicate: predicate, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// retrieve Owned Items based on XQuery Pagination structure ... - /// if supported ... - /// - /// - /// - /// - /// - /// - /// - /// - public virtual async Task> QueryOwned( - XQuery query, - XUserClaimsInfoDto userInfo = null, - Expression> predicate = null, - Func, IOrderedQueryable> orderBuilder = null, - Func, IIncludableQueryable> includeBuilder = null, - CancellationToken cancellationToken = default - ) - { - // - Expression> predicateor = null; - if (!predicate.IsNull()) - { - // - var predicateFnc = predicate.Compile(); - predicateor = x => - predicateFnc(x) && - IsOwned(x, userInfo); - } - else - { - predicateor = x => IsOwned(x, userInfo); - } - - // - var result = await provider.QueryAsync( - query: query, - predicate: predicateor, - ignoreSoftDeleteds: true, - orderBuilder: orderBuilder, - includeBuilder: includeBuilder, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add an item values ... - /// - /// - /// - /// - /// - /// - public virtual async Task Add( - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.AddAsync( - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update an item values ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task Update( - TKey id, - TDto item, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.UpdateAsync( - id: id, - item: item, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// remove an Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task Remove( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Check Permission ... - var item = await Get( - id: id, - cancellationToken: cancellationToken - ); - var hasPermission = - IsOwned(item, userInfo) || - HasPermision(userInfo); - if (!hasPermission) - { - XException.NotAllowed.Throw(); - } - - // - var result = await provider.RemoveAsync( - id: id, - saveChanges: true, - softDelete: false, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// count all exists Items ... - /// - /// - /// - public virtual async Task Count( - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.CountAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Check an Item exists or not ... - /// - /// - /// - /// - public virtual async Task IsExists( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - var result = await provider.IsExistsAsync( - id: id, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseTagProvided.cs - -using System.Linq; -using xModels.Base; -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using xExceptions.Constants; -using System.Threading.Tasks; -using xIdentityModels.Models; -using xTagService.Interfaces; -using xPushService.Interfaces; -using System.Collections.Generic; -using xIdentityModels.Extensions; - -namespace xTagService.Providers -{ - public abstract class XBaseTagProvided : IXTagProvided - where TEntity : XBaseEntity - where TDto : XBaseEntityDto - where THub : XBaseDtoHub - { - private readonly string[] permittedRoles; - private readonly IXBaseTagProvider tagProvider; - private readonly IXBaseDtoProvider provider; - - protected XBaseTagProvided( - IXBaseTagProvider tagProvider, - IXBaseDtoProvider provider, - string[] permittedRoles = null - ) - { - this.provider = provider; - this.tagProvider = tagProvider; - this.permittedRoles = permittedRoles; - } - - /// - /// Check an Items is Owned for User or not ... - /// - /// - /// - /// - public abstract bool IsOwned( - TDto item, - XUserClaimsInfoDto userInfo - ); - public abstract bool IsOwned( - TEntity item, - XUserClaimsInfoDto userInfo - ); - - /// - /// Check User Has Permission for Manipulate Data or not ... - /// - /// - /// - public bool HasPermision( - XUserClaimsInfoDto userInfo - ) - { - // - var result = - !userInfo.IsNullOrDefault() && - userInfo.HasAccess(permittedRoles); - - // - return result; - } - - // - #region Actions ... - /// - /// Attach Tag to Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.AddReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Detach Tag fro Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTag( - TKey id, - string tag, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tag.IsNullOrEmpty() && - !userInfo.IsNullOrDefault(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReference( - tag: tag, - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Attach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task AttachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await AttachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - IEnumerable tags, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull() && - !tags.IsNull() && - tags.HasChild(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - // Loop through Tags ... - foreach (var tag in tags) - { - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - - // - await DetachTag( - id: id, - tag: tag, - userInfo: userInfo, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - - /// - /// Detach all Attached Tags for Specified Item ... - /// - /// - /// - /// - /// - /// - public virtual async Task DetachTags( - TKey id, - XUserClaimsInfoDto userInfo = null, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var item = await provider.GetAsync( - id: id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - isValid = - !item.IsNullOrDefault() && - (IsOwned(item, userInfo) || - HasPermision(userInfo)); - if (!isValid) - { - XException.NotAllowed.Throw(); - } - - // - try - { - // - await tagProvider.RemoveReferences( - providedForId: id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - catch { } - } - - /// - /// Get Specified Model's Item ... - /// - /// - /// - /// - public virtual async Task> GetTags( - TKey id, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !id.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - isValid = await provider.IsExistsAsync( - id: id, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (!isValid) - { - XException.NotFound.Throw(); - } - - // - var result = (await tagProvider.GetAllReferences( - providedForId: id, - cancellationToken: cancellationToken - )) - .Select(x => x.Tag) - .Distinct() - .ToList(); - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\XBaseTagProvider.cs - -using System.Linq; -using xModels.Dtos; -using System.Threading; -using xCommons.Extensions; -using xDataService.Models; -using xExceptions.Constants; -using System.Threading.Tasks; -using xTagService.Extensions; -using xTagService.Interfaces; -using xDataService.Extensions; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Interfaces.Dtos; - -namespace xTagService.Providers -{ - public abstract class XBaseTagProvider : IXBaseTagProvider - { - // - #region Props ... - /// - /// Provider Identifier ... - /// - public string Provider { get; } - - /// - /// Tag Provider for Maipulating Tags ... - /// - public IXTagServiceProvider TagProvider { get; } - #endregion - - // - #region Constructor ... - public XBaseTagProvider( - string providedFor, - IXTagServiceProvider tagProvider - ) - { - // - Provider = providedFor; - TagProvider = tagProvider; - } - #endregion - - // - #region Referenced Actions ... - /// - /// Get Specified Indexed Reference for Specific Provided ID ... - /// - /// - /// - /// - /// - public async Task GetReference( - TKey providedForId, - int forIndex = 0, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - // Normalize ... - if (forIndex < 0) - { - forIndex = 0; - } - - // - // Retrieve Last Index ... - var maxIndex = (await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - )) - .Max(); - if (forIndex > maxIndex) - { - XException.NotFound.Throw(); - } - - // - var indexedIdentifier = GetIndexedProvidedID( - forIndex: forIndex, - providedForId: providedForId - ); - var result = await TagProvider.FindOneAsync( - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(indexedIdentifier) - ); - if (result.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - return result; - } - - /// - /// Retrieve all Exists References of Specific Provided ID ... - /// - /// - /// - /// - public async Task> GetAllReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Extract all Referencing Models for Specified Key ... - /// - /// - /// - /// - public async Task>> GetAllReferencings( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - - // - var result = (await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Select(x => x.References) - .ToList() - .SelectMany(x => x.ParseXReferenceList()) - .Where(x => x.ProvidedFor == Provider && $"{x.ReferencedTo}" == $"{providedForId}") - .OrderBy(x => x.Index) - .AsEnumerable(); - - // - return result; - } - - /// - /// Count References ... - /// - /// - /// - /// - public async Task CountReferences( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = (await TagProvider.FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - predicate: x => x.References.Contains(identifier) - )) - .Count(); - - // - return result; - } - - /// - /// Retrieve References of Specific Provided ID as Query ... - /// - /// - /// - /// - /// - public async Task> QueryReferences( - XQuery query, - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (query.IsNull() || providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var identifier = GetProvidedID(providedForId); - var result = await TagProvider.QueryAsync( - query: query, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.Id), - predicate: x => x.References.Contains(identifier) - ); - - // - return result; - } - - /// - /// Add Reference a Model to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XTagDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !model.IsNullOrDefault() && - !model.Tag.IsNullOrEmpty() && - model.Id.IsValidIntId() && - !providedForId.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Model Exists ... - result = await TagProvider.IsExistsAsync(model.Id); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Update Model by Retrieving ... - model = await TagProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - - // - // Retrieve all References ... - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check isReferenced or not ... - result = references - .Any(r => - r.Id == model.Id && - r.GetReferences() - .Any(rf => - rf.ProvidedFor == Provider && - rf.ReferencedTo == $"{providedForId}")); - if (result) - { - return result; - } - - // - // Here means there is not any reference to ProvidedForId ... - int forIndex = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - var modelReferences = model.GetReferences(); - modelReferences.Add(new XReference - { - Index = forIndex, - ProvidedFor = Provider, - ReferencedTo = $"{providedForId}" - }); - modelReferences = modelReferences - .OrderBy(r => r.Index) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update Data Base ... - model = await TagProvider.UpdateAsync( - id: model.Id, - item: model, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - - // - return result; - } - - /// - /// Add Reference a Model to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - XTagDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - // Since other Validations Handled in Calling, we Ignore them here ... - var result = - !model.IsNull() && - !reference.IsNullOrDefault() && - reference.ProvidedFor == Provider && - !reference.ReferencedTo.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await AddReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove Reference a Model for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XTagDto model, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !providedForId.IsNull() && - !model.IsNullOrDefault() && - model.Id.IsValidIntId(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Model ... - model = await TagProvider.GetAsync( - id: model.Id, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - result = !model.IsNullOrDefault(); - if (!result) - { - XException.NotFound.Throw(); - } - - // - // Reading Referencing Indexes ... - var indexes = await GetReferencingIndexes( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - // Check Model Reference to ID ... - var referencesCount = await CountReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - result = referencesCount == 0; - if (result) - { - // - // There is not any Reference to Remove ... - return result; - } - - // - // Check Model is Trully Referenced to ProvidedForId or not ... - var reference = model - .GetReferences() - .FirstOrDefault(r => - r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}"); - result = !reference.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Remove Referenced Item from Model ... - var modelReferences = model - .GetReferences() - .Where(r => - !(r.ProvidedFor == Provider && - r.ReferencedTo == $"{providedForId}")) - .ToList(); - model = model.UpdateReferences(modelReferences); - - // - // Update DataBase ... - model = await TagProvider.UpdateAsync( - item: model, - id: model.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - - // - result = !model.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - // Get Max Exists Indexes ... - var maxIndex = indexes.Max(); - - // - // Here We Have to Re Arrange Indexed ... - if (reference.Index < maxIndex) - { - // - var startIndex = reference.Index + 1; - for (int i = startIndex; i <= maxIndex; i++) - { - // - var dto = await GetReference( - forIndex: i, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!dto.IsNullOrDefault()) - { - // - var dtoReferences = dto.GetReferences(); - dtoReferences - .ToList() - .ForEach(iref => - { - // - if ( - iref.Index == i && - iref.ProvidedFor == Provider && - iref.ReferencedTo == reference.ReferencedTo - ) - { - iref.Index = i - 1; - } - }); - dto = dto.UpdateReferences(dtoReferences); - - // - dto = await TagProvider.UpdateAsync( - item: dto, - id: dto.Id, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - } - } - } - - // - return result; - } - - /// - /// Remove Reference a Model for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - XTagDto model, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - if (model.IsNullOrDefault() || - reference.IsNullOrDefault() || - reference.ReferencedTo.IsNull() || - reference.ProvidedFor != Provider) - { - XException.InvalidArgs.Throw(); - } - - // - var result = await RemoveReference( - model: model, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove All References to Specified Key ... - /// - /// - /// - /// - /// - public async Task RemoveReferences( - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = false; - var references = await GetAllReferences( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - if (!references.IsNull() && references.HasChild()) - { - // - foreach (var reference in references) - { - // - // Remove Reference ... - var itemReferences = reference.GetReferences() - .Where(r => - r.ProvidedFor != Provider || - (r.ProvidedFor == Provider && - r.ReferencedTo != $"{providedForId}")) - .ToList(); - var updatedModel = reference.UpdateReferences(itemReferences); - updatedModel = await TagProvider.UpdateAsync( - saveChanges: true, - item: updatedModel, - id: updatedModel.Id, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - if (!updatedModel.IsNullOrDefault()) - { - result = true; - } - } - } - - // - return result; - } - #endregion - - // - #region Tools ... - /// - /// Add Reference a Tag to Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = !tag.IsNullOrEmpty(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Tag Exists ... - result = await IsExists( - tag: tag, - cancellationToken: cancellationToken - ); - if (!result) - { - // - // Create Tag if Not Exists ... - var tagDto = new XTagDto - { - Tag = tag, - }; - tagDto = await TagProvider.AddAsync( - item: tagDto, - saveChanges: true, - connectionId: connectionId, - cancellationToken: cancellationToken - ); - result = !tagDto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - } - - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - result = await AddReference( - model: dto, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add Reference a Tag to Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task AddReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - // Validate ... - result = - !tag.IsNullOrEmpty() && - !reference.IsNullOrDefault() && - reference.ProvidedFor == Provider && - !reference.ReferencedTo.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await AddReference( - tag: tag, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - - /// - /// Remove Reference a Tag for Specific Provided ID ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - string tag, - TKey providedForId, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !tag.IsNullOrEmpty() && - !providedForId.IsNull(); - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - // Check Tag Exists ... - result = await IsExists( - tag: tag, - cancellationToken: cancellationToken - ); - if (!result) - { - XException.NotFound.Throw(); - } - - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - if (!result) - { - XException.ActionFailed.Throw(); - } - - // - result = await RemoveReference( - model: dto, - connectionId: connectionId, - providedForId: providedForId, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Reference a Tag for Specific XRefence ... - /// - /// - /// - /// - /// - /// - public async Task RemoveReference( - string tag, - XReference reference, - string connectionId = null, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var result = - !tag.IsNullOrEmpty() && - !reference.IsNullOrDefault() && - !reference.ReferencedTo.IsNull() && - reference.ProvidedFor == Provider; - if (!result) - { - XException.InvalidArgs.Throw(); - } - - // - result = await RemoveReference( - tag: tag, - connectionId: connectionId, - cancellationToken: cancellationToken, - providedForId: reference.ReferencedTo - ); - - // - return result; - } - #endregion - - // - #region Private ... - private string GetProvidedID( - TKey providedForId, - char splitter = '_' - ) - { - // - // Validate ... - if (providedForId.IsNull()) - { - XException.InvalidArgs.Throw(); - } - - // - var result = $"{Provider}{splitter}{providedForId}"; - return result; - } - - private string GetIndexedProvidedID( - TKey providedForId, - int forIndex, - char splitter = '_' - ) - { - // - var result = $"{GetProvidedID(providedForId, splitter)}{splitter}{forIndex}"; - - // - return result; - } - - private async Task> GetReferencingIndexes( - TKey providedForId, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - var isValid = - !providedForId.IsNull(); - if (!isValid) - { - XException.InvalidArgs.Throw(); - } - - // - var result = new List(); - var referencings = await GetAllReferencings( - providedForId: providedForId, - cancellationToken: cancellationToken - ); - isValid = - !referencings.IsNull() && - referencings.HasChild(); - if (!isValid) - { - return result; - } - - // - result = - referencings - .OrderBy(r => r.Index) - .Select(r => r.Index) - .ToList(); - - // - return result; - } - - private async Task GetTagByTag( - string tag, - CancellationToken cancellationToken = default - ) - { - // - XTagDto result = null; - - // - if (!tag.IsNullOrEmpty()) - { - // - result = await TagProvider - .FindOneAsync( - predicate: x => x.Tag == tag, - cancellationToken: cancellationToken - ); - } - - // - return result; - } - - private async Task IsExists( - string tag, - CancellationToken cancellationToken = default - ) - { - // - var result = false; - - // - if (!tag.IsNullOrEmpty()) - { - // - var dto = await GetTagByTag( - tag: tag, - cancellationToken: cancellationToken - ); - result = !dto.IsNullOrDefault(); - } - - // - return result; - } - #endregion - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\XTagEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.EntityFrameworkCore; -using xTagService.Configurations.Entities; - -namespace xTagService.Providers -{ - public class XTagEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XTagEntityRegisterar() - : base(nameof(XTagEntityRegisterar)) - { - // - // Add XTag Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XTagEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\XTagProvider.cs - -using xCommons.Extensions; -using xIdentityModels.Models; -using xPushService.Providers; -using xTagService.Interfaces; -using xTagService.Models.Dtos; -using xTagService.Providers.Dtos; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; - -namespace xTagService.Providers -{ - public class XTagProvider : XBaseProvided, IXTagProvider - { - public XTagProvider( - IXTagServiceProvider provider - ) : base( - provider, - permittedRoles: new string[] { } - ) - { } - - public override bool IsOwned( - XTagDto item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - - public override bool IsOwned( - XTag item, - XUserClaimsInfoDto userInfo - ) - { - return !item.IsNullOrDefault(); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagDtoHub.cs - -using xPushService.Base; -using xTagService.Models.Dtos; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; - -namespace xTagService.Providers.Dtos -{ - public class XTagDtoHub : XBaseDtoHub, IXTagDtoHub - { - public XTagDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using xTagService.Models.Dtos; -using System.Collections.Generic; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Dtos -{ - public class XTagRepositoryService : XBaseRepositoryService, IXTagRepositoryService - { - public XTagRepositoryService( - IXTagRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Dtos\XTagServiceProvider.cs - -using xPushService.Base; -using xTagService.Models.Dtos; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xTagService.Interfaces.Dtos; -using xTagService.Models.Entities; -using Microsoft.AspNetCore.SignalR; - -namespace xTagService.Providers.Dtos -{ - public class XTagServiceProvider : XBaseDtoProvider, IXTagServiceProvider - { - public XTagServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXTagRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagEFRepository : XBaseEFRepository, IXTagRepository - where TContext : XDbContext - { - public XTagEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagEntityHub.cs - -using xPushService.Base; -using xTagService.Models.Entities; -using Microsoft.Extensions.Logging; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagEntityHub : XBaseEntityHub, IXTagEntityHub - { - public XTagEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagInMemoryRepository : XBaseInMemoryRepository, IXTagRepository - { - public XTagInMemoryRepository( - XDataServiceConfiguration configuration, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagKeyGenerator.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagKeyGenerator : XIntKeyGenerator, IXTagKeyGenerator - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagMongoRepository : XBaseMongoRepository, IXTagRepository - { - public XTagMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXTagKeyGenerator keyGenerator = null, - IXTagRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagRepositoryEvents.cs - -using xDataService.Providers; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagRepositoryEvents : XBaseRepositoryEvents, IXTagRepositoryEvents - { } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xTagService.Models.Entities; -using Microsoft.AspNetCore.SignalR; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public class XTagRepositoryProvider : XBaseEntityProvider, IXTagRepositoryProvider - { - public XTagRepositoryProvider( - IHubContext hub, - IXTagRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\Entities\XTagSeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.Entities -{ - public abstract class XTagSeederBase : XBaseDbSeeder, IXTagSeeder - { - protected XTagSeederBase( - string entity, - string database, - IXTagRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xTagService.Constants; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXTagGraphQLTypeHelper - { - public XTagGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XTagServiceConstants.XTagCollectionName; - } - - public override string GetInQuerySingleName() - { - return XTagServiceConstants.XTagSingleName; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xTagService.Models.Entities; -using xTagService.Interfaces.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphQuery : XBaseGraphQLQuery - { - public XTagGraphQuery( - XDataServiceConfiguration configuration, - IXTagRepository repository, - IXTagGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphSchema : Schema - { - public XTagGraphSchema(IServiceProvider services) : base(services) - { - Query = (XTagGraphQuery)services.GetService(typeof(XTagGraphQuery)); - } - - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xTagService\Providers\GraphQL\XTagGraphType.cs - -using xDataService.GraphQL; -using xTagService.Models.Entities; - -namespace xTagService.Providers.GraphQL -{ - public class XTagGraphType : XBaseGraphObjectType - { - public XTagGraphType() : base() - { - Field(x => x.Tag); - Field(x => x.References); - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xTermsAndConditionsService-20261109_152622.txt b/Documents/GeneratedContext/xDashboard-xTermsAndConditionsService-20261109_152622.txt deleted file mode 100644 index 6077b82..0000000 --- a/Documents/GeneratedContext/xDashboard-xTermsAndConditionsService-20261109_152622.txt +++ /dev/null @@ -1,574 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Configurations\XTermsAndConditionsServiceConfiguration.cs - -using xDataService.Constants; -using System.Collections.Generic; -using xStringService.Models.Dtos; - -namespace xTermsAndConditionsService.Configurations -{ - /// - /// Terms and Conditions Configuration ... - /// - public class XTermsAndConditionsServiceConfiguration - { - /// - /// Terms And Conditions Resource Title in XString Table ... - /// - public string ResourceTitle { get; set; } = "terms_and_conditions"; - - /// - /// Seeding Mode for Terms and Conditions ... - /// - public XDbSeedingMode SeedingMode { get; set; } = XDbSeedingMode.AddIfNotExists; - - /// - /// Default Terms and Conditions for Add to Databse on App Startup ... - /// - public List TermsAndConditions { get; set; } = null; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Constants\ConfigurationNodeNames.cs - -namespace xTermsAndConditionsService.Constants -{ - public partial struct ConfigurationNodeNames - { - public const string TERMS_AND_CONDITIONS_SERVICE_NODE = "TermsAndConditionsService"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Constants\XTermsAndConditionsServiceConstants.cs - -namespace xTermsAndConditionsService.Constants -{ - public struct XTermsAndConditionsServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XTermsAndConditionsServiceDILogTag = "XTermsAndConditionsService"; - - // - // Table Mapping Identifiers ... - - // - // GraphQL Collection Mappings ... - - // - // Hubs ... - - // - // Custome Constants ... - - // - // EF Repositories Helper Extensions ... - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Controllers\XTermsAndConditionsControllerBase.cs - -using xCommons.Providers; -using xCommons.Configurations; -using xStringService.Controllers; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using xTermsAndConditionsService.Interfaces; - -namespace xTermsAndConditionsService.Controllers -{ - /// - /// a Base Controller Implementation for Providing Base Actions of - /// Terms and Conditions Provided Actions ... - /// - [AllowAnonymous] - public abstract class XTermsAndConditionsControllerBase : XBaseResourceProviderControllerBase, IXTermsAndConditionsController - { - protected XTermsAndConditionsControllerBase( - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider, - IXTermsAndConditionsProvider provider - ) : base( - logger, - appConfiguration, - identityProvider, - validationProvider, - provider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\DI\XDIHelperExtension.cs - -using System; -using System.Linq; -using xPushService.DI; -using xCommons.Extensions; -using xPushService.Helpers; -using xExceptions.Constants; -using xCommons.Configurations; -using Microsoft.AspNetCore.Builder; -using xStringService.Interfaces.Dtos; -using xTermsAndConditionsService.Hubs; -using Microsoft.Extensions.Configuration; -using xTermsAndConditionsService.Constants; -using xTermsAndConditionsService.Providers; -using xTermsAndConditionsService.Interfaces; -using Microsoft.Extensions.DependencyInjection; -using xTermsAndConditionsService.Configurations; - -namespace xTermsAndConditionsService.DI -{ - public static class XDIHelperExtension - { - /// - /// Retrieve xTermsAndConditionsService Configuration from AppSettings ... - /// - /// - /// - public static XTermsAndConditionsServiceConfiguration GetXTermsAndConditionsServiceConfiguration( - this IConfiguration configuration - ) - { - // - var section = configuration.GetSection(ConfigurationNodeNames.TERMS_AND_CONDITIONS_SERVICE_NODE); - var result = section.Get(); - - // - return result; - } - - /// - /// Extract xTermsAndConditionsService Configurations from AppSettings - /// and Register it in DI ... - /// - /// - /// - public static void AddXTermsAndConditionsConfiguration( - this IServiceCollection services, - IConfiguration configuration - ) - { - // - var serviceConfiguration = configuration.GetXTermsAndConditionsServiceConfiguration(); - services.AddXTermsAndConditionsConfiguration(serviceConfiguration); - } - - /// - /// Register xTermsAndConditionsService Configurations in DI ... - /// - /// - /// - public static void AddXTermsAndConditionsConfiguration( - this IServiceCollection services, - XTermsAndConditionsServiceConfiguration configuration - ) - { - // - if (configuration.IsNull()) - { - Log($"there is no provided configurations, using default ..."); - configuration = new XTermsAndConditionsServiceConfiguration(); - } - - // - services.AddSingleton(configuration); - } - - /// - /// Register TermsConditions Provider ... - /// - /// - /// provided AppSettings Configuration - /// - public static void AddXTermsConditionsService( - this IServiceCollection services, - IConfiguration configuration, - ServiceLifetime lifeTime = ServiceLifetime.Transient - ) - { - // - AddTermsAndConditionsService( - services: services, - lifeTime: lifeTime, - configuration: configuration - ); - } - - /// - /// Register TermsConditions Provider ... - /// - /// - /// provided xTermsAndConditionsService Configuration - /// - public static void AddXTermsConditionsService( - this IServiceCollection services, - XTermsAndConditionsServiceConfiguration configuration, - ServiceLifetime lifeTime = ServiceLifetime.Transient - ) - { - // - AddTermsAndConditionsService( - services: services, - lifeTime: lifeTime, - serviceConfiguration: configuration - ); - } - - public static void UseXTermsAndConditionsService( - this IApplicationBuilder app - ) - { - // - // Create an Scope for Services Acess ... - using (var scope = app.ApplicationServices.CreateScope()) - { - // - // Inject Requirements ... - var stringProvider = scope.ServiceProvider.GetService(); - var serviceConfiguration = scope.ServiceProvider.GetService(); - - // - // Using XTerms Hub ... - var pushHelper = new XPushServiceHelper(); - pushHelper.AddHub("terms"); - app.UseXPushService(pushHelper); - - // - // Validate Requirements Exists ... - var isValid = - !stringProvider.IsNull() && - !serviceConfiguration.IsNull() && - !serviceConfiguration.TermsAndConditions.IsNull() && - serviceConfiguration.TermsAndConditions.HasChild() && - serviceConfiguration.SeedingMode != xDataService.Constants.XDbSeedingMode.None; - if (isValid) - { - // - // Prepare Default Terms ... - serviceConfiguration - .TermsAndConditions - .ToList() - .ForEach(t => t.ResourceTitle = serviceConfiguration.ResourceTitle); - - // - // Loop through Terms and Conditions for Seeding ... - foreach (var item in serviceConfiguration.TermsAndConditions) - { - // - // Detect Exists Item ... - var exists = stringProvider.FindOneAsync( - predicate: x => - x.Language == item.Language && - x.ResourceTitle == item.ResourceTitle - ) - .GetAwaiter() - .GetResult(); - - // - var isExists = !exists.IsNullOrDefault(); - - // - switch (serviceConfiguration.SeedingMode) - { - // - case xDataService.Constants.XDbSeedingMode.AddOrUpdate: - // - // Update Exists by new Provided ... - exists.TranslatedValue = item.TranslatedValue; - exists = stringProvider.UpdateAsync( - id: exists.Id, - item: exists, - saveChanges: true - ) - .GetAwaiter() - .GetResult(); - - // - Log($"Refresh Terms and Conditions of {exists.Language}"); - break; - - // - case xDataService.Constants.XDbSeedingMode.AddIfNotExists: - // - if (!isExists) - { - // - exists = stringProvider.AddAsync( - item: item, - saveChanges: true - ) - .GetAwaiter() - .GetResult(); - - // - Log($"Add Terms and Conditions for {exists.Language}"); - } - break; - } - } - } - } - } - - // - #region Private ... - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XTermsAndConditionsServiceConstants.XTermsAndConditionsServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Add Terms and Conditions Provider Service ... - /// - /// - /// - private static void AddTermsAndConditionsService( - IServiceCollection services, - IConfiguration configuration = null, - XTermsAndConditionsServiceConfiguration serviceConfiguration = null, - ServiceLifetime lifeTime = ServiceLifetime.Transient - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("AddTermsAndConditions failed, services not provided ..."); - throw exception; - } - - // - // Validate Configuration ... - var isConfigValid = !configuration.IsNull() || !serviceConfiguration.IsNull(); - if (!isConfigValid) - { - // - Log("AddTermsAndConditions failed, configuration not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("AddTermsAndConditions failed, lifetime not provided ..."); - throw exception; - } - - // - // Check Dependencies Exists ... - var isDependenciesPassed = !services - .GetRegisteredService() - .IsNull() && - !services.GetRegisteredService() - .IsNull(); - if (!isDependenciesPassed) - { - // - Log("AddTermsAndConditions failed due Dependencies Issues, IXStringServiceProvider or XAppConfiguration not provided ..."); - throw exception; - } - - // - // Service Configuration Handler ... - if (serviceConfiguration.IsNull()) - { - serviceConfiguration = configuration.GetXTermsAndConditionsServiceConfiguration(); - } - services.AddXTermsAndConditionsConfiguration(serviceConfiguration); - - // - // Register Resource Providers ... - services.Add(new ServiceDescriptor(typeof(IXTermsAndConditionsProvider), typeof(XTermsAndConditionsProvider), lifeTime)); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Hubs\XTermsHub.cs - -using System.Threading; -using xPushService.Base; -using xCommons.Extensions; -using System.Threading.Tasks; -using xPushService.Constants; -using xStringService.Models.Dtos; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.Logging; - -namespace xTermsAndConditionsService.Hubs -{ - /// - /// a Hub for Notifing Terms and Conditions Events to Connected Clients ... - /// - public class XTermsHub : XBaseHub - { - public XTermsHub( - ILogger logger - ) : base(logger) - { - } - - // - #region Hub Actions ... - /// - /// Add Specified Terms and Conditions ... - /// - /// - /// - /// - public async Task Add( - XStringDto entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Add.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Deleted Specified Terms and Conditions ... - /// - /// - /// - /// - public async Task Delete( - XStringDto entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Delete.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Entity Updated ... - /// - /// - /// - /// - public async Task Update( - XStringDto entity, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XBaseEntityHubAction.Update.GetStringValue(), - entity.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Interfaces\IXTermsAndConditionsController.cs - -using xStringService.Interfaces; - -namespace xTermsAndConditionsService.Interfaces -{ - /// - /// an Interface for Describing Terms and Conditions Management Controller Actions ... - /// - public interface IXTermsAndConditionsController : IXBaseResourceProviderController - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Interfaces\IXTermsAndConditionsProvider.cs - -using xStringService.Interfaces; - -namespace xTermsAndConditionsService.Interfaces -{ - /// - /// an Interface for Describing Terms and Conditions Management Provided Actions ... - /// - public interface IXTermsAndConditionsProvider : IXResourceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xTermsAndConditionsService\Providers\XTermsAndConditionsProvider.cs - -using xStringService.Providers; -using xStringService.Interfaces.Dtos; -using xTermsAndConditionsService.Interfaces; -using xTermsAndConditionsService.Configurations; - -namespace xTermsAndConditionsService.Providers -{ - /// - /// an Implementation of Terms and Conditions Management Provided Actions ... - /// - public class XTermsAndConditionsProvider : XBaseResourceProvider, IXTermsAndConditionsProvider - { - public XTermsAndConditionsProvider( - IXStringServiceProvider provider, - XTermsAndConditionsServiceConfiguration configuration - ) : base( - resource: "NULL", - provider - ) - { - // - // Since we nee to Set Resource Title of Terms and Conditions - // during instancing using Provided Configurations ... - // set this value here ... - resource = configuration.ResourceTitle; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xWebinarService-20261109_152621.txt b/Documents/GeneratedContext/xDashboard-xWebinarService-20261109_152621.txt deleted file mode 100644 index 3363577..0000000 --- a/Documents/GeneratedContext/xDashboard-xWebinarService-20261109_152621.txt +++ /dev/null @@ -1,2038 +0,0 @@ - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Configurations\Entities\XWebinarEntityConfiguration.cs - -using System; -using xDataService.Providers; -using xWebinarService.Constants; -using Microsoft.EntityFrameworkCore; -using xWebinarService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xWebinarService.Configurations.Entities -{ - public class XWebinarEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XWebinarServiceConstants.XWebinarTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Configurations\Entities\XWebinarSubscriberEntityConfiguration.cs - -using xDataService.Providers; -using xWebinarService.Constants; -using Microsoft.EntityFrameworkCore; -using xWebinarService.Models.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace xWebinarService.Configurations.Entities -{ - public class XWebinarSubscriberEntityConfiguration : XBaseEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable(XWebinarServiceConstants.XWebinarSubscriberTable); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Constants\XWebinarServiceConstants.cs - -namespace xWebinarService.Constants -{ - public struct XWebinarServiceConstants - { - // - // Service Extensions Log Tag ... - public const string XWebinarServiceDILogTag = "XWebinarService"; - - // - // Table Mapping Identifiers ... - public const string XWebinarTable = "Webinars"; - public const string XWebinarSubscriberTable = "WebinarSubscribers"; - - // - // GraphQL Collection Mappings ... - public const string XWebinarSingleName = "webinar"; - public const string XWebinarCollectionName = "webinars"; - - public const string XWebinarSubscriberSingleName = "webinarSubscriber"; - public const string XWebinarSubscriberCollectionName = "webinarSubscribers"; - - // - // Hubs ... - public const string XWebinarDtoHub = "webinarDto"; - public const string XWebinarEntityHub = "webinarEntity"; - public const string XWebinarSubscriberDtoHub = "webinarSubscriberDto"; - public const string XWebinarSubscriberEntityHub = "webinarSubscriberEntity"; - - // - // Custome Constants ... - - // - // EF Repositories Helper Extensions ... - public const string GetXWebinarEFRepositoryDescriptor = "GetXWebinarEFRepositoryDescriptor"; - public const string GetXWebinarSubscriberEFRepositoryDescriptor = "GetXWebinarSubscriberEFRepositoryDescriptor"; - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Constants\XWebinarType.cs - -using xExceptions.Attributes; - -namespace xWebinarService.Constants -{ - /// - /// Webinar Type ... - /// - public enum XWebinarType - { - [StringValue("Public")] - Public = 0, - [StringValue("Private")] - Private = 1 - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\DI\XDIHelperExtension.cs - -using System; -using xDataService.Db; -using xDataService.DI; -using xPushService.DI; -using xCommons.Helpers; -using xCommons.Extensions; -using xDataService.Models; -using xPushService.Helpers; -using xExceptions.Constants; -using xDataService.Constants; -using xWebinarService.Helpers; -using xWebinarService.Constants; -using Microsoft.AspNetCore.Builder; -using xWebinarService.Providers.Dtos; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Providers.Entities; -using xWebinarService.Interfaces.Entities; -using Microsoft.Extensions.DependencyInjection; - -namespace xWebinarService.DI -{ - public static class XDIHelperExtension - { - /// - /// Register Service ... - /// - /// - /// - /// - public static void AddXWebinarService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - AddWebinarService( - contextType: null, - services: services, - lifeTime: lifeTime, - repositoryType: repositoryType - ); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - public static void AddXWebinarService( - this IServiceCollection services, - XRepositoryType repositoryType, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - where TContext : XDbContext - { - AddWebinarService( - services: services, - lifeTime: lifeTime, - contextType: typeof(TContext), - repositoryType: repositoryType - ); - } - - /// - /// Use XWebinarService Middleware ... - /// - /// - /// - public static void UsexWebinarService( - this IApplicationBuilder app, - bool isDevelopmentEnvironment = false - ) - { - // - #region Using XWebinar Hubs ... - // - var pushHelper = new XPushServiceHelper(); - - // - pushHelper.AddHub(XWebinarServiceConstants.XWebinarDtoHub); - pushHelper.AddHub(XWebinarServiceConstants.XWebinarEntityHub); - - // - pushHelper.AddHub(XWebinarServiceConstants.XWebinarSubscriberDtoHub); - pushHelper.AddHub(XWebinarServiceConstants.XWebinarSubscriberEntityHub); - - // - app.UseXPushService(pushHelper); - #endregion - - // - // Using XWebinar Repository Descriptor ... - if (!webinarDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: webinarDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - - // - // Using XWebinarSubscriber Repository Descriptor ... - if (!webinarSubscriberDescriptor.IsNull()) - { - // - app.UseXRepository( - descriptor: webinarSubscriberDescriptor, - isDevelopmentEnvironment: isDevelopmentEnvironment - ); - } - } - - // - #region Private ... - private static XRepositoryDescriptor webinarDescriptor = null; - private static XRepositoryDescriptor webinarSubscriberDescriptor = null; - - /// - /// a LogTag for Service ... - /// - private static string XLogTag = XWebinarServiceConstants.XWebinarServiceDILogTag; - - /// - /// print a log in Console ... - /// - /// - private static void Log(string message) - { - Console.WriteLine($"{XLogTag} => {message}"); - } - - /// - /// Register Service ... - /// - /// - /// - /// - /// - private static void AddWebinarService( - IServiceCollection services, - XRepositoryType repositoryType, - Type contextType = null, - ServiceLifetime lifeTime = ServiceLifetime.Scoped - ) - { - // - var exception = XException.InvalidArgs.ToException(); ; - - // - // Services ... - var isServicesExists = !services.IsNull(); - if (!isServicesExists) - { - // - Log("Service Registration failed, services not provided ..."); - throw exception; - } - - // - // Lifetime ... - var isLifetimeExists = !lifeTime.IsNull(); - if (!isLifetimeExists) - { - // - Log("Service Registration failed, lifetime not provided ..."); - throw exception; - } - - // - // Validate Repository Type ... - var isRepositoryTypeValid = - (repositoryType == XRepositoryType.EF && - !contextType.IsNull()) || - ((repositoryType == XRepositoryType.Mongo || - repositoryType == XRepositoryType.InMemory) && - contextType.IsNull()); - if (!isRepositoryTypeValid) - { - // - Log("Service Registration failed, Invalid Repository Type and Context Type ..."); - throw exception; - } - - // - // Maske Instance of Repository Descriptor - // Based on Provided Type ... - switch (repositoryType) - { - // - case XRepositoryType.EF: - // - webinarDescriptor = typeof(XWebinarServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XWebinarServiceConstants.GetXWebinarEFRepositoryDescriptor - ); - - // - webinarSubscriberDescriptor = typeof(XWebinarServiceHelper) - .InvokeGenericMethod( - args: null, - runtimeType: contextType, - methodName: XWebinarServiceConstants.GetXWebinarSubscriberEFRepositoryDescriptor - ); - break; - - // - case XRepositoryType.Mongo: - webinarDescriptor = XWebinarServiceHelper.GetXWebinarMongoRepositoryDescriptor(); - webinarSubscriberDescriptor = XWebinarServiceHelper.GetXWebinarSubscriberMongoRepositoryDescriptor(); - break; - - // - case XRepositoryType.InMemory: - webinarDescriptor = XWebinarServiceHelper.GetXWebinarInMemoryRepositoryDescriptor(); - webinarSubscriberDescriptor = XWebinarServiceHelper.GetXWebinarSubscriberInMemoryRepositoryDescriptor(); - break; - } - - // - // Register xWebinar Repository Descriptor ... - services.AddXRepository( - lifeTime: lifeTime, - descriptor: webinarDescriptor - ); - - services.AddXRepository( - lifeTime: lifeTime, - descriptor: webinarSubscriberDescriptor - ); - - // - // Register Dto Services ... - services.Add( - new ServiceDescriptor(typeof(IXWebinarServiceProvider), typeof(XWebinarServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXWebinarRepositoryService), typeof(XWebinarRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXWebinarRepositoryProvider), typeof(XWebinarRepositoryProvider), lifeTime) - ); - - services.Add( - new ServiceDescriptor(typeof(IXWebinarSubscriberServiceProvider), typeof(XWebinarSubscriberServiceProvider), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXWebinarSubscriberRepositoryService), typeof(XWebinarSubscriberRepositoryService), lifeTime) - ); - services.Add( - new ServiceDescriptor(typeof(IXWebinarSubscriberRepositoryProvider), typeof(XWebinarSubscriberRepositoryProvider), lifeTime) - ); - - // - // services.Add( - // new ServiceDescriptor(typeof(IXWebinarProvider), typeof(XWebinarProvider), lifeTime) - // ); - - // - Log("Service Regitration Succeed ..."); - } - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Helpers\XWebinarServiceHelper.cs - -using System; -using GraphQL.Types; -using xDataService.Db; -using xDataService.Models; -using xDataService.Providers; -using xWebinarService.Models.Entities; -using xWebinarService.Providers.GraphQL; -using xWebinarService.Providers.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Helpers -{ - public static class XWebinarServiceHelper - { - // - #region XWebinar ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarEFRepository, - TContext - > GetXWebinarEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarEFRepository, - TContext, - IXWebinarSeeder, - TSeederImplementation - > GetXWebinarEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarEFRepository, - TContext, - IXWebinarSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarMongoRepository - > GetXWebinarMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarMongoRepository, - IXWebinarSeeder, - TSeederImplementation - > GetXWebinarMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarMongoRepository, - IXWebinarSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarInMemoryRepository - > GetXWebinarInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarInMemoryRepository, - IXWebinarSeeder, - TSeederImplementation - > GetXWebinarInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XWebinar, - Guid, - IXWebinarKeyGenerator, - XWebinarKeyGenerator, - IXWebinarRepositoryEvents, - XWebinarRepositoryEvents, - XWebinarGraphType, - GuidGraphType, - XWebinarGraphQuery, - IXWebinarGraphQLTypeHelper, - XWebinarGraphQLTypeHelper, - XWebinarGraphSchema, - IXWebinarRepository, - XWebinarInMemoryRepository, - IXWebinarSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - - // - #region XWebinarSubscriber ... - // - #region EF Repository Descriptor Provider(s) ... - public static XEFRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberEFRepository, - TContext - > GetXWebinarSubscriberEFRepositoryDescriptor() - where TContext : XDbContext - { - // - var result = new XEFRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberEFRepository, - TContext - >(); - - // - return result; - } - - public static XEFRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberEFRepository, - TContext, - IXWebinarSubscriberSeeder, - TSeederImplementation - > GetXWebinarSubscriberEFRepositoryDescriptor() - where TContext : XDbContext - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XEFRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberEFRepository, - TContext, - IXWebinarSubscriberSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region Mongo Repository Descriptor Provider(s) ... - public static XMongoRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberMongoRepository - > GetXWebinarSubscriberMongoRepositoryDescriptor() - { - // - var result = new XMongoRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberMongoRepository - >(); - - // - return result; - } - - public static XMongoRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberMongoRepository, - IXWebinarSubscriberSeeder, - TSeederImplementation - > GetXWebinarSubscriberMongoRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XMongoRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberMongoRepository, - IXWebinarSubscriberSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - - // - #region InMemory Repository Descriptor Provider(s) ... - public static XInMemoryRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberInMemoryRepository - > GetXWebinarSubscriberInMemoryRepositoryDescriptor() - { - // - var result = new XInMemoryRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberInMemoryRepository - >(); - - // - return result; - } - - public static XInMemoryRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberInMemoryRepository, - IXWebinarSubscriberSeeder, - TSeederImplementation - > GetXWebinarSubscriberInMemoryRepositoryDescriptor() - where TSeederImplementation : XBaseDbSeeder - { - // - var result = new XInMemoryRepositoryDescriptor< - XWebinarSubscriber, - int, - IXWebinarSubscriberKeyGenerator, - XWebinarSubscriberKeyGenerator, - IXWebinarSubscriberRepositoryEvents, - XWebinarSubscriberRepositoryEvents, - XWebinarSubscriberGraphType, - IntGraphType, - XWebinarSubscriberGraphQuery, - IXWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphQLTypeHelper, - XWebinarSubscriberGraphSchema, - IXWebinarSubscriberRepository, - XWebinarSubscriberInMemoryRepository, - IXWebinarSubscriberSeeder, - TSeederImplementation - >(); - - // - return result; - } - #endregion - #endregion - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarDtoHub.cs - -using System; -using xPushService.Interfaces; -using xWebinarService.Models.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarRepositoryService.cs - -using System; -using xDataService.Interfaces; -using xWebinarService.Models.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarServiceProvider.cs - -using System; -using xPushService.Interfaces; -using xWebinarService.Models.Dtos; -using xWebinarService.Providers.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarServiceProvider : IXBaseDtoProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarSubscriberDtoHub.cs - -using xPushService.Interfaces; -using xWebinarService.Models.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarSubscriberDtoHub : IXBaseDtoHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarSubscriberRepositoryService.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarSubscriberRepositoryService : IXBaseRepositoryService - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Dtos\IXWebinarSubscriberServiceProvider.cs - -namespace xWebinarService.Interfaces.Dtos -{ - public interface IXWebinarSubscriberServiceProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarEntityHub.cs - -using System; -using xPushService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarGraphQLTypeHelper.cs - -using System; -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarKeyGenerator.cs - -using System; -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarRepository.cs - -using System; -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarRepositoryEvents.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarRepositoryProvider.cs - -using System; -using xPushService.Interfaces; -using xWebinarService.Models.Entities; -using xWebinarService.Providers.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSeeder.cs - -using System; -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberEntityHub.cs - -using xPushService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberEntityHub : IXBaseEntityHub - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberGraphQLTypeHelper.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberGraphQLTypeHelper : IXBaseGraphQLTypeHelper - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberKeyGenerator.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberKeyGenerator : IXKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberRepository.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberRepository : IXBaseRepository - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberRepositoryEvents.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberRepositoryEvents : IXBaseRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberRepositoryProvider.cs - -using xPushService.Interfaces; -using xWebinarService.Models.Entities; -using xWebinarService.Providers.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberRepositoryProvider : IXBaseEntityProvider - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Interfaces\Entities\IXWebinarSubscriberSeeder.cs - -using xDataService.Interfaces; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Interfaces.Entities -{ - public interface IXWebinarSubscriberSeeder : IXBaseDbSeeder - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Models\Dtos\XWebinarDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; -using xWebinarService.Constants; - -namespace xWebinarService.Models.Dtos -{ - public class XWebinarDto : XBaseGuidIDEntityDto - { - public bool Enabled { get; set; } - public string OwnerId { get; set; } - public XPersonDto Owner { get; set; } - public XWebinarType Type { get; set; } - public XResourceDto Title { get; set; } - public DateTime CreatedOn { get; set; } - public XResourceDto Description { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Models\Dtos\XWebinarSubscriberDto.cs - -using System; -using xModels.Base; -using xModels.Dtos; - -namespace xWebinarService.Models.Dtos -{ - public class XWebinarSubscriberDto : XBaseIntIDEntityDto - { - public Guid WebinarId { get; set; } - public string SubscriberId { get; set; } - public XPersonDto Subscriber { get; set; } - public DateTime SubscribedOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Models\Entities\XWebinar.cs - -using System; -using xModels.Base; -using xWebinarService.Constants; -using System.ComponentModel.DataAnnotations; - -namespace xWebinarService.Models.Entities -{ - /// - /// Webinar Entity ... - /// - public class XWebinar : XBaseGuidIDEntity - { - /// - /// Title (Resource ID) ... - /// - /// - [Required] - [StringLength(255)] - public string Title { get; set; } - - /// - /// Description (Resource ID) ... - /// - /// - [Required] - [StringLength(255)] - public string Description { get; set; } - - /// - /// User Identifier ... - /// - /// - [Required] - public string OwnerId { get; set; } - - /// - /// Webinar Type ... - /// - public XWebinarType Type { get; set; } - - /// - /// Creation Time ... - /// - /// - [Required] - public DateTime CreatedOn { get; set; } - - /// - /// Specified Webinar Enabled or not ... - /// - /// - public bool Enabled { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Models\Entities\XWebinarSubscriber.cs - -using System; -using xModels.Base; -using System.ComponentModel.DataAnnotations; - -namespace xWebinarService.Models.Entities -{ - /// - /// Webinar Subscriber ... - /// - public class XWebinarSubscriber : XBaseIntIDEntity - { - [Required] - public string SubscriberId { get; set; } - - [Required] - public Guid WebinarId { get; set; } - - public DateTime SubscribedOn { get; set; } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\XWebinarEntityRegisterar.cs - -using System; -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xWebinarService.Models.Entities; -using xWebinarService.Configurations.Entities; - -namespace xWebinarService.Providers -{ - public class XWebinarEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XWebinarEntityRegisterar() - : base(nameof(XWebinarEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XWebinarEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\XWebinarSubscriberEntityRegisterar.cs - -using xDataService.Providers; -using xDataService.Interfaces; -using Microsoft.EntityFrameworkCore; -using xWebinarService.Models.Entities; -using xWebinarService.Configurations.Entities; - -namespace xWebinarService.Providers -{ - public class XWebinarSubscriberEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar - { - public XWebinarSubscriberEntityRegisterar() - : base(nameof(XWebinarSubscriberEntityRegisterar)) - { - // - // Add Entity ... - AddEntity(); - } - - /// - /// Configure Entities ... - /// - /// - public override void ConfigureEntities(ModelBuilder modelBuilder) - { - // - // Configure Entity Using Provided ... - modelBuilder - .ApplyConfigurationsFromAssembly(typeof(XWebinarSubscriberEntityConfiguration).Assembly); - - // - base.ConfigureEntities(modelBuilder); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarDtoHub.cs - -using System; -using xPushService.Base; -using xWebinarService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarDtoHub : XBaseDtoHub, IXWebinarDtoHub - { - public XWebinarDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarRepositoryService.cs - -using System; -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xWebinarService.Models.Dtos; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarRepositoryService : XBaseRepositoryService, IXWebinarRepositoryService - { - public XWebinarRepositoryService( - IXWebinarRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarServiceProvider.cs - -using System; -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xWebinarService.Models.Dtos; -using Microsoft.AspNetCore.SignalR; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarServiceProvider : XBaseDtoProvider, IXWebinarServiceProvider - { - public XWebinarServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXWebinarRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarSubscriberDtoHub.cs - -using xPushService.Base; -using xWebinarService.Models.Dtos; -using Microsoft.Extensions.Logging; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarSubscriberDtoHub : XBaseDtoHub, IXWebinarSubscriberDtoHub - { - public XWebinarSubscriberDtoHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarSubscriberRepositoryService.cs - -using AutoMapper; -using xDataService.Providers; -using System.Collections.Generic; -using xWebinarService.Models.Dtos; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarSubscriberRepositoryService : XBaseRepositoryService, IXWebinarSubscriberRepositoryService - { - public XWebinarSubscriberRepositoryService( - IXWebinarSubscriberRepository repository, - IEnumerable mapperProfiles = null - ) : base( - repository, - mapperProfiles - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Dtos\XWebinarSubscriberServiceProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using xWebinarService.Models.Dtos; -using Microsoft.AspNetCore.SignalR; -using xWebinarService.Interfaces.Dtos; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.Dtos -{ - public class XWebinarSubscriberServiceProvider : XBaseDtoProvider, IXWebinarSubscriberServiceProvider - { - public XWebinarSubscriberServiceProvider( - IHubContext hub, - XDataServiceConfiguration dataConfiguration, - IXWebinarSubscriberRepositoryService service, - IXIdentityProvider identityProvider = null - ) : base( - hub, - dataConfiguration, - service, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarEFRepository.cs - -using System; -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarEFRepository : XBaseEFRepository, IXWebinarRepository - where TContext : XDbContext - { - public XWebinarEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXWebinarKeyGenerator keyGenerator = null, - IXWebinarRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarEntityHub.cs - -using System; -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarEntityHub : XBaseEntityHub, IXWebinarEntityHub - { - public XWebinarEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarInMemoryRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarInMemoryRepository : XBaseInMemoryRepository, IXWebinarRepository - { - public XWebinarInMemoryRepository( - XDataServiceConfiguration configuration, - IXWebinarKeyGenerator keyGenerator = null, - IXWebinarRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarKeyGenerator.cs - -using xDataService.Providers; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarKeyGenerator : XGuidKeyGenerator, IXWebinarKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarMongoRepository.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarMongoRepository : XBaseMongoRepository, IXWebinarRepository - { - public XWebinarMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXWebinarKeyGenerator keyGenerator = null, - IXWebinarRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarRepositoryEvents.cs - -using xDataService.Providers; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarRepositoryEvents : XBaseRepositoryEvents, IXWebinarRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarRepositoryProvider.cs - -using System; -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarRepositoryProvider : XBaseEntityProvider, IXWebinarRepositoryProvider - { - public XWebinarRepositoryProvider( - IHubContext hub, - IXWebinarRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSeederBase.cs - -using System; -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public abstract class XWebinarSeederBase : XBaseDbSeeder, IXWebinarSeeder - { - public XWebinarSeederBase( - string entity, - string database, - IXWebinarRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberEFRepository.cs - -using xDataService.Db; -using xDataService.Providers; -using xDataService.Interfaces; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberEFRepository : XBaseEFRepository, IXWebinarSubscriberRepository - where TContext : XDbContext - { - public XWebinarSubscriberEFRepository( - IXUnitOfWorks unitOfWorks, - XDataServiceConfiguration configuration, - IXWebinarSubscriberKeyGenerator keyGenerator = null, - IXWebinarSubscriberRepositoryEvents baseRepositoryEvents = null - ) : base( - unitOfWorks, - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberEntityHub.cs - -using xPushService.Base; -using Microsoft.Extensions.Logging; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberEntityHub : XBaseEntityHub, IXWebinarSubscriberEntityHub - { - public XWebinarSubscriberEntityHub( - ILogger logger - ) : base(logger) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberInMemoryRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberInMemoryRepository : XBaseInMemoryRepository, IXWebinarSubscriberRepository - { - public XWebinarSubscriberInMemoryRepository( - XDataServiceConfiguration configuration, - IXWebinarSubscriberKeyGenerator keyGenerator = null, - IXWebinarSubscriberRepositoryEvents baseRepositoryEvents = null - ) : base( - configuration, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberKeyGenerator.cs - -using xDataService.Providers; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberKeyGenerator : XIntKeyGenerator, IXWebinarSubscriberKeyGenerator - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberMongoRepository.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberMongoRepository : XBaseMongoRepository, IXWebinarSubscriberRepository - { - public XWebinarSubscriberMongoRepository( - XDataBaseConfiguration dbConfiguration, - XDataServiceConfiguration configuration, - string collectionName = null, - IXWebinarSubscriberKeyGenerator keyGenerator = null, - IXWebinarSubscriberRepositoryEvents baseRepositoryEvents = null - ) : base( - dbConfiguration, - configuration, - collectionName, - keyGenerator, - baseRepositoryEvents - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberRepositoryEvents.cs - -using xDataService.Providers; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberRepositoryEvents : XBaseRepositoryEvents, IXWebinarSubscriberRepositoryEvents - { } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberRepositoryProvider.cs - -using xPushService.Base; -using xDataService.Configuration; -using xIdentityService.Interfaces; -using Microsoft.AspNetCore.SignalR; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public class XWebinarSubscriberRepositoryProvider : XBaseEntityProvider, IXWebinarSubscriberRepositoryProvider - { - public XWebinarSubscriberRepositoryProvider( - IHubContext hub, - IXWebinarSubscriberRepository repository, - XDataServiceConfiguration dataConfiguration, - IXIdentityProvider identityProvider = null - ) : base( - hub, - repository, - dataConfiguration, - identityProvider - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\Entities\XWebinarSubscriberSeederBase.cs - -using xDataService.Providers; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.Entities -{ - public abstract class XWebinarSubscriberSeederBase : XBaseDbSeeder, IXWebinarSubscriberSeeder - { - public XWebinarSubscriberSeederBase( - string entity, - string database, - IXWebinarSubscriberRepository repository, - XDataServiceConfiguration dataServiceConfiguration - ) : base( - entity, - database, - repository, - dataServiceConfiguration - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarGraphQLTypeHelper.cs - -using System; -using xDataService.GraphQL; -using xWebinarService.Constants; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXWebinarGraphQLTypeHelper - { - public XWebinarGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XWebinarServiceConstants.XWebinarCollectionName; - } - - public override string GetInQuerySingleName() - { - return XWebinarServiceConstants.XWebinarSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarGraphQuery.cs - -using System; -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarGraphQuery : XBaseGraphQLQuery - { - public XWebinarGraphQuery( - XDataServiceConfiguration configuration, - IXWebinarRepository repository, - IXWebinarGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarGraphSchema : Schema - { - public XWebinarGraphSchema(IServiceProvider services) : base(services) - { - Query = (XWebinarGraphQuery)services.GetService(typeof(XWebinarGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarGraphType.cs - -using System; -using xDataService.GraphQL; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarGraphType : XBaseGraphObjectType - { - public XWebinarGraphType() : base() - { - Field(x => x.Type); - Field(x => x.Title); - Field(x => x.OwnerId); - Field(x => x.Enabled); - Field(x => x.CreatedOn); - Field(x => x.Description); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarSubscriberGraphQLTypeHelper.cs - -using xDataService.GraphQL; -using xWebinarService.Constants; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarSubscriberGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXWebinarSubscriberGraphQLTypeHelper - { - public XWebinarSubscriberGraphQLTypeHelper( - XDataServiceConfiguration configuration - ) : base(configuration) - { } - - public override string GetInQueryCollectionName() - { - return XWebinarServiceConstants.XWebinarSubscriberCollectionName; - } - - public override string GetInQuerySingleName() - { - return XWebinarServiceConstants.XWebinarSubscriberSingleName; - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarSubscriberGraphQuery.cs - -using GraphQL.Types; -using xDataService.GraphQL; -using xDataService.Configuration; -using xWebinarService.Models.Entities; -using xWebinarService.Interfaces.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarSubscriberGraphQuery : XBaseGraphQLQuery - { - public XWebinarSubscriberGraphQuery( - XDataServiceConfiguration configuration, - IXWebinarSubscriberRepository repository, - IXWebinarSubscriberGraphQLTypeHelper helper - ) : base( - configuration, - repository, - helper - ) - { } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarSubscriberGraphSchema.cs - -using System; -using GraphQL.Types; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarSubscriberGraphSchema : Schema - { - public XWebinarSubscriberGraphSchema(IServiceProvider services) : base(services) - { - Query = (XWebinarSubscriberGraphQuery)services.GetService(typeof(XWebinarSubscriberGraphQuery)); - } - } -} - -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xWebinarService\Providers\GraphQL\XWebinarSubscriberGraphType.cs - -using xDataService.GraphQL; -using xWebinarService.Models.Entities; - -namespace xWebinarService.Providers.GraphQL -{ - public class XWebinarSubscriberGraphType : XBaseGraphObjectType - { - public XWebinarSubscriberGraphType() : base() - { - Field(x => x.WebinarId); - Field(x => x.SubscribedOn); - Field(x => x.SubscriberId); - } - } -} diff --git a/Documents/OpenApi/Swagger/xApi-swagger.json b/Documents/OpenApi/Swagger/xApi-swagger.json index 70101b6..cb51d99 100644 --- a/Documents/OpenApi/Swagger/xApi-swagger.json +++ b/Documents/OpenApi/Swagger/xApi-swagger.json @@ -12943,6 +12943,240 @@ } } } + }, + "/api/v{version}/XBotProvider/Me": { + "get": { + "tags": [ + "XBotProvider" + ], + "parameters": [ + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string", + "default": "1.0" + } + }, + { + "name": "X-PoweredBy", + "in": "header", + "description": "a Basic Authorization Filter", + "schema": { + "type": "String", + "default": "SaherElmITCenter" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/XBotResUser" + } + } + } + } + } + } + }, + "/api/v{version}/XBotProvider/Updates": { + "get": { + "tags": [ + "XBotProvider" + ], + "parameters": [ + { + "name": "Limit", + "in": "query", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "Offset", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "Timeout", + "in": "query", + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string", + "default": "1.0" + } + }, + { + "name": "X-PoweredBy", + "in": "header", + "description": "a Basic Authorization Filter", + "schema": { + "type": "String", + "default": "SaherElmITCenter" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/XBotUpdateResponse" + } + } + } + } + } + } + } + }, + "/api/v{version}/XBotProvider/Message": { + "post": { + "tags": [ + "XBotProvider" + ], + "parameters": [ + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string", + "default": "1.0" + } + }, + { + "name": "X-PoweredBy", + "in": "header", + "description": "a Basic Authorization Filter", + "schema": { + "type": "String", + "default": "SaherElmITCenter" + } + } + ], + "requestBody": { + "content": { + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/XBotSendMessageRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/XBotSendMessageRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/XBotSendMessageRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/XBotSendMessageRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/XBotMessage" + } + } + } + } + } + } + }, + "/api/v{version}/XBotProvider/Test/Hi": { + "get": { + "tags": [ + "XBotProvider" + ], + "summary": "Check the Controller Up and Running", + "parameters": [ + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string", + "default": "1.0" + } + }, + { + "name": "X-PoweredBy", + "in": "header", + "description": "a Basic Authorization Filter", + "schema": { + "type": "String", + "default": "SaherElmITCenter" + } + } + ], + "responses": { + "200": { + "description": "Success" + } + } + } + }, + "/api/v{version}/XBotProvider/Test/PassRequireXPowered": { + "get": { + "tags": [ + "XBotProvider" + ], + "summary": "Check Controller ByPass XPowered Filter", + "parameters": [ + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "string", + "default": "1.0" + } + }, + { + "name": "X-PoweredBy", + "in": "header", + "description": "a Basic Authorization Filter", + "schema": { + "type": "String", + "default": "SaherElmITCenter" + } + } + ], + "responses": { + "200": { + "description": "Success" + } + } + } } }, "components": { @@ -14049,17 +14283,17 @@ "memberType": { "$ref": "#/components/schemas/MemberTypes" }, + "name": { + "type": "string", + "nullable": true, + "readOnly": true + }, "declaringType": { "$ref": "#/components/schemas/Type" }, "reflectedType": { "$ref": "#/components/schemas/Type" }, - "name": { - "type": "string", - "nullable": true, - "readOnly": true - }, "module": { "$ref": "#/components/schemas/Module" }, @@ -16020,6 +16254,241 @@ "type": "integer", "format": "int32" }, + "XBotCallbackQuery": { + "type": "object", + "properties": { + "id": { + "type": "string", + "nullable": true + }, + "data": { + "type": "string", + "nullable": true + }, + "user": { + "$ref": "#/components/schemas/XBotResUser" + }, + "message": { + "$ref": "#/components/schemas/XBotMessage" + } + }, + "additionalProperties": false, + "description": "a Callbacked From a Inline Keyboard ..." + }, + "XBotMessage": { + "type": "object", + "properties": { + "messageId": { + "type": "integer", + "format": "int64" + }, + "messageThreadId": { + "type": "integer", + "format": "int64" + }, + "from": { + "$ref": "#/components/schemas/XBotResUser" + }, + "date": { + "type": "integer", + "format": "int64" + }, + "chat": { + "nullable": true + }, + "senderChat": { + "nullable": true + }, + "forwardFrom": { + "$ref": "#/components/schemas/XBotResUser" + }, + "forwardFromChat": { + "nullable": true + }, + "forwardFromMessageId": { + "type": "integer", + "format": "int64" + }, + "forwardDate": { + "type": "integer", + "format": "int64" + }, + "replyToMessage": { + "$ref": "#/components/schemas/XBotMessage" + }, + "editDate": { + "type": "integer", + "format": "int64" + }, + "mediaGroupId": { + "type": "string", + "nullable": true + }, + "text": { + "type": "string", + "nullable": true + }, + "entities": { + "type": "array", + "items": { }, + "nullable": true + }, + "animation": { + "nullable": true + }, + "audio": { + "nullable": true + }, + "document": { + "nullable": true + }, + "photo": { + "type": "array", + "items": { }, + "nullable": true + }, + "sticker": { + "nullable": true + }, + "video": { + "nullable": true + }, + "voice": { + "nullable": true + }, + "caption": { + "type": "string", + "nullable": true + }, + "captionEntities": { + "type": "array", + "items": { }, + "nullable": true + }, + "contact": { + "nullable": true + }, + "location": { + "nullable": true + }, + "newChatMembers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/XBotResUser" + }, + "nullable": true + }, + "leftChatMember": { + "$ref": "#/components/schemas/XBotResUser" + }, + "invoice": { + "nullable": true + }, + "successfulPayment": { + "nullable": true + }, + "webAppData": { + "nullable": true + }, + "replyMarkup": { + "nullable": true + }, + "forumTopicCreated": { + "nullable": true + } + }, + "additionalProperties": false, + "description": "Represent a Bot MEssage ..." + }, + "XBotResUser": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "isBot": { + "type": "boolean" + }, + "lastName": { + "type": "string", + "nullable": true + }, + "username": { + "type": "string", + "nullable": true + }, + "firstName": { + "type": "string", + "nullable": true + }, + "languageCode": { + "type": "string", + "nullable": true + }, + "hasMainWebApp": { + "type": "string", + "nullable": true + }, + "hasTopicsEnabled": { + "type": "boolean" + }, + "allowsUsersToCreateTopics": { + "type": "boolean" + } + }, + "additionalProperties": false, + "description": "Represent XBot Response User ..." + }, + "XBotSendMessageRequest": { + "type": "object", + "properties": { + "chatId": { + "type": "integer", + "format": "int64" + }, + "text": { + "type": "string", + "nullable": true + }, + "replyMarkup": { + "nullable": true + }, + "messageThreadId": { + "type": "integer", + "format": "int64" + }, + "replyToMessageId": { + "type": "integer", + "format": "int64" + } + }, + "additionalProperties": false, + "description": "Bot Message Send Request ..." + }, + "XBotUpdateResponse": { + "type": "object", + "properties": { + "updateId": { + "type": "integer", + "format": "int64" + }, + "message": { + "$ref": "#/components/schemas/XBotMessage" + }, + "editedMessage": { + "$ref": "#/components/schemas/XBotMessage" + }, + "callbackQuery": { + "$ref": "#/components/schemas/XBotCallbackQuery" + }, + "preCheckoutQuery": { + "nullable": true + } + }, + "additionalProperties": false, + "description": "Represent an Event in Bot ..." + }, "XCategoryDto": { "type": "object", "properties": { diff --git a/Documents/Resources/Json/Requests.md b/Documents/Resources/Json/Requests.md index 8f69a7f..2d34b38 100644 --- a/Documents/Resources/Json/Requests.md +++ b/Documents/Resources/Json/Requests.md @@ -753,3 +753,130 @@ Response: } } ``` + +## Bot + +### Me + +```json +{ + "id": 57317004, + "is_bot": true, + "username": "xsaherelmbot", + "first_name": "xBaleBot", + "has_topics_enabled": false, + "allows_users_to_create_topics": false +} +``` + +### Updates + +```json +[ + { + "update_id": 1, + "message": { + "message_id": 1, + "message_thread_id": 0, + "from": { + "id": 1917703782, + "is_bot": false, + "last_name": "", + "first_name": "kimia ", + "has_topics_enabled": false, + "allows_users_to_create_topics": false + }, + "date": 1794469606, + "chat": { + "id": 1917703782, + "type": "private", + "first_name": "kimia " + }, + "forward_from_message_id": 0, + "forward_date": 0, + "edit_date": 0, + "text": "/start", + "entities": [ + { + "type": "bot_command", + "offset": 0, + "length": 6 + } + ] + } + }, + { + "update_id": 2, + "message": { + "message_id": 2, + "message_thread_id": 0, + "from": { + "id": 442637838, + "is_bot": false, + "last_name": "", + "first_name": "بهاره زرگر", + "has_topics_enabled": false, + "allows_users_to_create_topics": false + }, + "date": 1794484300, + "chat": { + "id": 442637838, + "type": "private", + "first_name": "بهاره زرگر" + }, + "forward_from_message_id": 0, + "forward_date": 0, + "edit_date": 0, + "text": "/start", + "entities": [ + { + "type": "bot_command", + "offset": 0, + "length": 6 + } + ] + } + } +] +``` + +### Message + +Request: + +```json +{ + "chatId": 442637838, + "text": "SaherElm IT Center Invites You to xBotProvider ...", + "replyMarkup": null, + "messageThreadId": 0, + "replyToMessageId": 0 +} +``` + +Response: + +```json +{ + "message_id": 4, + "message_thread_id": 0, + "from": { + "id": 57317004, + "is_bot": true, + "last_name": "", + "username": "xsaherelmbot", + "first_name": "", + "has_topics_enabled": false, + "allows_users_to_create_topics": false + }, + "date": 1794495172, + "chat": { + "id": 442637838, + "type": "private" + }, + "forward_from_message_id": 0, + "forward_date": 0, + "edit_date": 0, + "text": "SaherElm IT Center Invites You to xBotProvider ..." +} +``` diff --git a/Modules/xBotService b/Modules/xBotService index d3b5ba6..fa59823 160000 --- a/Modules/xBotService +++ b/Modules/xBotService @@ -1 +1 @@ -Subproject commit d3b5ba622fbad0148e5feafdc99e63f57b78a861 +Subproject commit fa598230084c5f1a5f88681c2a171af6ba733192 diff --git a/Modules/xHttpService b/Modules/xHttpService index 3f70731..3afe34e 160000 --- a/Modules/xHttpService +++ b/Modules/xHttpService @@ -1 +1 @@ -Subproject commit 3f707317bfa01652f2e3bb946548753295ae5b87 +Subproject commit 3afe34e438f27b9ad59322038c25c6d749a7135f diff --git a/Modules/xIdentityService b/Modules/xIdentityService index 89bc958..825e554 160000 --- a/Modules/xIdentityService +++ b/Modules/xIdentityService @@ -1 +1 @@ -Subproject commit 89bc95865ab405880d45b05f96b48db1b00b586f +Subproject commit 825e55487803699750918b3166a4185cb7b6744b diff --git a/Modules/xLoggingService b/Modules/xLoggingService index def0807..2308ec0 160000 --- a/Modules/xLoggingService +++ b/Modules/xLoggingService @@ -1 +1 @@ -Subproject commit def0807fdd5704c534b92b279eb6b1a801834af5 +Subproject commit 2308ec0be3d79f7f10362b892b8541ee66df1925 diff --git a/Modules/xServices b/Modules/xServices index 0a641f4..7885a6b 160000 --- a/Modules/xServices +++ b/Modules/xServices @@ -1 +1 @@ -Subproject commit 0a641f4117c5f9e4cf0a5c4e87170cb7f2ffe203 +Subproject commit 7885a6b629ee37997f775c8f03a65454505b1f45