public async Task <IActionResult> OnPostAsync() { System.Collections.Generic.IEnumerable <User> dbUsers = await userRepository.GetUsers(); if (dbUsers.Any(x => x.Username.ToLower() == User.Username.ToLower().Trim())) { HasError = true; ViewData["Error"] = "Υπάρχει ήδη χρήστης με Όνομα Χρήστη (Username) που δώσατε."; return(Page()); } if (dbUsers.Any(x => x.Email.ToLower() == User.Email.ToLower().Trim())) { HasError = true; ViewData["Error"] = "Υπάρχει ήδη χρήστης με την Ηλεκτρονική Διεύθυνση που δώσατε."; return(Page()); } User.Username = User.Username.Trim(); User.Email = User.Email.Trim(); User.Password = CrypterAlgorithm.ComputeSha256Hash(User.Password); if (await userRepository.InsertUser(User)) { HasError = false; TempData["SuccessMessage"] = "Ο Χρήστης προστέθηκε με επιτυχία."; return(RedirectToPage(Url.Content("~/Admin/UserList"))); } HasError = true; ViewData["Error"] = "Δεν μπορέσαμε να κάνουμε την εγγραφή προσπαθήστε ξανά"; return(Page()); }
/// <summary> /// Print the CommandLine help. /// </summary> /// <param name="parser">Parser used (CommandLine).</param> /// <param name="errs">Error list.</param> /// <param name="argv">argv list.</param> /// <typeparam name="T">The generic type parameter: Object to parser to get the usage.</typeparam> /// <returns>String usage.</returns> public string PrintHelp <T>(CommandLine.ParserResult <T> parser, System.Collections.Generic.IEnumerable <CommandLine.Error> errs, string[] argv) { // create logs if not already created CLILogs.CreateLoggers(); string helpText = PrintHelpErrorUsage(parser); ParseException ex = new ParseException(); // check if a "help" flag is used if (argv.Length > 1 && argv[1] == "help") { CLILogs.Usage(PrintHelpUsage(parser)); throw new ParseHelpException(); } if (errs == null) { CLILogs.Usage(helpText); throw ex; } if (errs.Any(x => x.Tag == CommandLine.ErrorType.VersionRequestedError)) { helpText = PrintHelpVersion(parser); ex = new ParseVersionException(); } else if (errs.Any(x => x.Tag == CommandLine.ErrorType.HelpRequestedError)) { helpText = PrintHelpUsage(parser); ex = new ParseHelpException(); } else if (errs.Any(x => x.Tag == CommandLine.ErrorType.HelpVerbRequestedError)) { helpText = PrintHelpVerbUsage(parser); ex = new ParseHelpException(); } else if (errs.Any(x => x.Tag == CommandLine.ErrorType.NoVerbSelectedError || x.Tag == CommandLine.ErrorType.BadVerbSelectedError)) { helpText = PrintHelpErrorVerbUsage(parser); string errorList = string.Empty; errs.ToList().ForEach(e => errorList += e.ToString()); ex = new ParseException(errorList); CLILogs.Debug("Parsing error : " + errorList); } else { string errorList = string.Empty; errs.ToList().ForEach(e => errorList += e.ToString()); ex = new ParseException(errorList); CLILogs.Debug("Parsing error : " + errorList); } CLILogs.Usage(helpText); throw ex; }
public static bool IsFileSupported(ITextBuffer buffer) { try { if (buffer == null || buffer.Properties == null) { return(false); } // For some reason, the IClassifierProvider gets called twice. // Here we check if the value has been stored alewSY so we don't run twice. if (buffer.Properties.TryGetProperty(_propKey, out bool isEnabled)) { return(isEnabled); } string fileName = buffer.GetFilePath(); // Check if filename is absolute because when debugging, script files are sometimes dynamically created. if (string.IsNullOrWhiteSpace(fileName) || !Path.IsPathRooted(fileName)) { return(PersistantReturnValue(buffer, false)); } System.Collections.Generic.IEnumerable <string> patterns = VSPackage.Options.GetIgnorePatterns(); if (patterns.Any(p => fileName.IndexOf(p, StringComparison.OrdinalIgnoreCase) > -1)) { return(PersistantReturnValue(buffer, false)); } if (VSPackage.Options.IgnoreMiscFiles) { var dte = (DTE2)Package.GetGlobalService(typeof(EnvDTE.DTE)); if (dte != null && dte.Solution.FindProjectItem(fileName) == null) { return(PersistantReturnValue(buffer, false)); } } // Ignore files containing the string <auto-generated> in the first 10 lines foreach (ITextSnapshotLine line in buffer.CurrentSnapshot.Lines.Take(10)) { if (line.Length < 200) { string content = line.GetText(); if (content.IndexOf("<auto-generated>", StringComparison.OrdinalIgnoreCase) > -1) { return(PersistantReturnValue(buffer, false)); } } } return(PersistantReturnValue(buffer, true)); } catch (Exception) { return(false); } }
public (bool verified, UserViewModel user) Login(string Email, string Password) { UserViewModel userModel = new UserViewModel(); Data.Repositories.IRepository <User> userRepository = _unitOfWork.GetRepository <User>(); Data.Repositories.IRepository <UserPassword> passRepository = _unitOfWork.GetRepository <UserPassword>(); System.Collections.Generic.IEnumerable <User> user = userRepository.Find(x => x.Email == Email); if (!user.Any()) { return(false, userModel); } userModel = _mapper.Map <User, UserViewModel>(user.FirstOrDefault()); System.Collections.Generic.IEnumerable <UserPassword> password = passRepository.Find(x => x.UserId == user.FirstOrDefault().Id); if (!password.Any()) { return(false, userModel); } (bool Verified, bool NeedsUpgrade)validation = _passwordHasher.Check(password.FirstOrDefault().Password, Password); if (!validation.Verified) { return(false, userModel); } return(true, userModel); }
public async Task CreateMissingRolesCmd() { System.Collections.Generic.IEnumerable <string> allGuildRoles = VerificationService.FindAllRoles(Context.Guild.Roles).Select(role => role.Name.ToUpperInvariant()); System.Collections.Generic.List <string> allRoles = VerificationService.AllRoles(); System.Collections.Generic.IEnumerable <string> missingRoles = allRoles.Except(allGuildRoles, StringComparer.InvariantCultureIgnoreCase); foreach (string role in missingRoles) { await Context.Guild.CreateRoleAsync(role, isMentionable : false); await Task.Delay(TimeSpan.FromMilliseconds(150)); } EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder .WithTitle($"Created roles:"); if (missingRoles.Any()) { embedBuilder.WithDescription(string.Join('\n', missingRoles)); } else { embedBuilder.WithDescription("None"); } await ReplyAsync(embed : embedBuilder.Build()); }
AddSetting( string name, System.Collections.Generic.IEnumerable <Bam.Core.TokenizedString> value, string condition = null, bool inheritExisting = false, bool arePaths = false) { lock (this.Settings) { if (!value.Any()) { return; } var linearized = arePaths ? this.toRelativePaths(value) : new Bam.Core.TokenizedStringArray(value.Distinct()).ToString(';'); if (this.Settings.Any(item => item.Name == name && item.Condition == condition)) { var settingOption = this.Settings.First(item => item.Name == name && item.Condition == condition); if (settingOption.Value.Contains(linearized)) { return; } throw new Bam.Core.Exception("Cannot append {3}, to the option {0} as it already exists for condition {1}: {2}", name, condition, settingOption.Value.ToString(), linearized); } this.Settings.AddUnique(new VSSetting(name, inheritExisting ? System.String.Format("{0};%({1})", linearized, name) : linearized, condition)); } }
public override IResult Proces(dynamic value) { var result = CheckNull(this, value); if (!result.HasData) { return(result); } System.Collections.Generic.IEnumerable <Request.HttpFile> values = value; if (!values.Any()) { if (this.CanNull) { return(this.ResultCreate()); } else { return(this.ResultCreate(State, Message ?? string.Format("argument \"{0}\" can not null.", this.Member))); } } foreach (var item in values) { if (Size < (item.Value.Length / 1024)) { return(this.ResultCreate(-171, string.Format("File size max {0} KB.", Size))); } } var files = values.Distinct(Equality <Request.HttpFile> .CreateComparer(c => c.Key)).ToDictionary(c => c.Key, c => c.Value.StreamReadByte()); return(this.ResultCreate(files)); }
/// <summary> /// Merges two ILists of type T where each item is only added if there isn't already one there with the same value in the specified field /// </summary> /// <param name="collection1"> /// The collection 1. /// </param> /// <param name="collection2"> /// The collection 2. /// </param> /// <param name="fieldName"> /// The field name. /// </param> /// <typeparam name="T"> /// The generic type parameter /// </typeparam> public static void DistinctAdd <T>(this System.Collections.Generic.IList <T> collection1, System.Collections.Generic.IList <T> collection2, string fieldName) { if ((collection1 == null) || (collection2 == null)) { return; } foreach (var item in collection2) { var anotherItem = item; var prop = typeof(T).GetProperty(fieldName); var field = typeof(T).GetField(fieldName); System.Collections.Generic.IEnumerable <T> results = null; if (prop != null) { // ReSharper disable ImplicitlyCapturedClosure results = collection1.Where(x => prop.GetValue(x, null) == prop.GetValue(anotherItem, null)); // ReSharper restore ImplicitlyCapturedClosure } if (field != null) { // ReSharper disable ImplicitlyCapturedClosure results = collection1.Where(x => field.GetValue(x) == field.GetValue(anotherItem)); // ReSharper restore ImplicitlyCapturedClosure } if (results == null || !results.Any()) { collection1.Add(item); } } }
private void CheckForDecreasedVisibility(SymbolAnalysisContext context) { ISymbol symbol = context.Symbol; // Only look for methods hiding others (not overriding). Overriding with a different visibility is already a compiler error if (symbol.IsOverride) { return; } // Bail out if the member is publicly accessible, or sealed, or on a sealed type if (IsVisibleOutsideAssembly(symbol) || symbol.IsSealed || (symbol.ContainingType?.IsSealed ?? true)) { return; } // Event accessors cannot have visibility modifiers, so don't analyze them if ((symbol as IMethodSymbol)?.AssociatedSymbol as IEventSymbol != null) { return; } // Find members on base types that share the member's name System.Collections.Generic.IEnumerable <INamedTypeSymbol> ancestorTypes = symbol?.ContainingType?.GetBaseTypes() ?? Enumerable.Empty <INamedTypeSymbol>(); System.Collections.Generic.IEnumerable <ISymbol> hiddenOrOverriddenMembers = ancestorTypes.SelectMany(t => t.GetMembers(symbol.Name)); if (hiddenOrOverriddenMembers.Any(IsVisibleOutsideAssembly)) { context.ReportDiagnostic(symbol.CreateDiagnostic(Rule)); } }
private async Task UpdateContentTypeLabelAsync() { if (_updatingTypeLabel) { return; } _updatingTypeLabel = true; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ITextBuffer buffer = GetTextBuffer(out SnapshotPoint? point); _lblContentType.Value = buffer.ContentType.TypeName; System.Collections.Generic.IEnumerable <string> typeNames = buffer.ContentType.BaseTypes.Select(t => t.DisplayName); if (typeNames.Any()) { _lblContentType.SetTooltip("base types: " + string.Join(", ", typeNames) + Environment.NewLine + "Snapshot: " + buffer.CurrentSnapshot.Version); } _updatingTypeLabel = false; }
public async Task <IActionResult> OnPostAsync() { System.Collections.Generic.IEnumerable <User> dbUsers = await userRepository.GetUsers(); if (dbUsers.Any(x => x.Username.ToLower() == SUser.Username.ToLower().Trim() && x.Id != SUser.Id)) { HasError = true; ViewData["Error"] = "Υπάρχει ήδη χρήστης με Όνομα Χρήστη (Username) που δώσατε."; return(Page()); } if (dbUsers.Any(x => x.Email.ToLower() == SUser.Email.ToLower().Trim() && x.Id != SUser.Id)) { HasError = true; ViewData["Error"] = "Υπάρχει ήδη χρήστης με την Ηλεκτρονική Διεύθυνση που δώσατε."; return(Page()); } if (string.IsNullOrEmpty(SUser.Password)) { SUser.Password = dbUsers.FirstOrDefault(x => x.Id == SUser.Id).Password; } else { SUser.Password = CrypterAlgorithm.ComputeSha256Hash(SUser.Password); } User dbUser = await userRepository.GetUser(SUser.Id); dbUser.Username = SUser.Username; dbUser.Password = SUser.Password; dbUser.Email = SUser.Email; dbUser.FamilyName = SUser.FamilyName; dbUser.IsAdmin = SUser.IsAdmin; if (await userRepository.UpdateUser(dbUser)) { HasError = false; TempData["SuccessMessage"] = "Ο Χρήστης προστέθηκε με επιτυχία."; return(RedirectToPage(Url.Content("~/Admin/UserList"))); } HasError = true; ViewData["Error"] = "Δεν μπορέσαμε να κάνουμε την εγγραφή προσπαθήστε ξανά"; return(Page()); }
public override async System.Threading.Tasks.Task <System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> > InsertOrUpdate(System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> values) { //This no longer works as we are setting the ID on the new observers at the portal side. //The update base code doesn't inser those entities in the database, thus we need to manually update/insert. //var result = await base.InsertOrUpdate(values); Guid requestID = values.First().RequestID; List <Guid> observerIDs = values.Select(p => p.ID.Value).ToList(); //PMNDEV-4548 - We are only inserting new Observers via the Observer Add dialog and will not be handling deletions/removals. //Check if we need to delete any entities //if (DataContext.RequestObservers.Any(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false)) //{ // var toDelete = DataContext.RequestObservers.Where(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false); // DataContext.RequestObservers.RemoveRange(toDelete); //} foreach (var observer in values) { if (DataContext.RequestObservers.Any(p => p.ID == observer.ID)) { //Existing Observer await base.Update(values.Where(p => p.ID == observer.ID)); } else { //New Observer RequestObserver newObserver = DataContext.RequestObservers.Create(); newObserver.ID = observer.ID.Value; newObserver.DisplayName = observer.DisplayName; newObserver.Email = observer.Email; newObserver.RequestID = observer.RequestID; newObserver.SecurityGroupID = observer.SecurityGroupID; newObserver.UserID = observer.UserID; DataContext.RequestObservers.Add(newObserver); } } await DataContext.SaveChangesAsync(); if (values.Any(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty))) { var toInsertCollection = values.Where(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty)); foreach (var observer in toInsertCollection) { foreach (var observerEventSubscription in observer.EventSubscriptions.Where(p => p.RequestObserverID == Guid.Empty)) { var obj = DataContext.RequestObserverEventSubscriptions.Create(); obj.EventID = observerEventSubscription.EventID; obj.Frequency = observerEventSubscription.Frequency.HasValue ? observerEventSubscription.Frequency.Value : DTO.Enums.Frequencies.Immediately; obj.RequestObserverID = observer.ID.Value; DataContext.RequestObserverEventSubscriptions.Add(obj); } } await DataContext.SaveChangesAsync(); } return(values); }
/// <summary> /// 配置文档生成 /// </summary> /// <param name="services">程序的服务对象</param> /// <param name="configuration">程序的配置对象</param> /// <param name="env">环境节点</param> public static void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostingEnvironment env) { if (!env.IsProduction()) { services.AddSwaggerGen(options => { options.SwaggerDoc("My", new Info { Title = "框架api" }); options.SwaggerDoc("T1", new Info { Title = "测试" }); options.SwaggerDoc("T2", new Info { Title = "真棒" }); options.SwaggerDoc("Demo", new Info { Title = "Demo模块" }); options.DocInclusionPredicate((docName, apiDesc) => { if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo)) { return(false); } System.Collections.Generic.IEnumerable <string> versions = methodInfo.DeclaringType .GetCustomAttributes(true) .OfType <MyVersionAttribute>() .Select(attr => attr.Version); return(versions.Any(v => $"{v.ToString()}" == docName)); }); // Define the BearerAuth scheme that's in use //页面可以显示自定义的授权按钮 options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); // Assign scope requirements to operations based on AuthorizeAttribute options.OperationFilter <SecurityRequirementsOperationFilter>(); string xmlCommentsPath = Path.Combine(Server.BinPath, "My.D3.Application.xml"); options.IncludeXmlComments(xmlCommentsPath, true); xmlCommentsPath = Path.Combine(Server.BinPath, "My.D3.xml"); options.IncludeXmlComments(xmlCommentsPath, true); xmlCommentsPath = Path.Combine(Server.BinPath, "My.D3.Entity.xml"); options.IncludeXmlComments(xmlCommentsPath, true); }); } }
public bool DisconnectClient(int accountId) { System.Collections.Generic.IEnumerable <WorldClient> enumerable = this.FindClients((WorldClient client) => client.Account != null && client.Account.Id == accountId); foreach (WorldClient current in enumerable) { current.Disconnect(); } return(enumerable.Any <WorldClient>()); }
private static bool HasPublicIPAddress() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); System.Collections.Generic.IEnumerable <IPAddress> uips = adapters.Select(a => a.GetIPProperties()) .SelectMany(p => p.UnicastAddresses.Cast <IPAddressInformation>(), (p, u) => u.Address); return (uips.Any( ip => !IPAddress.IsLoopback(ip) && ip.AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork(ip))); }
internal static IServiceCollection AddSwagger(this IServiceCollection services, SwaggerConfigurationModel swaggerConfiguration) { services.AddSwaggerGen(x => { x.CustomSchemaIds(y => y.FullName); foreach (VersionConfigurationModel current in swaggerConfiguration.Versions) { x.SwaggerDoc($"v{current.Version}", new OpenApiInfo { Version = $"v{current.Version}", Title = current.Title, Description = current.Description, Contact = new OpenApiContact { Email = current.Email } }); } x.DocInclusionPredicate((version, apiDescriptor) => { if (!apiDescriptor.TryGetMethodInfo(out MethodInfo mi)) { return(false); } if (!Regex.IsMatch(apiDescriptor.RelativePath, @"v{version}") && !Regex.IsMatch(apiDescriptor.RelativePath, @"v(\d+\.)?(\d+\.)?(\*|\d+)")) { return(false); } System.Collections.Generic.IEnumerable <ApiVersion> versions = mi.DeclaringType.GetCustomAttributes(true) .OfType <ApiVersionAttribute>() .SelectMany(attr => attr.Versions); ApiVersion[] maps = mi.GetCustomAttributes() .OfType <MapToApiVersionAttribute>() .SelectMany(attr => attr.Versions).ToArray(); return(versions.Any(v => $"v{v.ToString()}" == version) && (maps.Length == 0 || maps.Any(v => $"v{v.ToString()}" == version))); }); System.Collections.Generic.IEnumerable <string> documentations = swaggerConfiguration.XmlDocumentation ?? new[] { $"{Assembly.GetEntryAssembly().GetName().Name}.xml" }; foreach (string documentationPath in documentations) { string xmlPath = Path.Combine(AppContext.BaseDirectory, documentationPath); x.IncludeXmlComments(xmlPath); } }); return(services); }
protected override async Task OnInitializedAsync() { AuthenticationState authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); System.Security.Claims.ClaimsPrincipal user = authState.User; if (user.Identity.IsAuthenticated) { System.Collections.Generic.IEnumerable <System.Security.Claims.Claim> userClaims = user.Claims.Where(claim => claim.Type.Equals(ClaimType)); Claims = userClaims.Any() ? userClaims.Select(claim => claim.Value).Aggregate(AddClaims) : ""; } }
private async Task <Document> IncreaseVisibility(Document document, SyntaxNode node, CancellationToken cancellationToken) { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SyntaxNode declaration = editor.Generator.GetDeclaration(node); ISymbol symbol = editor.SemanticModel.GetDeclaredSymbol(node); System.Collections.Generic.IEnumerable <INamedTypeSymbol> ancestorTypes = symbol?.ContainingType?.GetBaseTypes() ?? Enumerable.Empty <INamedTypeSymbol>(); System.Collections.Generic.IEnumerable <ISymbol> hiddenOrOverriddenMembers = ancestorTypes.SelectMany(t => t.GetMembers(symbol.Name)); // Check if a public member was overridden if (hiddenOrOverriddenMembers.Any(s => s.DeclaredAccessibility == Accessibility.Public)) { IncreaseVisibility(editor, declaration, Accessibility.Public); return(editor.GetChangedDocument()); } // Otherwise, check if a protected or internal member was overridden if (hiddenOrOverriddenMembers.Any(s => s.DeclaredAccessibility == Accessibility.ProtectedOrInternal)) { IncreaseVisibility(editor, declaration, Accessibility.ProtectedOrInternal); return(editor.GetChangedDocument()); } // Otherwise, check if a protected member was overridden if (hiddenOrOverriddenMembers.Any(s => s.DeclaredAccessibility == Accessibility.Protected)) { IncreaseVisibility(editor, declaration, Accessibility.Protected); return(editor.GetChangedDocument()); } // Otherwise, make no change return(document); }
/// <summary> /// Constructor for VM /// </summary> /// <param name="currentFolders">Current folders.</param> public FolderIconPickerViewModel(System.Collections.Generic.IEnumerable <Icon> currentFolders) { CurrentFolderStrings = new System.Collections.Generic.List <string>(); if (currentFolders.Any()) { foreach (var folder in currentFolders) { CurrentFolderStrings.Add(folder.Text); } } IconSelectedFromList = new Xamarin.Forms.Command(ItemSelected); CommandSaveClicked = new Xamarin.Forms.Command(SaveClicked); }
public static System.Byte[] CreateZipArchive(System.Collections.Generic.IEnumerable <System.String> Files) { if ((Files == null) || (!(Files.Any()))) { return(null); } System.Collections.Generic.Dictionary <System.String, System.String> FilesDictionary = new System.Collections.Generic.Dictionary <System.String, System.String>(); foreach (System.String File in Files) { FilesDictionary.Add(File, new System.IO.FileInfo(File).Name); } return(SoftmakeAll.SDK.Files.Compression.CreateZipArchive(FilesDictionary)); }
public static void NullOrWithNoNullElements <T>(System.Collections.Generic.IEnumerable <T> sequence, string parameterName) where T : class { Func <T, bool> func = null; if (sequence != null) { if (func == null) { func = ((T e) => e == null); } if (sequence.Any(func)) { throw new System.ArgumentException(MessagingStrings.SequenceContainsNullElement, parameterName); } } }
public static void RegisterComponents(bool repos = true, bool queries = true, bool mappers = true) { if (Application.container == null) { var builder = new ContainerBuilder(); var assemblyPattern = new Regex($"{nameof(SiliconeTrader)}.*.dll"); System.Collections.Generic.IEnumerable<Assembly> loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => assemblyPattern.IsMatch(Path.GetFileName(a.Location))); string dynamicAssembliesPath = new Uri(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location)).LocalPath; System.Collections.Generic.IEnumerable<string> dynamicAssemblies = Directory.EnumerateFiles(dynamicAssembliesPath, "*.dll", SearchOption.AllDirectories) .Where(filename => assemblyPattern.IsMatch(Path.GetFileName(filename)) && !loadedAssemblies.Any(a => Path.GetFileName(a.Location) == Path.GetFileName(filename))); System.Collections.Generic.IEnumerable<Assembly> allAssemblies = loadedAssemblies.Concat(dynamicAssemblies.Select(Assembly.LoadFrom)).Distinct(); builder.RegisterAssemblyModules(allAssemblies.ToArray()); Application.container = builder.Build(); } }
public Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { System.Collections.Generic.IEnumerable <Claim> customClaims = principal.Claims.Where(c => _sourceClaimType.Equals(c.Type, StringComparison.OrdinalIgnoreCase)); System.Collections.Generic.IEnumerable <Claim> roleClaims = customClaims.SelectMany(c => { return(c.Value.Split(' ').Select(s => new Claim(_roleType, s))); }); if (!roleClaims.Any()) { return(Task.FromResult(principal)); } ClaimsPrincipal transformed = new ClaimsPrincipal(principal); ClaimsIdentity rolesIdentity = new ClaimsIdentity(roleClaims, _authType, null, _roleType); transformed.AddIdentity(rolesIdentity); return(Task.FromResult(transformed)); }
public async Task RolesCmd() { System.Collections.Generic.IEnumerable <string> roles = VerificationService.FindAllRoles(Context.Guild.Roles).Select(role => role.Name); EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder .WithTitle("Configured Roles:"); if (roles.Any()) { embedBuilder.WithDescription(string.Join('\n', roles)); } else { embedBuilder.WithDescription("None"); } await ReplyAsync(embed : embedBuilder.Build()); }
T IRepository <T> .SingleRecord(System.Linq.Expressions.Expression <Func <T, bool> > where) { using (System.Data.IDbConnection connection = Connection) { string columns = BuildSelectColumns(); string whereClause = BuildWhereClause(where.Body); string sqlStatement = string.Format("SELECT {0} FROM [{1}].[{2}] WITH (NOLOCK) WHERE {3} ", columns, _schema, _table, whereClause); System.Collections.Generic.IEnumerable <T> entities = connection.Query <T>(sqlStatement); T entity = default(T); if (entities != null) { if (entities.Any()) { entity = entities.FirstOrDefault(); } } return(entity); } }
public async Task MissingRolesCmd() { System.Collections.Generic.IEnumerable <string> allGuildRoles = VerificationService.FindAllRoles(Context.Guild.Roles).Select(role => role.Name.ToUpperInvariant()); System.Collections.Generic.List <string> allRoles = VerificationService.AllRoles(); System.Collections.Generic.IEnumerable <string> missingRoles = allRoles.Except(allGuildRoles, StringComparer.InvariantCultureIgnoreCase); EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder .WithTitle($"Missing roles:"); if (missingRoles.Any()) { embedBuilder.WithDescription(string.Join('\n', missingRoles)); } else { embedBuilder.WithDescription("None"); } await ReplyAsync(embed : embedBuilder.Build()); }
async Task DispatchAsync(Publish publish, string clientId, bool isWill = false) { System.Collections.Generic.IEnumerable <ClientSubscription> subscriptions = sessionRepository .ReadAll().ToList() .SelectMany(s => s.GetSubscriptions()) .Where(x => topicEvaluator.Matches(publish.Topic, x.TopicFilter)); if (!subscriptions.Any()) { _tracer.Verbose(ServerProperties.ServerPublishReceiverFlow_TopicNotSubscribed(publish.Topic, clientId)); _undeliveredMessagesListener.OnNext(new MqttUndeliveredMessage { SenderId = clientId, Message = new MqttApplicationMessage(publish.Topic, publish.Payload) }); } else { foreach (ClientSubscription subscription in subscriptions) { await DispatchAsync(publish, subscription, isWill); } } }
private static void AnalyzeSymbol(SymbolAnalysisContext context) { var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // If any interface implemented by this type has the attribute and if the interface and this type are not // in "internals visible" context, then issue an error. foreach (INamedTypeSymbol iface in namedTypeSymbol.AllInterfaces) { System.Collections.Generic.IEnumerable <AttributeData> attributes = iface.GetAttributes(); // We are doing a string comparison of the name here because we don't care where the attribute comes from. // CodeAnalysis.dll itself has this attribute and if the user assembly also had it, symbol equality will fail // but we should still issue the error. if (attributes.Any(a => a.AttributeClass.Name.Equals(InternalImplementationOnlyAttributeName, StringComparison.Ordinal) && a.AttributeClass.ToDisplayString().Equals(InternalImplementationOnlyAttributeFullName, StringComparison.Ordinal))) { if (!iface.ContainingAssembly.GivesAccessTo(namedTypeSymbol.ContainingAssembly)) { context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule, namedTypeSymbol.Name, iface.Name)); break; } } } }
private static void Main(string[] args) { GenericDataService <User> userService = new GenericDataService <User>(new SimpleTraderDbContexfactory()); userService.Create(new User { Username = "******" }).Wait(); // System.Console.WriteLine("Data inserted.!!"); // var userUpdate = userService.Update(1, new User { Username = "******" }).Result; //bool deleteUser = userService.Delete(3).Result; System.Collections.Generic.IEnumerable <User> allusers = userService.GetAll().Result; //System.Console.WriteLine("User Deleted.!!!!"); if (!allusers.Any()) { System.Console.WriteLine("There aren't users a databaase"); } else { foreach (var users in allusers) { System.Console.WriteLine($"The Users: {users.Username}"); } } }
/// <summary> /// Authenticate user/application using Credentials. /// </summary> /// <param name="Credentials">Credentials to use during authentication process.</param> public static async System.Threading.Tasks.Task AuthenticateAsync(SoftmakeAll.SDK.Fluent.Authentication.ICredentials Credentials) { if (Credentials != null) { SoftmakeAll.SDK.Fluent.SDKContext.SignOut(); SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = Credentials; // From AccessKey if (Credentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application) { SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Basic {System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{Credentials.ClientID}@{Credentials.ContextIdentifier.ToString().ToLower()}:{Credentials.ClientSecret}"))}"; SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Store(); await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization); return; } } else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null) { try { System.Text.Json.JsonElement CacheData = SoftmakeAll.SDK.Fluent.GeneralCacheHelper.ReadString().ToJsonElement(); if (!(CacheData.IsValid())) { throw new System.Exception(); } // From AccessKey if (CacheData.GetInt32("AuthType") == (int)SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application) { SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetGuid("ContextIdentifier"), CacheData.GetString("ClientID"), null, (SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes)CacheData.GetInt32("AuthType")); SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = CacheData.GetString("Authorization"); if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization)) { throw new System.Exception(); } await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization); return; } else { SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials = new SoftmakeAll.SDK.Fluent.Authentication.Credentials(CacheData.GetJsonElement("AppMetadata").EnumerateObject().First().Value.GetGuid("client_id")); SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType = SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive; } } catch { } } if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials == null) { SoftmakeAll.SDK.Fluent.SDKContext.SignOut(); throw new System.Exception("Invalid Credentials from cache."); } // From AccessKey if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Application) { return; } // From Public Client Application if ((SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null) || (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.ExpiresOn.Subtract(System.DateTimeOffset.UtcNow).TotalMinutes <= 5.0D)) { System.String[] Scopes = new System.String[] { "openid", "https://softmakeb2c.onmicrosoft.com/48512da7-b030-4e62-be61-9e19b2c52d8a/user_impersonation" }; if (SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication == null) { if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive { SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "A_signup_signin", "http://localhost:1435"); } else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password { SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication = SoftmakeAll.SDK.Fluent.SDKContext.CreatePublicClientApplication(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ContextIdentifier, "_ROPC"); } else { throw new System.Exception("Invalid authentication type."); } } // Getting existing Account in cache try { System.Collections.Generic.IEnumerable <Microsoft.Identity.Client.IAccount> Accounts = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.GetAccountsAsync(); if (Accounts.Any()) { SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenSilent(Scopes, Accounts.FirstOrDefault()).ExecuteAsync(); if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult != null) { SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}"; await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken); return; } } } catch { SoftmakeAll.SDK.Fluent.GeneralCacheHelper.Clear(); } if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Interactive) // From Interactive { try { SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenInteractive(Scopes).WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin).ExecuteAsync(); } catch { } } else if (SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.AuthenticationType == SoftmakeAll.SDK.Fluent.Authentication.AuthenticationTypes.Credentials) // From Username and Password { if (System.String.IsNullOrWhiteSpace(SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret)) { SoftmakeAll.SDK.Fluent.SDKContext.SignOut(); throw new System.Exception("Authentication aborted. Please, re-enter credentials."); } System.Security.SecureString Password = new System.Security.SecureString(); foreach (System.Char Char in SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientSecret) { Password.AppendChar(Char); } Password.MakeReadOnly(); try { SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult = await SoftmakeAll.SDK.Fluent.SDKContext.PublicClientApplication.AcquireTokenByUsernamePassword(Scopes, SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.ClientID, Password).ExecuteAsync(); Password.Dispose(); } catch { Password.Dispose(); SoftmakeAll.SDK.Fluent.SDKContext.SignOut(); throw new System.Exception("Invalid username or password."); } } if (SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult == null) { SoftmakeAll.SDK.Fluent.SDKContext.SignOut(); throw new System.Exception("Authentication aborted."); } SoftmakeAll.SDK.Fluent.SDKContext.InMemoryCredentials.Authorization = $"Bearer {SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken}"; await SoftmakeAll.SDK.Fluent.SDKContext.ClientWebSocket.ConfigureAsync(SoftmakeAll.SDK.Fluent.SDKContext.AuthenticationResult.AccessToken); return; } }