string.ToUpperInvariant()

Here are the examples of the csharp api string.ToUpperInvariant() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1497 Examples 7

19 View Source File : IrdProvider.cs
License : MIT License
Project Creator : 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            ProductCode = ProductCode?.ToUpperInvariant();
            var result = new HashSet<DiscKeyInfo>();
            var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            Log.Trace("Searching local cache for a match...");
            if (Directory.Exists(discKeyCachePath))
            {
                var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
                foreach (var irdFile in matchingIrdFiles)
                {
                    try
                    {
                        try
                        {
                            var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
                            result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
                            knownFilenames.Add(Path.GetFileName(irdFile));
                        }
                        catch (InvalidDataException)
                        {
                            File.Delete(irdFile);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e);
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn(e, e.Message);
                    }
                }
            }

            Log.Trace("Searching IRD Library for match...");
            var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
            var irdList = irdInfoList?.Data?.Where(
                              i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
                          ).ToList() ?? new List<SearchResulreplacedem>(0);
            if (irdList.Count == 0)
                Log.Debug("No matching IRD file was found in the Library");
            else
            {
                Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
                foreach (var irdInfo in irdList)
                {
                    var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
                    result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
                    knownFilenames.Add(irdInfo.Filename);
                }
            }
            if (knownFilenames.Count == 0)
            {
                Log.Warn("No valid matching IRD file could be found");
                Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
            }

            Log.Info($"Found {result.Count} IRD files");
            return result;
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

public async System.Threading.Tasks.Task UpdatePresenceAsync(Doreplacedent doreplacedent, Boolean overrideTimestampReset = false)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!Settings.enabled)
                {
                    if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                        if (!this.Discord.Initialize())
                            ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

                    this.Discord.ClearPresence();
                    return;
                }

                this.Presence.Details = this.Presence.State = this.replacedets.LargeImageKey = this.replacedets.LargeImageText = this.replacedets.SmallImageKey = this.replacedets.SmallImageText = String.Empty;

                if (Settings.secretMode)
                {
                    this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
                    this.Presence.State = Translates.PresenceState(Settings.Default.translates);
                    this.replacedets.LargeImageKey = this.versionImageKey;
                    this.replacedets.LargeImageText = this.versionString;
                    this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    goto finish;
                }

                this.Presence.Details = this.Presence.State = "";
                String[] language = Array.Empty<String>();

                if (doreplacedent != null)
                {
                    String filename = Path.GetFileName(path: doreplacedent.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
                    List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
                    language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
                }

                Boolean supported = language.Length > 0;
                this.replacedets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
                this.replacedets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
                this.replacedets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
                this.replacedets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);

                if (Settings.showFileName)
                    this.Presence.Details = !(doreplacedent is null) ? Path.GetFileName(doreplacedent.FullName) : Translates.NoFile(Settings.Default.translates);

                if (Settings.showSolutionName)
                {
                    Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
                    this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";

                    if (idling)
                    {
                        this.replacedets.LargeImageKey = this.versionImageKey;
                        this.replacedets.LargeImageText = this.versionString;
                        this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    }
                }

                if (Settings.showTimestamp && doreplacedent != null)
                {
                    if (!this.InitializedTimestamp)
                    {
                        this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                        this.InitializedTimestamp = true;
                    }

                    if (Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                    else if (Settings.resetTimestamp && overrideTimestampReset)
                        this.Presence.Timestamps = this.CurrentTimestamps;
                    else if (!Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = this.InitialTimestamps;

                    this.CurrentTimestamps = this.Presence.Timestamps;
                }

                finish:;
                this.Presence.replacedets = this.replacedets;

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                    if (!this.Discord.Initialize())
                        ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));

                this.Discord.SetPresence(this.Presence);
            }
            catch (ArgumentException e)
            {
                ActivityLog.LogError(e.Source, e.Message);
            }
        }

19 View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing

static bool TryStringToOpcode(string str, out CPU.Opcode opcode) {
            var names = Enum.GetNames(typeof(CPU.Opcode));
            var values = Enum.GetValues(typeof(CPU.Opcode));
            str = str.ToUpperInvariant();
            
            for(int i = 0; i < names.Length; i++) {
                if(names[i] == str) {
                    opcode = (CPU.Opcode)values.GetValue(i);
                    return true;
                }
            }

            opcode = 0;
            return false;
        }

19 View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing

static bool TryStringToCond(string str, out CPU.Cond cond) {
            var names = Enum.GetNames(typeof(CPU.Cond));
            var values = Enum.GetValues(typeof(CPU.Cond));
            str = str.ToUpperInvariant();
            
            for(int i = 0; i < names.Length; i++) {
                if(names[i] == str) {
                    cond = (CPU.Cond)values.GetValue(i);
                    return true;
                }
            }

            cond = 0;
            return false;
        }

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

private static string GetSignature(NameValueDictionary args, string secretKey)
	    {
		    var sb = new StringBuilder();
			foreach (var arg in args)
			{
				sb.Append(arg.Key);
				sb.Append("=");
				sb.Append(arg.Value);
				sb.Append("&");
			}

			sb.Append("secret_key=");
		    sb.Append(secretKey);

		    using (var md = MD5.Create())
		    {
				using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())))
		        {
			        var hashData = md.ComputeHash(stream);

					// Format as hexadecimal string.
					var hashBuilder = new StringBuilder();
					foreach (byte data in hashData)
					{
						hashBuilder.Append(data.ToString("x2", CultureInfo.InvariantCulture));
					}
					return hashBuilder.ToString().ToUpperInvariant();
		        }
		    }
	    }

19 View Source File : SimNetwork.cs
License : MIT License
Project Creator : abdullin

public string BodyString() {
            var body = Payload == null ? "" : Payload.ToString();
            if (Flag != SimFlag.None) {
                body += $" {Flag.ToString().ToUpperInvariant()}";
            }

            return body.Trim();
        }

19 View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock

public IEnumerable<string> Generate(
            GuidEncoding encoding,
            GuidFormat format,
            IEnumerable<string> args = null)
        {
            var guid = GenerateGuid(args ?? Array.Empty<string>());

            if (encoding == GuidEncoding.MixedEndian)
                guid = ToMixedEndian(guid);

            var guidString = FormatGuid(format, guid);

            switch (format)
            {
                case GuidFormat.Base64:
                case GuidFormat.Short:
                    yield return guidString;
                    break;
                default:
                    if (uppercase)
                        yield return guidString.ToUpperInvariant();
                    else
                        yield return guidString;
                    break;
            }
        }

