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; 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); // foreach (var file in files) { // 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 ... var uploadedFile = await fileProvider.Upload( file: file, userInfo: userInfo, connectionId: connectionId, cancellationToken: cancellationToken ); // // Add Reference File to Prompt Message ... if (scope.ScopeId.HasValue) { // 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 ); } // 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 } }