19 View Source File : LogarithmicAxis3DView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = (string)value;

            var result = str.ToUpperInvariant().Equals("E") ? Math.E : Double.Parse(str, CultureInfo.InvariantCulture);

            return result;
        }

19 View Source File : Handler.cs
License : MIT License
Project Creator : actions

protected void AddInputsToEnvironment()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(Inputs, nameof(Inputs));

            // Add the inputs to the environment variable dictionary.
            foreach (KeyValuePair<string, string> pair in Inputs)
            {
                AddEnvironmentVariable(
                    key: $"INPUT_{pair.Key?.Replace(' ', '_').ToUpperInvariant()}",
                    value: pair.Value);
            }
        }

19 View Source File : IssueMatcher.cs
License : MIT License
Project Creator : actions

public void Validate()
        {
            // Validate owner
            if (string.IsNullOrEmpty(_owner))
            {
                throw new ArgumentException("Owner must not be empty");
            }

            // Validate severity
            switch ((_severity ?? string.Empty).ToUpperInvariant())
            {
                case "":
                case "ERROR":
                case "WARNING":
                case "NOTICE":
                    break;
                default:
                    throw new ArgumentException($"Matcher '{_owner}' contains unexpected default severity '{_severity}'");
            }

            // Validate at least one pattern
            if (_patterns == null || _patterns.Length == 0)
            {
                throw new ArgumentException($"Matcher '{_owner}' does not contain any patterns");
            }

            int? file = null;
            int? line = null;
            int? column = null;
            int? severity = null;
            int? code = null;
            int? message = null;
            int? fromPath = null;

            // Validate each pattern config
            for (var i = 0; i < _patterns.Length; i++)
            {
                var isFirst = i == 0;
                var isLast = i == _patterns.Length - 1;
                var pattern = _patterns[i];
                pattern.Validate(isFirst,
                    isLast,
                    ref file,
                    ref line,
                    ref column,
                    ref severity,
                    ref code,
                    ref message,
                    ref fromPath);
            }

            if (message == null)
            {
                throw new ArgumentException($"At least one pattern must set 'message'");
            }
        }

19 View Source File : TemperatureTypeConverter.cs
License : MIT License
Project Creator : Actipro

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
			string valueString = value as string;
			if (null != valueString) {
				valueString = valueString.Trim().ToUpperInvariant();

				// Determine if Fahrenheit or Celsius
				bool fahrenheit = true;
				if (valueString.Length > 0) {
					string scale = valueString.Substring(valueString.Length - 1);
					bool removeLastChar = false;
					if ("C" == scale) {
						fahrenheit = false;
						removeLastChar = true;
					}
					else if ("F" == scale) {
						removeLastChar = true;
					}

					if (removeLastChar) {
						if (valueString.Length > 1)
							valueString = valueString.Substring(0, valueString.Length - 1).Trim();
						else
							valueString = string.Empty;
					}
				}

				// Remove degree symbol, if it's there
				if (valueString.Length > 0) {
					string scale = valueString.Substring(valueString.Length - 1);
					if ("°" == scale) {
						if (valueString.Length > 1)
							valueString = valueString.Substring(0, valueString.Length - 1).Trim();
						else
							valueString = string.Empty;
					}
				}

				// Convert degrees portion using base clreplaced
				double degrees = 0.0;
				if (0 != valueString.Length)
					degrees = (double)base.ConvertFrom(context, culture, valueString);

				// Converter if needed
				if (!fahrenheit)
					degrees = degrees * 9 / 5 + 32.0;

				return degrees;
			}

			return base.ConvertFrom(context, culture, value);
		}

19 View Source File : CodeViewerTreeFilter.cs
License : MIT License
Project Creator : Actipro

public override DataFilterResult Filter(object item, object context) {
			var shellObject = item as ShellObjectViewModel;
			if (shellObject != null) {
				if (shellObject.IsFolder)
					return DataFilterResult.IncludedWithDescendants;
				else {
					var parsingName = shellObject.RelativeParsingName;
					if (!string.IsNullOrEmpty(parsingName)) {
						var extension = Path.GetExtension(parsingName);
						if (!string.IsNullOrEmpty(extension)) {
							extension = extension.ToUpperInvariant();
							switch (extension) {
								case ".CS":
								case ".XAML":
									return DataFilterResult.Included;
							}
						}
					}
				}
			}

			return DataFilterResult.Excluded;
		}

19 View Source File : CodeViewerWindow.xaml.cs
License : MIT License
Project Creator : Actipro

private void UpdateSourcePane() {
			var selectedShellObject = shellListBox.SelectedShellObject;
			if (selectedShellObject != null) {
				if (selectedShellObject.IsFolder) {
					editorDockPanel.Visibility = Visibility.Collapsed;
				}
				else {
					// NOTE: Any changes to supported extensions need to be made in CodeViewerTreeFilter as well
					switch (Path.GetExtension(selectedShellObject.ParsingName).ToUpperInvariant()) {
						case ".CS":
							editor.Doreplacedent.Language = this.ViewModel.SyntaxLanguageCSharp;
							break;
						case ".XAML":
							editor.Doreplacedent.Language = this.ViewModel.SyntaxLanguageXaml;
							break;
						default:
							editor.Doreplacedent.Language = SyntaxLanguage.PlainText;
							break;
					}

					// Load the file
					try {
						editor.Doreplacedent.LoadFile(selectedShellObject.ParsingName);
					}
					catch (Exception ex) {
						editor.Doreplacedent.Language = SyntaxLanguage.PlainText;
						editor.Doreplacedent.SetText(String.Format("An exception occurred while loading the file '{0}':\r\n\r\n{1}", selectedShellObject.ParsingName, ex.Message));
					}

					editorDockPanel.Visibility = Visibility.Visible;
				}
			}
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

protected override void OnTextInput(TextCompositionEventArgs e) {
			// Call the base method
			base.OnTextInput(e);

			if (!e.Handled) {
				switch (e.Text.ToUpperInvariant()) {
					case "X": { 
						// Delete the card under the pointer
						var column = taskBoard.HitTestForColumn(Mouse.GetPosition(taskBoard));
						if (column != null) {
							var card = column.HitTestForCard(Mouse.GetPosition(column));
							if (card != null) {
								var task = card.Content as TaskModel;
								if (task != null)
									task.DeleteTaskCommand.Execute(null);
							}
						}
						break;
					}
				}
			}
		}

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static bool IsUnitTestreplacedembly(this Compilation compilation)
		{
			string replacedemblyName = compilation?.replacedemblyName;

			if (replacedemblyName.IsNullOrEmpty())
				return false;

			string replacedemblyNameUpperCase = replacedemblyName.ToUpperInvariant();

			for (int i = 0; i < UnitTestreplacedemblyMarkers.Length; i++)
			{
				if (replacedemblyNameUpperCase.Contains(UnitTestreplacedemblyMarkers[i]))
					return replacedemblyName != AreplacedinatorTestsName;
			}

			return false;
		}

19 View Source File : RegionsVisitor.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax endRegionDirective)
			{
				if (_regionsStack.Count == 0 || _cancellationToken.IsCancellationRequested)
				{
					if (!_cancellationToken.IsCancellationRequested)
						base.VisitEndRegionDirectiveTrivia(endRegionDirective);

					return;
				}

				RegionDirectiveTriviaSyntax regionDirective = _regionsStack.Pop();
				string regionNameUpperCase = GetRegionName(regionDirective).ToUpperInvariant();

				if (regionNameUpperCase.Contains(_identifierToRemove))
				{
					RegionNodesToRemove.Add(endRegionDirective);
				}

				base.VisitEndRegionDirectiveTrivia(endRegionDirective);
			}

19 View Source File : RegionsVisitor.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override void VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax regionDirective)
			{
				if (_cancellationToken.IsCancellationRequested)
					return;

				_regionsStack.Push(regionDirective);
				string regionNameUpperCase = GetRegionName(regionDirective).ToUpperInvariant();

				if (regionNameUpperCase.Contains(_identifierToRemove))
				{
					RegionNodesToRemove.Add(regionDirective);
				}

				base.VisitRegionDirectiveTrivia(regionDirective);
			}

19 View Source File : SuppressionManagerInitInfo.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override int GetHashCode()
		{
			int hash = 17;

			unchecked
			{
				hash = 23 * hash + (Path?.ToUpperInvariant().GetHashCode() ?? 0);
				hash = 23 * hash + GenerateSuppressionBase.GetHashCode();
			}

			return hash;
		}

19 View Source File : RawPriceDataParser.cs
License : MIT License
Project Creator : adainrivers

private static int? RomanToInt(string roman)
        {
            if (roman == null)
            {
                return null;
            }
            switch (roman.Trim().ToUpperInvariant())
            {
                case "I":
                    return 1;
                case "II":
                    return 2;
                case "III":
                    return 3;
                case "IV":
                    return 4;
                case "V":
                    return 5;
                default:
                    return null;
            }
        }

19 View Source File : HostExtensions.cs
License : Apache License 2.0
Project Creator : adamralph

public static Host DetectIfNull(this Host? host)
        {
            if (host.HasValue)
            {
                return host.Value;
            }

            if (Environment.GetEnvironmentVariable("APPVEYOR")?.ToUpperInvariant() == "TRUE")
            {
                return Host.AppVeyor;
            }
            else if (Environment.GetEnvironmentVariable("TF_BUILD")?.ToUpperInvariant() == "TRUE")
            {
                return Host.AzurePipelines;
            }
            else if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS")?.ToUpperInvariant() == "TRUE")
            {
                return Host.GitHubActions;
            }
            else if (Environment.GetEnvironmentVariable("GITLAB_CI")?.ToUpperInvariant() == "TRUE")
            {
                return Host.GitLabCI;
            }
            else if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TRAVIS_OS_NAME")))
            {
                return Host.Travis;
            }
            else if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME")))
            {
                return Host.TeamCity;
            }
            else if (Environment.GetEnvironmentVariable("TERM_PROGRAM")?.ToUpperInvariant() == "VSCODE")
            {
                return Host.VisualStudioCode;
            }

            return Host.Console;
        }

19 View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : adamralph

public static string ToAltCase(this string value) =>
#pragma warning disable CA1308 // Normalize strings to uppercase
#if NET5_0_OR_GREATER
            new(value.Select((c, i) => i % 2 == 0 ? c.ToString().ToLowerInvariant()[0] : c.ToString().ToUpperInvariant()[0]).ToArray());
#else
            new string(value.Select((c, i) => i % 2 == 0 ? c.ToString().ToLowerInvariant()[0] : c.ToString().ToUpperInvariant()[0]).ToArray());

19 View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX

public static string MakeRelativePath(string path, string basePath)
        {
            List<string> pathElements =
                new List<string>(path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));
            List<string> basePathElements =
                new List<string>(basePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));

            if (!basePath.EndsWith("\\", StringComparison.Ordinal) && basePathElements.Count > 0)
            {
                basePathElements.RemoveAt(basePathElements.Count - 1);
            }

            // Find first part of paths that don't match
            int i = 0;
            while (i < Math.Min(pathElements.Count - 1, basePathElements.Count))
            {
                if (pathElements[i].ToUpperInvariant() != basePathElements[i].ToUpperInvariant())
                {
                    break;
                }

                ++i;
            }

            // For each remaining part of the base path, insert '..'
            StringBuilder result = new StringBuilder();
            if (i == basePathElements.Count)
            {
                result.Append(@".\");
            }
            else if (i < basePathElements.Count)
            {
                for (int j = 0; j < basePathElements.Count - i; ++j)
                {
                    result.Append(@"..\");
                }
            }

            // For each remaining part of the path, add the path element
            for (int j = i; j < pathElements.Count - 1; ++j)
            {
                result.Append(pathElements[j]);
                result.Append(@"\");
            }

            result.Append(pathElements[pathElements.Count - 1]);

            // If the target was a directory, put the terminator back
            if (path.EndsWith(@"\", StringComparison.Ordinal))
            {
                result.Append(@"\");
            }

            return result.ToString();
        }

19 View Source File : SubKeyHashedListCell.cs
License : MIT License
Project Creator : ADeltaX

internal int IndexOf(string name)
        {
            foreach (int index in Find(name, 0))
            {
                KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(_subKeyIndexes[index]);
                if (cell.Name.ToUpperInvariant() == name.ToUpperInvariant())
                {
                    return index;
                }
            }

            return -1;
        }

19 View Source File : SubKeyHashedListCell.cs
License : MIT License
Project Creator : ADeltaX

private IEnumerable<int> FindByPrefix(string name, int start)
        {
            int compChars = Math.Min(name.Length, 4);
            string compStr = name.Substring(0, compChars).ToUpperInvariant() + "\0\0\0\0";

            for (int i = start; i < _nameHashes.Count; ++i)
            {
                bool match = true;
                uint hash = _nameHashes[i];

                for (int j = 0; j < 4; ++j)
                {
                    char ch = (char)((hash >> (j * 8)) & 0xFF);
                    if (char.ToUpperInvariant(ch) != compStr[j])
                    {
                        match = false;
                        break;
                    }
                }

                if (match)
                {
                    yield return i;
                }
            }
        }

19 View Source File : SharePointDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private static string ConvertSortExpressionToCaml(string sortExpression)
		{
			if (string.IsNullOrWhiteSpace(sortExpression)) throw new ArgumentNullException("sortExpression");

			var sort = sortExpression.Trim();
			var sortAsc = !sort.EndsWith(" DESC", StringComparison.InvariantCultureIgnoreCase);
			var sortBy = sort.Split(' ').First();

			return @"Name=""{0}"" Ascending=""{1}""".FormatWith(sortBy, sortAsc.ToString().ToUpperInvariant());
		}

19 View Source File : EntityListFilters.cs
License : MIT License
Project Creator : Adoxio

public static string CurrentSort(string sortExpression, string attribute)
		{
			if (string.IsNullOrEmpty(sortExpression) || string.IsNullOrEmpty(attribute))
			{
				return null;
			}

			var match = Regex.Match(sortExpression, "{0} (?<direction>ASC|DESC)".FormatWith(attribute), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

			return match.Success ? match.Groups["direction"].Value.ToUpperInvariant() : null;
		}

19 View Source File : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio

private static FileInfo GetDeviceFile(string environment)
		{
			return new FileInfo(string.Format(CultureInfo.InvariantCulture, LiveIdConstants.LiveDeviceFileNameFormat,
				string.IsNullOrEmpty(environment) ? null : "-" + environment.ToUpperInvariant()));
		}

19 View Source File : FolderRegPickerWindow.xaml.cs
License : MIT License
Project Creator : advancedmonitoring

public static RegistryKey GetKeyFromString(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                return null;
            path = path.Trim();
            if (path[path.Length - 1] == '\\')
                path = path.Substring(0, path.Length - 1);
            var index = path.IndexOf('\\');
            var start = (index == -1) ? path : path.Substring(0, index);
            RegistryKey rv;
            switch (start.ToUpperInvariant())
            {
                case "HKEY_CLreplacedES_ROOT":
                case "HKCR":
                    rv = Registry.ClreplacedesRoot;
                    break;

                case "HKEY_CURRENT_USER":
                case "HKCU":
                    rv = Registry.CurrentUser;
                    break;

                case "HKEY_LOCAL_MACHINE":
                case "HKLM":
                    rv = Registry.LocalMachine;
                    break;

                case "HKEY_USERS":
                case "HKU":
                    rv = Registry.Users;
                    break;

                case "HKEY_CURRENT_CONFIG":
                    rv = Registry.CurrentConfig;
                    break;

                default:
                    return null;
            }
            if (index == -1)
            {
                return rv;
            }
            try
            {
                path = path.Substring(index + 1);
                return rv.OpenSubKey(path);
            }
            catch
            {
                return null;
            }
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RedisArray.Strings Sort(string key, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get)
        {
            List<string> args = new List<string>();
            args.Add(key);
            if (by != null)
                args.AddRange(new[] { "BY", by });
            if (offset.HasValue && count.HasValue)
                args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
            foreach (var pattern in get)
                args.AddRange(new[] { "GET", pattern });
            if (dir.HasValue)
                args.Add(dir.ToString().ToUpperInvariant());
            if (isAlpha.HasValue && isAlpha.Value)
                args.Add("ALPHA");
            return new RedisArray.Strings("SORT", args.ToArray());
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RedisInt SortAndStore(string key, string destination, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get)
        {
            List<string> args = new List<string>();
            args.Add(key);
            if (by != null)
                args.AddRange(new[] { "BY", by });
            if (offset.HasValue && count.HasValue)
                args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
            foreach (var pattern in get)
                args.AddRange(new[] { "GET", pattern });
            if (dir.HasValue)
                args.Add(dir.ToString().ToUpperInvariant());
            if (isAlpha.HasValue && isAlpha.Value)
                args.Add("ALPHA");
            args.AddRange(new[] { "STORE", destination });
            return new RedisInt("SORT", args.ToArray());
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RedisInt ZInterStore(string destination, double[] weights = null, RedisAggregate? aggregate = null, params string[] keys)
        {
            List<object> args = new List<object>();
            args.Add(destination);
            args.Add(keys.Length);
            args.AddRange(keys);
            if (weights != null && weights.Length > 0)
            {
                args.Add("WEIGHTS");
                foreach (var weight in weights)
                    args.Add(weight);
            }
            if (aggregate != null)
            {
                args.Add("AGGREGATE");
                args.Add(aggregate.ToString().ToUpperInvariant());
            }
            return new RedisInt("ZINTERSTORE", args.ToArray());
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RedisInt ZUnionStore(string destination, double[] weights = null, RedisAggregate? aggregate = null, params string[] keys)
        {
            List<object> args = new List<object>();
            args.Add(destination);
            args.Add(keys.Length);
            args.AddRange(keys);
            if (weights != null && weights.Length > 0)
            {
                args.Add("WEIGHTS");
                foreach (var weight in weights)
                    args.Add(weight);
            }
            if (aggregate != null)
            {
                args.Add("AGGREGATE");
                args.Add(aggregate.ToString().ToUpperInvariant());
            }
            return new RedisInt("ZUNIONSTORE", args.ToArray());
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static RedisStatus.Nullable Set(string key, object value, int? expirationSeconds = null, long? expirationMilliseconds = null, RedisExistence? exists = null)
        {
            var args = new List<object> { key, value };
            if (expirationSeconds != null)
                args.AddRange(new[] { "EX", expirationSeconds.ToString() });
            if (expirationMilliseconds != null)
                args.AddRange(new[] { "PX", expirationMilliseconds.ToString() });
            if (exists != null)
                args.AddRange(new[] { exists.ToString().ToUpperInvariant() });
            return new RedisStatus.Nullable("SET", args.ToArray());
        }

19 View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RedisArray.Generic<Dictionary<string, string>> Sort(string key, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, bool? isHash = null, params string[] get)
        {
            List<string> args = new List<string>();
            args.Add(key);
            if (by != null)
                args.AddRange(new[] { "BY", by });
            if (offset.HasValue && count.HasValue)
                args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
            foreach (var pattern in get)
                args.AddRange(new[] { "GET", pattern });
            if (dir.HasValue)
                args.Add(dir.ToString().ToUpperInvariant());
            if (isAlpha.HasValue && isAlpha.Value)
                args.Add("ALPHA");
            return new RedisArray.Generic<Dictionary<string,string>>(new RedisHash("SORT", args.ToArray()));
        }

19 View Source File : SeedData.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static void SeedClientUris(IAdminStore<Enreplacedy.ClientUri> clientUriStore, ISModels.Client client)
        {
            var uris = client.RedirectUris.Select(o => new Enreplacedy.ClientUri
            {
                Id = Guid.NewGuid().ToString(),
                ClientId = client.ClientId,
                Uri = o
            }).ToList();

            foreach (var origin in client.AllowedCorsOrigins)
            {
                var cors = new Uri(origin);
                var uri = uris.FirstOrDefault(u => cors.CorsMatch(u.Uri));
                var corsUri = new Uri(origin);
                var sanetized = $"{corsUri.Scheme.ToUpperInvariant()}://{corsUri.Host.ToUpperInvariant()}:{corsUri.Port}";

                if (uri == null)
                {

                    uris.Add(new Enreplacedy.ClientUri
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = client.ClientId,
                        Uri = origin,
                        Kind = Enreplacedy.UriKinds.Cors,
                        SanetizedCorsUri = sanetized
                    });
                    continue;
                }

                uri.SanetizedCorsUri = sanetized;
                uri.Kind = Enreplacedy.UriKinds.Redirect | Enreplacedy.UriKinds.Cors;
            }

            foreach (var postLogout in client.PostLogoutRedirectUris)
            {
                var uri = uris.FirstOrDefault(u => u.Uri == postLogout);
                if (uri == null)
                {
                    uris.Add(new Enreplacedy.ClientUri
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = client.ClientId,
                        Uri = postLogout,
                        Kind = Enreplacedy.UriKinds.PostLogout
                    });
                    continue;
                }

                uri.Kind |= Enreplacedy.UriKinds.Redirect;
            }

            foreach (var uri in uris)
            {
                try
                {
                    clientUriStore.CreateAsync(uri).GetAwaiter().GetResult();
                }
                catch (ArgumentException)
                {
                    // silent
                }
            }
        }

19 View Source File : QueryableExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static IQueryable<replacedem> Sort<replacedem>(this IQueryable<replacedem> query, string orderByExpression, Func<IQueryable<replacedem>, string, string, IQueryable<replacedem>> func = null)
        {
            orderByExpression = orderByExpression ?? throw new ArgumentNullException(nameof(orderByExpression));

            var terms = orderByExpression.Split(' ');
            var field = terms[0];
            var direction = terms.Length > 1 ? terms[1] : "ASC";
            if (func != null)
            {
                return func(query, field, direction);
            }

            if (direction.ToUpperInvariant() == "DESC")
            {
                return query.OrderByDescending(field);
            }

            return query.OrderBy(field);
        }

19 View Source File : EntityExtension.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static bool CorsMatch(this Uri cors, Uri uri)
        {
            cors = cors ?? throw new ArgumentNullException(nameof(cors));
            uri = uri ?? throw new ArgumentNullException(nameof(uri));

            return uri.Scheme.ToUpperInvariant() == cors.Scheme.ToUpperInvariant() &&
                uri.Host.ToUpperInvariant() == cors.Host.ToUpperInvariant() &&
                uri.Port == cors.Port;
        }

19 View Source File : SeedData.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static void SeedClientUris(IAdminStore<Enreplacedy.ClientUri> clientUriStore, IdenreplacedyServer4.Models.Client client)
        {
            var uris = client.RedirectUris.Select(o => new Enreplacedy.ClientUri
            {
                Id = Guid.NewGuid().ToString(),
                ClientId = client.ClientId,
                Uri = o
            }).ToList();

            foreach (var origin in client.AllowedCorsOrigins)
            {
                var cors = new Uri(origin);
                var uri = uris.FirstOrDefault(u => cors.CorsMatch(u.Uri));
                var corsUri = new Uri(origin);
                var sanetized = $"{corsUri.Scheme.ToUpperInvariant()}://{corsUri.Host.ToUpperInvariant()}:{corsUri.Port}";

                if (uri == null)
                {

                    uris.Add(new Enreplacedy.ClientUri
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = client.ClientId,
                        Uri = origin,
                        Kind = Enreplacedy.UriKinds.Cors,
                        SanetizedCorsUri = sanetized
                    });
                    continue;
                }

                uri.SanetizedCorsUri = sanetized;
                uri.Kind = Enreplacedy.UriKinds.Redirect | Enreplacedy.UriKinds.Cors;
            }

            foreach (var postLogout in client.PostLogoutRedirectUris)
            {
                var uri = uris.FirstOrDefault(u => u.Uri == postLogout);
                if (uri == null)
                {
                    uris.Add(new Enreplacedy.ClientUri
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = client.ClientId,
                        Uri = postLogout,
                        Kind = Enreplacedy.UriKinds.PostLogout
                    });
                    continue;
                }

                uri.Kind |= Enreplacedy.UriKinds.Redirect;
            }

            foreach (var uri in uris)
            {
                clientUriStore.CreateAsync(uri).GetAwaiter().GetResult();
            }
        }

19 View Source File : Client.razor.cs
License : Apache License 2.0
Project Creator : Aguafrommars

protected override void SanetizeEnreplacedyToSaved<TEnreplacedy>(TEnreplacedy enreplacedy)
        {
            if (enreplacedy is Enreplacedy.Client client)
            {
                Model.Id = client.Id;
            }
            if (enreplacedy is Enreplacedy.IClientSubEnreplacedy subEnreplacedy)
            {
                subEnreplacedy.ClientId = Model.Id;
            }
            if (enreplacedy is Enreplacedy.ClientUri clientUri && clientUri.Uri != null)
            {
                if ((clientUri.Kind & Enreplacedy.UriKinds.Cors) == Enreplacedy.UriKinds.Cors)
                {
                    var corsUri = new Uri(clientUri.Uri);
                    clientUri.SanetizedCorsUri = $"{corsUri.Scheme.ToUpperInvariant()}://{corsUri.Host.ToUpperInvariant()}:{corsUri.Port}";
                    return;
                }
                clientUri.SanetizedCorsUri = null;
            }
            if (enreplacedy is Enreplacedy.ClientSecret secret && secret.Id == null && secret.Type == SecretTypes.SharedSecret)
            {
                secret.Value = secret.Value.Sha256();
            }
        }

19 View Source File : RegisterClientService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static void ValidateRedirectUri(ClientRegisteration registration, string uri, Uri redirectUri)
        {
            if (registration.ApplicationType == "web" &&
                                registration.GrantTypes.Contains("implicit"))
            {
                if (redirectUri.Scheme != "https")
                {
                    throw new RegistrationException("invalid_redirect_uri", $"Invalid RedirectUri '{uri}'. Implicit client must use 'https' scheme only.");
                }
                if (redirectUri.Host.ToUpperInvariant() == "LOCALHOST")
                {
                    throw new RegistrationException("invalid_redirect_uri", $"Invalid RedirectUri '{uri}'. Implicit client cannot use 'localhost' host.");
                }
            }
            if (registration.ApplicationType == "native")
            {
                if (redirectUri.Scheme == Uri.UriSchemeGopher ||
                    redirectUri.Scheme == Uri.UriSchemeHttps ||
                    redirectUri.Scheme == Uri.UriSchemeNews ||
                    redirectUri.Scheme == Uri.UriSchemeNntp)
                {
                    throw new RegistrationException("invalid_redirect_uri", $"Invalid RedirectUri '{uri}'.Native client cannot use standard '{redirectUri.Scheme}' scheme, you must use a custom scheme such as 'net.pipe' or 'net.tcp', or 'http' scheme with 'localhost' host.");
                }
                if (redirectUri.Scheme == Uri.UriSchemeHttp && redirectUri.Host.ToUpperInvariant() != "LOCALHOST")
                {
                    throw new RegistrationException("invalid_redirect_uri", $"Invalid RedirectUri '{uri}'.Only 'localhost' host is allowed for 'http' scheme and 'native' client.");
                }
            }
        }

19 View Source File : CorsPolicyService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async Task<bool> IsOriginAllowedAsync(string origin)
        {
            var corsUri = new Uri(origin);
            var sanetized = $"{corsUri.Scheme.ToUpperInvariant()}://{corsUri.Host.ToUpperInvariant()}:{corsUri.Port}";
            var response = await _store.GetAsync(new PageRequest
            {
                Filter = $"{nameof(ClientUri.SanetizedCorsUri)} eq '{sanetized}'",
                Select = nameof(ClientUri.SanetizedCorsUri)
            }).ConfigureAwait(false);
            return response.Count > 0;
        }

19 View Source File : WsFederationControllerTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

[Fact]
        public async Task Index_should_return_signin_doreplacedent_when_user_found()
        {
            var configuration = new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = "Development",
                ["Seed"] = "true"
            };
            var userSessionMock = new Mock<IUserSession>();
            var sub = Guid.NewGuid().ToString();
            var name = Guid.NewGuid().ToString();
            var user = new ClaimsPrincipal(
                new ClaimsIdenreplacedy(
                    new[]
                    {
                        new Claim("name", name),
                        new Claim("sub", sub),
                        new Claim("amr", Guid.NewGuid().ToString())
                    },
                    "wsfed",
                    "name",
                    "role"));
            userSessionMock.Setup(m => m.GetUserAsync()).ReturnsAsync(user);

            var sut = TestUtils.CreateTestServer(services =>
            {
                services.AddTransient(p => userSessionMock.Object);
            }, configuration, configureEndpoints: _configureEndpoints);

            using var scope = sut.Services.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();

            var clientId = $"urn:{Guid.NewGuid()}";
            await context.Clients.AddAsync(new Client
            {
                Id = clientId,
                Enabled = true,
                ProtocolType = IdenreplacedyServerConstants.ProtocolTypes.WsFederation,
                AllowedScopes = new[]
                {
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "openid"
                    },
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "profile"
                    }
                },
                RelyingParty = new RelyingParty
                {
                    Id = clientId,
                    TokenType = IdenreplacedyServer4.WsFederation.WsFederationConstants.TokenTypes.Saml11TokenProfile11,
                    DigestAlgorithm = SecurityAlgorithms.Sha256Digest,
                    SignatureAlgorithm = SecurityAlgorithms.RsaSha256Signature,
                    SamlNameIdentifierFormat = IdenreplacedyServer4.WsFederation.WsFederationConstants.SamlNameIdentifierFormats.UnspecifiedString,
                    ClaimMappings = new[]
                    {
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Name,
                            ToClaimType = ClaimTypes.Name
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Subject,
                            ToClaimType = ClaimTypes.NameIdentifier
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Email,
                            ToClaimType = ClaimTypes.Email
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.GivenName,
                            ToClaimType = ClaimTypes.GivenName
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.FamilyName,
                            ToClaimType = ClaimTypes.Surname
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.BirthDate,
                            ToClaimType = ClaimTypes.DateOfBirth
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.WebSite,
                            ToClaimType = ClaimTypes.Webpage
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Gender,
                            ToClaimType = ClaimTypes.Gender
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Role,
                            ToClaimType = ClaimTypes.Role
                        }
                    }
                }
            }).ConfigureAwait(false);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var idenreplacedyContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            await idenreplacedyContext.Users.AddAsync(new User
            {
                Id = sub,
                UserName = name,
                NormalizedUserName = name.ToUpperInvariant(),
                SecurityStamp = Guid.NewGuid().ToString()
            }).ConfigureAwait(false);
            await idenreplacedyContext.SaveChangesAsync().ConfigureAwait(false);

            using var client = sut.CreateClient();
            using var response = await client.GetAsync($"/wsfederation?wtrealm={clientId}&wa=wsignin1.0&wreply={client.BaseAddress}");

            replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

            var content = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            replacedert.NotNull(content);
        }

19 View Source File : WsFederationControllerTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

[Fact]
        public async Task Index_should_return_signin_doreplacedent_with_client_claim_when_user_found()
        {
            var configuration = new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = "Development",
                ["Seed"] = "true"
            };
            var sub = Guid.NewGuid().ToString();
            var name = Guid.NewGuid().ToString();
            var user = new ClaimsPrincipal(
                new ClaimsIdenreplacedy(
                    new[]
                    {
                        new Claim(JwtClaimTypes.Name, name),
                        new Claim(JwtClaimTypes.Subject, sub),
                        new Claim(JwtClaimTypes.AuthenticationMethod, OidcConstants.AuthenticationMethods.Preplacedword)
                    },
                    "wsfed",
                    "name",
                    "role"));

            var userSessionMock = new Mock<IUserSession>();
            userSessionMock.Setup(m => m.GetUserAsync()).ReturnsAsync(user);

            var profileServiceMock = new Mock<IProfileService>();
            profileServiceMock.Setup(m => m.GetProfileDataAsync(It.IsAny<ISModels.ProfileDataRequestContext>()))
                .Callback<ISModels.ProfileDataRequestContext>(ctx => ctx.IssuedClaims = new List<Claim>
                {
                    new Claim(JwtClaimTypes.Name, name),
                    new Claim(JwtClaimTypes.Subject, sub),
                    new Claim("http://exemple.com", Guid.NewGuid().ToString()),
                })
                .Returns(Task.CompletedTask);

            var sut = TestUtils.CreateTestServer(services =>
            {
                services.AddTransient(p => userSessionMock.Object)
                    .AddTransient(p => profileServiceMock.Object);
            }, configuration, configureEndpoints: _configureEndpoints);

            using var scope = sut.Services.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();

            var clientId = $"urn:{Guid.NewGuid()}";
            await context.Clients.AddAsync(new Client
            {
                Id = clientId,
                Enabled = true,
                ProtocolType = IdenreplacedyServerConstants.ProtocolTypes.WsFederation,
                AllowedScopes = new[]
                {
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "openid"
                    },
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "profile"
                    }
                },
                ClientClaims = new[]
                {
                    new ClientClaim
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Type = "http://myorg.com/claim",
                        Value = Guid.NewGuid().ToString()
                    }
                },
                RelyingParty = new RelyingParty
                {
                    Id = clientId,
                    TokenType = IdenreplacedyServer4.WsFederation.WsFederationConstants.TokenTypes.Saml11TokenProfile11,
                    DigestAlgorithm = SecurityAlgorithms.Sha256Digest,
                    SignatureAlgorithm = SecurityAlgorithms.RsaSha256Signature,
                    SamlNameIdentifierFormat = IdenreplacedyServer4.WsFederation.WsFederationConstants.SamlNameIdentifierFormats.UnspecifiedString,
                    ClaimMappings = new[]
                    {
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Name,
                            ToClaimType = ClaimTypes.Name
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Subject,
                            ToClaimType = ClaimTypes.NameIdentifier
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Email,
                            ToClaimType = ClaimTypes.Email
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.GivenName,
                            ToClaimType = ClaimTypes.GivenName
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.FamilyName,
                            ToClaimType = ClaimTypes.Surname
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.BirthDate,
                            ToClaimType = ClaimTypes.DateOfBirth
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.WebSite,
                            ToClaimType = ClaimTypes.Webpage
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Gender,
                            ToClaimType = ClaimTypes.Gender
                        },
                        new RelyingPartyClaimMapping
                        {
                            Id = Guid.NewGuid().ToString(),
                            RelyingPartyId = clientId,
                            FromClaimType = JwtClaimTypes.Role,
                            ToClaimType = ClaimTypes.Role
                        }
                    }
                }
            }).ConfigureAwait(false);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var idenreplacedyContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            await idenreplacedyContext.Users.AddAsync(new User
            {
                Id = sub,
                UserName = name,
                NormalizedUserName = name.ToUpperInvariant(),
                SecurityStamp = Guid.NewGuid().ToString()
            }).ConfigureAwait(false);
            await idenreplacedyContext.SaveChangesAsync().ConfigureAwait(false);

            using var client = sut.CreateClient();
            using var response = await client.GetAsync($"/wsfederation?wtrealm={clientId}&wa=wsignin1.0&wreply={client.BaseAddress}");

            replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

            var content = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            replacedert.NotNull(content);
            replacedert.Contains("exemple.com", content);
            replacedert.Contains("myorg.com", content);
        }

19 View Source File : EntityExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static bool CorsMatch(this Uri cors, string url)
        {
            cors = cors ?? throw new ArgumentNullException(nameof(cors));
            url = url ?? throw new ArgumentNullException(nameof(url));
            var uri = new Uri(url);
            return uri.Scheme.ToUpperInvariant() == cors.Scheme.ToUpperInvariant() &&
                uri.Host.ToUpperInvariant() == cors.Host.ToUpperInvariant() &&
                uri.Port == cors.Port;
        }

19 View Source File : WsFederationControllerTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

[Fact]
        public async Task Index_should_return_signin_doreplacedent_for_saml2_token_type_when_user_found()
        {
            var configuration = new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = "Development",
                ["Seed"] = "true"
            };
            var sub = Guid.NewGuid().ToString();
            var name = Guid.NewGuid().ToString();
            var user = new ClaimsPrincipal(
                new ClaimsIdenreplacedy(
                    new[]
                    {
                        new Claim(JwtClaimTypes.Name, name),
                        new Claim(JwtClaimTypes.Subject, sub),
                        new Claim(JwtClaimTypes.AuthenticationMethod, OidcConstants.AuthenticationMethods.Preplacedword)
                    },
                    "wsfed",
                    "name",
                    "role"));

            var userSessionMock = new Mock<IUserSession>();
            userSessionMock.Setup(m => m.GetUserAsync()).ReturnsAsync(user);

            var profileServiceMock = new Mock<IProfileService>();
            profileServiceMock.Setup(m => m.GetProfileDataAsync(It.IsAny<ISModels.ProfileDataRequestContext>()))
                .Callback<ISModels.ProfileDataRequestContext>(ctx => ctx.IssuedClaims = new List<Claim>
                {
                    new Claim(JwtClaimTypes.Name, name),
                    new Claim(JwtClaimTypes.Subject, sub),
                    new Claim("exemple.com", Guid.NewGuid().ToString()),
                })
                .Returns(Task.CompletedTask);

            var sut = TestUtils.CreateTestServer(services =>
            {
                services.AddTransient(p => userSessionMock.Object)
                    .AddTransient(p => profileServiceMock.Object);
            }, configuration, configureEndpoints: _configureEndpoints);

            using var scope = sut.Services.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();

            var clientId = $"urn:{Guid.NewGuid()}";
            await context.Clients.AddAsync(new Client
            {
                Id = clientId,
                Enabled = true,
                ProtocolType = IdenreplacedyServerConstants.ProtocolTypes.WsFederation,
                AllowedScopes = new[]
                {
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "openid"
                    },
                    new ClientScope
                    {
                        Id = Guid.NewGuid().ToString(),
                        ClientId = clientId,
                        Scope = "profile"
                    }
                },
                RelyingParty = new RelyingParty
                {
                    Id = clientId,
                    TokenType = IdenreplacedyServer4.WsFederation.WsFederationConstants.TokenTypes.Saml2TokenProfile11,
                    DigestAlgorithm = SecurityAlgorithms.Sha256Digest,
                    SignatureAlgorithm = SecurityAlgorithms.RsaSha256Signature,
                    SamlNameIdentifierFormat = IdenreplacedyServer4.WsFederation.WsFederationConstants.SamlNameIdentifierFormats.UnspecifiedString,
                    ClaimMappings = Array.Empty<RelyingPartyClaimMapping>()
                }
            }).ConfigureAwait(false);
            await context.SaveChangesAsync().ConfigureAwait(false);

            var idenreplacedyContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            await idenreplacedyContext.Users.AddAsync(new User
            {
                Id = sub,
                UserName = name,
                NormalizedUserName = name.ToUpperInvariant(),
                SecurityStamp = Guid.NewGuid().ToString()
            }).ConfigureAwait(false);
            await idenreplacedyContext.SaveChangesAsync().ConfigureAwait(false);

            using var client = sut.CreateClient();
            using var response = await client.GetAsync($"/wsfederation?wtrealm={clientId}&wa=wsignin1.0&wreply={client.BaseAddress}");

            replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

            var content = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            replacedert.NotNull(content);
            replacedert.Contains("exemple.com", content);
        }

19 View Source File : GeneratorTools.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static void ReplaceKey(ref string lua, string key, object value)
        {
            string valueStr = Toolbox.ValToString(value);
            if (value is bool) valueStr = valueStr.ToLowerInvariant();

            lua = lua.Replace($"${key.ToUpperInvariant()}$", valueStr);
        }

19 View Source File : DCSMission.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal string ReplaceValues(string rawText)
        {
            if (rawText == null) return null;

            foreach (KeyValuePair<string, string> keyPair in Values) // Replace included scripts first so later replacements (objective count, player coalition, etc) will be applied to them too
            {
                if (!keyPair.Key.ToLowerInvariant().StartsWith("script")) continue;
                rawText = rawText.Replace($"${keyPair.Key.ToUpperInvariant()}$", keyPair.Value);
            }

            foreach (KeyValuePair<string, string> keyPair in Values) // Replace other values
                rawText = rawText.Replace($"${keyPair.Key.ToUpperInvariant()}$", keyPair.Value);

            return rawText;
        }

19 View Source File : DCSMission.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

private void SetValue(string key, string value, bool append)
        {
            if (string.IsNullOrEmpty(key)) return;
            key = key.ToUpperInvariant();
            value = value ?? "";
            value = value.Replace("\r\n", "\n");

            string displayedValue = value.Replace("\n", " ");
            if (displayedValue.Length > MAX_VALUE_LENGTH_DISPLAY) displayedValue = displayedValue.Substring(0, MAX_VALUE_LENGTH_DISPLAY) + "...";

            BriefingRoom.PrintToLog($"Mission parameter \"{key.ToLowerInvariant()}\" {(append ? "appended with" : "set to")} \"{displayedValue}\".");

            if (!Values.ContainsKey(key))
                Values.Add(key, value);
            else
                Values[key] = append ? Values[key] + value : value;
        }

19 View Source File : DatabaseEntryInfo.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

public string GetNameAndDescription(string separator = " - ", bool upperCaseName = false)
        {
            string casedName = upperCaseName ? Name.ToUpperInvariant() : Name;

            if (string.IsNullOrEmpty(Description)) return casedName;
            return $"{casedName}{separator}{Description}";
        }

19 View Source File : EmailHelpers.cs
License : MIT License
Project Creator : alethic

public static bool Validate(string email, bool allowInternational = false)
        {
            var index = 0;

            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            if (email.Length == 0 || email.Length >= 255)
            {
                return false;
            }

            if (!SkipWord(email, ref index, allowInternational) || index >= email.Length)
            {
                return false;
            }

            while (email[index] == '.')
            {
                index++;

                if (index >= email.Length)
                {
                    return false;
                }

                if (!SkipWord(email, ref index, allowInternational))
                {
                    return false;
                }

                if (index >= email.Length)
                {
                    return false;
                }
            }

            if (index + 1 >= email.Length || index > 64 || email[index++] != '@')
            {
                return false;
            }

            if (email[index] != '[')
            {
                // domain
                if (!SkipDomain(email, ref index, allowInternational))
                {
                    return false;
                }

                return index == email.Length;
            }

            // address literal
            index++;

            // we need at least 8 more characters
            if (index + 8 >= email.Length)
            {
                return false;
            }

            var ipv6 = email.Substring(index, 5);
            if (ipv6.ToUpperInvariant() == "IPV6:")
            {
                index += "IPv6:".Length;
                if (!SkipIPv6Literal(email, ref index))
                {
                    return false;
                }
            }
            else
            {
                if (!SkipIPv4Literal(email, ref index))
                {
                    return false;
                }
            }

            if (index >= email.Length || email[index++] != ']')
            {
                return false;
            }

            return index == email.Length;
        }

See More Examples