System.Collections.Generic.ICollection.Add(string)

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

990 Examples 7

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static string GetCrefNamespace(string cref, string @namespace)
        {
            IList<string> sameString = new List<string>();
            var splitNamespace = @namespace.Split('.');
            var splitCref = cref.Split('.');
            int minLength = Math.Min(splitNamespace.Length, splitCref.Length);
            for (int i = 0; i < minLength; i++)
            {
                if (splitCref[i] == splitNamespace[i])
                {
                    sameString.Add(splitCref[i]);
                }
                else
                {
                    break;
                }
            }

            cref = cref.Substring(string.Join('.', sameString).Length + 1);
            return cref;
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

private static string GeneraParameters(IList<ParameterInfo> parameters, bool hasType, bool hasPre)
        {
            StringBuilder sb = new StringBuilder();
            IList<string> list = new List<string>();
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var item in parameters)
                {
                    if (hasType)
                    {
                        list.Add($"{item.Type} {item.Name}");
                    }
                    else
                    {
                        list.Add($"{item.Name}");
                    }
                }

                sb.Append((hasPre ? ", " : string.Empty) + string.Join(", ", list));
            }

            return sb.ToString();
        }

19 View Source File : LProjectDependencies.cs
License : MIT License
Project Creator : 3F

protected void BuildOrder()
        {
            bool h(string id)
            {
                map[id].ForEach(dep => h(dep));
                if(!order.Contains(id)) {
                    order.Add(id);
                }
                return true;
            };

            foreach(KeyValuePair<string, HashSet<string>> project in map)
            {
                h(project.Key);
                if(!order.Contains(project.Key)) {
                    order.Add(project.Key);
                }
            }
        }

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

private static void CompileRule(LanguageRule languageRule,
                                                 StringBuilder regex,
                                                 ICollection<string> captures,
                                                 bool isFirstRule)
        {
            if (!isFirstRule)
            {
                regex.AppendLine();
                regex.AppendLine();
                regex.AppendLine("|");
                regex.AppendLine();
            }
            
            regex.AppendFormat("(?-xis)(?m)({0})(?x)", languageRule.Regex);

            int numberOfCaptures = GetNumberOfCaptures(languageRule.Regex);

            for (int i = 0; i <= numberOfCaptures; i++)
            {
                string scope = null;

                foreach (int captureIndex in languageRule.Captures.Keys)
                {
                    if (i == captureIndex)
                    {
                        scope = languageRule.Captures[captureIndex];
                        break;
                    }
                }

                captures.Add(scope);
            }
        }

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

private static void CompileRules(IList<LanguageRule> rules,
                                         out Regex regex,
                                         out IList<string> captures)
        {
            StringBuilder regexBuilder = new StringBuilder();
            captures = new List<string>();

            regexBuilder.AppendLine("(?x)");
            captures.Add(null);

            CompileRule(rules[0], regexBuilder, captures, true);

            for (int i = 1; i < rules.Count; i++)
                CompileRule(rules[i], regexBuilder, captures, false);

            regex = new Regex(regexBuilder.ToString());
        }

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

private async Task<int> ExecuteGitCommandAsync(RunnerActionPluginExecutionContext context, string repoRoot, string command, string options, IList<string> output)
        {
            string arg = StringUtil.Format($"{command} {options}").Trim();
            context.Command($"git {arg}");

            if (output == null)
            {
                output = new List<string>();
            }

            var processInvoker = new ProcessInvoker(context);
            processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
            {
                output.Add(message.Data);
            };

            processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
            {
                context.Output(message.Data);
            };

            return await processInvoker.ExecuteAsync(
                workingDirectory: repoRoot,
                fileName: gitPath,
                arguments: arg,
                environment: gitEnv,
                requireExitCodeZero: false,
                outputEncoding: s_encoding,
                cancellationToken: default(CancellationToken));
        }

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

public async Task<string> DockerCreate(IExecutionContext context, ContainerInfo container)
        {
            IList<string> dockerOptions = new List<string>();
            // OPTIONS
            dockerOptions.Add($"--name {container.ContainerDisplayName}");
            dockerOptions.Add($"--label {DockerInstanceLabel}");
            if (!string.IsNullOrEmpty(container.ContainerWorkDirectory))
            {
                dockerOptions.Add($"--workdir {container.ContainerWorkDirectory}");
            }
            if (!string.IsNullOrEmpty(container.ContainerNetwork))
            {
                dockerOptions.Add($"--network {container.ContainerNetwork}");
            }
            if (!string.IsNullOrEmpty(container.ContainerNetworkAlias))
            {
                dockerOptions.Add($"--network-alias {container.ContainerNetworkAlias}");
            }
            foreach (var port in container.UserPortMappings)
            {
                dockerOptions.Add($"-p {port.Value}");
            }
            dockerOptions.Add($"{container.ContainerCreateOptions}");
            foreach (var env in container.ContainerEnvironmentVariables)
            {
                if (String.IsNullOrEmpty(env.Value))
                {
                    dockerOptions.Add($"-e \"{env.Key}\"");
                }
                else
                {
                    dockerOptions.Add($"-e \"{env.Key}={env.Value.Replace("\"", "\\\"")}\"");
                }
            }

            // Watermark for GitHub Action environment
            dockerOptions.Add("-e GITHUB_ACTIONS=true");

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!container.ContainerEnvironmentVariables.ContainsKey("CI"))
            {
                dockerOptions.Add("-e CI=true");
            }

            foreach (var volume in container.MountVolumes)
            {
                // replace `"` with `\"` and add `"{0}"` to all path.
                String volumeArg;
                if (String.IsNullOrEmpty(volume.SourceVolumePath))
                {
                    // Anonymous docker volume
                    volumeArg = $"-v \"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
                }
                else
                {
                    // Named Docker volume / host bind mount
                    volumeArg = $"-v \"{volume.SourceVolumePath.Replace("\"", "\\\"")}\":\"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
                }
                if (volume.ReadOnly)
                {
                    volumeArg += ":ro";
                }
                dockerOptions.Add(volumeArg);
            }
            if (!string.IsNullOrEmpty(container.ContainerEntryPoint))
            {
                dockerOptions.Add($"--entrypoint \"{container.ContainerEntryPoint}\"");
            }
            // IMAGE
            dockerOptions.Add($"{container.ContainerImage}");

            // COMMAND
            // Intentionally blank. Always overwrite ENTRYPOINT and/or send ARGs

            // [ARG...]
            dockerOptions.Add($"{container.ContainerEntryPointArgs}");

            var optionsString = string.Join(" ", dockerOptions);
            List<string> outputStrings = await ExecuteDockerCommandAsync(context, "create", optionsString);

            return outputStrings.FirstOrDefault();
        }

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

public async Task<int> DockerRun(IExecutionContext context, ContainerInfo container, EventHandler<ProcessDataReceivedEventArgs> stdoutDataReceived, EventHandler<ProcessDataReceivedEventArgs> stderrDataReceived)
        {
            IList<string> dockerOptions = new List<string>();
            // OPTIONS
            dockerOptions.Add($"--name {container.ContainerDisplayName}");
            dockerOptions.Add($"--label {DockerInstanceLabel}");

            dockerOptions.Add($"--workdir {container.ContainerWorkDirectory}");
            dockerOptions.Add($"--rm");

            foreach (var env in container.ContainerEnvironmentVariables)
            {
                // e.g. -e MY_SECRET maps the value into the exec'ed process without exposing
                // the value directly in the command
                dockerOptions.Add($"-e {env.Key}");
            }

            // Watermark for GitHub Action environment
            dockerOptions.Add("-e GITHUB_ACTIONS=true");

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!container.ContainerEnvironmentVariables.ContainsKey("CI"))
            {
                dockerOptions.Add("-e CI=true");
            }

            if (!string.IsNullOrEmpty(container.ContainerEntryPoint))
            {
                dockerOptions.Add($"--entrypoint \"{container.ContainerEntryPoint}\"");
            }

            if (!string.IsNullOrEmpty(container.ContainerNetwork))
            {
                dockerOptions.Add($"--network {container.ContainerNetwork}");
            }

            foreach (var volume in container.MountVolumes)
            {
                // replace `"` with `\"` and add `"{0}"` to all path.
                String volumeArg;
                if (String.IsNullOrEmpty(volume.SourceVolumePath))
                {
                    // Anonymous docker volume
                    volumeArg = $"-v \"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
                }
                else
                {
                    // Named Docker volume / host bind mount
                    volumeArg = $"-v \"{volume.SourceVolumePath.Replace("\"", "\\\"")}\":\"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
                }
                if (volume.ReadOnly)
                {
                    volumeArg += ":ro";
                }
                dockerOptions.Add(volumeArg);
            }
            // IMAGE
            dockerOptions.Add($"{container.ContainerImage}");

            // COMMAND
            // Intentionally blank. Always overwrite ENTRYPOINT and/or send ARGs

            // [ARG...]
            dockerOptions.Add($"{container.ContainerEntryPointArgs}");

            var optionsString = string.Join(" ", dockerOptions);
            return await ExecuteDockerCommandAsync(context, "run", optionsString, container.ContainerEnvironmentVariables, stdoutDataReceived, stderrDataReceived, context.CancellationToken);
        }

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

public async Task<int> ExecuteAsync(string workingDirectory,
                                            string fileName,
                                            string arguments,
                                            IDictionary<string, string> environment,
                                            bool requireExitCodeZero,
                                            Encoding outputEncoding,
                                            bool killProcessOnCancel,
                                            bool inheritConsoleHandler,
                                            CancellationToken cancellationToken)
        {
            // make sure container exist.
            ArgUtil.NotNull(Container, nameof(Container));
            ArgUtil.NotNullOrEmpty(Container.ContainerId, nameof(Container.ContainerId));

            var dockerManager = HostContext.GetService<IDockerCommandManager>();
            string dockerClientPath = dockerManager.DockerPath;

            // Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
            IList<string> dockerCommandArgs = new List<string>();
            dockerCommandArgs.Add($"exec");

            // [OPTIONS]
            dockerCommandArgs.Add($"-i");
            dockerCommandArgs.Add($"--workdir {workingDirectory}");
            foreach (var env in environment)
            {
                // e.g. -e MY_SECRET maps the value into the exec'ed process without exposing
                // the value directly in the command
                dockerCommandArgs.Add($"-e {env.Key}");
            }
            if (!string.IsNullOrEmpty(PrependPath))
            {
                // Prepend tool paths to container's PATH
                var fullPath = !string.IsNullOrEmpty(Container.ContainerRuntimePath) ? $"{PrependPath}:{Container.ContainerRuntimePath}" : PrependPath;
                dockerCommandArgs.Add($"-e PATH=\"{fullPath}\"");
            }

            // CONTAINER
            dockerCommandArgs.Add($"{Container.ContainerId}");

            // COMMAND
            dockerCommandArgs.Add(fileName);

            // [ARG...]
            dockerCommandArgs.Add(arguments);

            string dockerCommandArgstring = string.Join(" ", dockerCommandArgs);

            // make sure all env are using container path
            foreach (var envKey in environment.Keys.ToList())
            {
                environment[envKey] = this.Container.TranslateToContainerPath(environment[envKey]);
            }

            using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
            {
                processInvoker.OutputDataReceived += OutputDataReceived;
                processInvoker.ErrorDataReceived += ErrorDataReceived;

#if OS_WINDOWS
                // It appears that node.exe outputs UTF8 when not in TTY mode.
                outputEncoding = Encoding.UTF8;
#else
                // Let .NET choose the default.
                outputEncoding = null;
#endif

                return await processInvoker.ExecuteAsync(workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work),
                                                         fileName: dockerClientPath,
                                                         arguments: dockerCommandArgstring,
                                                         environment: environment,
                                                         requireExitCodeZero: requireExitCodeZero,
                                                         outputEncoding: outputEncoding,
                                                         killProcessOnCancel: killProcessOnCancel,
                                                         redirectStandardIn: null,
                                                         inheritConsoleHandler: inheritConsoleHandler,
                                                         cancellationToken: cancellationToken);
            }
        }

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

[EditorBrowsable(EditorBrowsableState.Never)]
        public async Task<HttpResponseMessage> UploadFileAsync(
            Int64 containerId,
            String itemPath,
            Stream fileStream,
            byte[] contentId,
            Int64 fileLength,
            Boolean isGzipped,
            Guid scopeIdentifier,
            CancellationToken cancellationToken = default(CancellationToken),
            int chunkSize = c_defaultChunkSize,
            int chunkRetryTimes = c_defaultChunkRetryTimes,
            bool uploadFirstChunk = false,
            Object userState = null)
        {
            if (containerId < 1)
            {
                throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
            }

            if (chunkSize > c_maxChunkSize)
            {
                chunkSize = c_maxChunkSize;
            }

            // if a contentId is specified but the chunk size is not a 2mb multiple error
            if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
            {
                throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
            }

            ArgumentUtility.CheckForNull(fileStream, "fileStream");

            ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
            ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);

            if (isGzipped
                && (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
                    || (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
            {
                throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
            }

            if (isGzipped && fileStream.Length >= fileLength)
            {
                throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
            }

            HttpRequestMessage requestMessage = null;
            List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);

            if (fileStream.Length == 0)
            {
                // zero byte upload
                FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
                requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
                return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
            }

            bool multiChunk = false;
            int totalChunks = 1;
            if (fileStream.Length > chunkSize)
            {
                totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
                FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
                multiChunk = true;
            }
            else
            {
                FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
                chunkSize = (int)fileStream.Length;
            }

            StreamParser streamParser = new StreamParser(fileStream, chunkSize);
            SubStream currentStream = streamParser.GetNextStream();
            HttpResponseMessage response = null;

            Byte[] dataToSend = new Byte[chunkSize];
            int currentChunk = 0;
            Stopwatch uploadTimer = new Stopwatch();
            while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
            {
                currentChunk++;

                for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
                {
                    if (attempt > 1)
                    {
                        TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
                        FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
                        await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
                        currentStream.Seek(0, SeekOrigin.Begin);
                    }

                    FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");

                    // inorder for the upload to be retryable, we need the content to be re-readable
                    // to ensure this we copy the chunk into a byte array and send that
                    // chunk size ensures we can convert the length to an int
                    int bytesToCopy = (int)currentStream.Length;
                    using (MemoryStream ms = new MemoryStream(dataToSend))
                    {
                        await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
                    }

                    // set the content and the Content-Range header
                    HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    byteArrayContent.Headers.ContentLength = currentStream.Length;
                    byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
                                                                                                             currentStream.EndingPostionOnOuterStream,
                                                                                                             streamParser.Length);
                    FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");

                    try
                    {
                        if (requestMessage != null)
                        {
                            requestMessage.Dispose();
                            requestMessage = null;
                        }

                        requestMessage = await CreateRequestMessageAsync(
                            HttpMethod.Put,
                            FileContainerResourceIds.FileContainer,
                            routeValues: new { containerId = containerId },
                            version: s_currentApiVersion,
                            content: byteArrayContent,
                            queryParameters: query,
                            userState: userState,
                            cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
                        continue;
                    }

                    if (isGzipped)
                    {
                        //add gzip header info
                        byteArrayContent.Headers.ContentEncoding.Add("gzip");
                        byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    if (contentId != null)
                    {
                        byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
                    }

                    FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
                    uploadTimer.Restart();

                    try
                    {
                        if (response != null)
                        {
                            response.Dispose();
                            response = null;
                        }

                        response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
                        continue;
                    }

                    uploadTimer.Stop();
                    FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");

                    if (multiChunk)
                    {
                        FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else if (IsFastFailResponse(response))
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
                        break;
                    }
                    else
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
                        continue;
                    }
                }

                // if we don't have success then bail and return the failed response
                if (!response.IsSuccessStatusCode)
                {
                    break;
                }

                if (contentId != null && response.StatusCode == HttpStatusCode.Created)
                {
                    // no need to keep uploading since the server said it has all the content
                    FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
                    break;
                }

                currentStream = streamParser.GetNextStream();
                if (uploadFirstChunk)
                {
                    break;
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            return response;
        }

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

private void UpdateSuggestedList(string text)
        {
            //TODO: BROKEN

            var filter = text;

            if (filter.StartsWith(@"Computer\", StringComparison.InvariantCultureIgnoreCase))
                filter = filter.Remove(0, @"Computer\".Length);

            listViewSuggestion.ItemsSource = null;

            if (string.IsNullOrEmpty(filter))
            {
                IList<string> str = new List<string>();

                foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    str.Add(@"Computer\" + x.Name);

                listViewSuggestion.ItemsSource = str;
            }
            else
            {
                var splitted = filter.Split(new char[] { '\\' }, 2);
                if (splitted.Length >= 2)
                {
                    splitted[1] = splitted[1].Trim();

                    List<RegistryHive> registries = new List<RegistryHive>();

                    foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    {
                        if (x.Name.Equals(splitted[0], StringComparison.InvariantCultureIgnoreCase))
                            registries.Add(x.AttachedHive);
                    }

                    IList<string> str = new List<string>();
                    var subSplitted = splitted[1].Split(new char[] { '\\' });

                    var subIncorporated = string.Join("\\", subSplitted, 0, subSplitted.Length - 1);

                    foreach (var reg in registries)
                    {

                        var key = reg.Root.OpenSubKey(splitted[1] == "" ? "\\" : subIncorporated);
                        if (key != null)
                            foreach (var subKey in key.SubKeys)
                                str.Add(@"Computer\" + splitted[0] + subKey.Name); //TODO

                    }

                    if (subSplitted.Length >= 1 && !string.IsNullOrEmpty(subSplitted[0]))
                        str = str.Where(x => x.StartsWith(@"Computer\" + splitted[0] + "\\" + splitted[1], StringComparison.InvariantCultureIgnoreCase)).ToList();

                    listViewSuggestion.ItemsSource = str;
                }
                else
                {
                    IList<string> str = new List<string>();

                    foreach (var x in treeRoot[0].RegistryHiveTreeViews)
                    {
                        if (x.Name.StartsWith(splitted[0], StringComparison.InvariantCultureIgnoreCase))
                            str.Add(@"Computer\" + x.Name);
                    }

                    listViewSuggestion.ItemsSource = str;
                }
            }
        }

19 View Source File : CecilDefinitionsFactory.cs
License : MIT License
Project Creator : adrianoc

private static void ProcessGenericTypeParameters(string memberDefVar, IVisitorContext context, IList<TypeParameterSyntax> typeParamList, IList<string> exps)
        {
            // forward declare all generic type parameters to allow one type parameter to reference any of the others; this is useful in constraints for example:
            // clreplaced Foo<T,S> where T: S  { }
            var tba = new List<(string genParamDefVar, ITypeParameterSymbol typeParameterSymbol)>();
            foreach (var typeParameter in typeParamList)
            {
                var symbol = context.SemanticModel.GetDeclaredSymbol(typeParameter);
                var genericParamName = typeParameter.Identifier.Text;
                
                var genParamDefVar = context.Naming.GenericParameterDeclaration(typeParameter);

                context.DefinitionVariables.RegisterNonMethod(string.Empty, genericParamName, MemberKind.TypeParameter, genParamDefVar);
                exps.Add(GenericParameter(context, memberDefVar, genericParamName, genParamDefVar, symbol));
                
                tba.Add((genParamDefVar, symbol));
            }
            
            foreach (var entry in tba)
            {
                AddConstraints(entry.genParamDefVar, entry.typeParameterSymbol);
                exps.Add($"{memberDefVar}.GenericParameters.Add({entry.genParamDefVar});");
            }
            
            void AddConstraints(string genParamDefVar, ITypeParameterSymbol typeParam)
            {
                if (typeParam.HasConstructorConstraint || typeParam.HasValueTypeConstraint) // struct constraint implies new()
                {
                    exps.Add($"{genParamDefVar}.HasDefaultConstructorConstraint = true;");
                }

                if (typeParam.HasReferenceTypeConstraint)
                {
                    exps.Add($"{genParamDefVar}.HasReferenceTypeConstraint = true;");
                }
                
                if (typeParam.HasValueTypeConstraint)
                {
                    var systemValueTypeRef = Utils.ImportFromMainModule("typeof(System.ValueType)");
                    var constraintType = typeParam.HasUnmanagedTypeConstraint
                        ? $"{systemValueTypeRef}.MakeRequiredModifierType({context.TypeResolver.Resolve("System.Runtime.InteropServices.UnmanagedType")})" 
                        : systemValueTypeRef;

                    exps.Add($"{genParamDefVar}.Constraints.Add(new GenericParameterConstraint({constraintType}));");
                    exps.Add($"{genParamDefVar}.HasNotNullableValueTypeConstraint = true;");
                }

                if (typeParam.Variance == VarianceKind.In)
                {
                    exps.Add($"{genParamDefVar}.IsContravariant = true;");
                }
                else if (typeParam.Variance == VarianceKind.Out)
                {
                    exps.Add($"{genParamDefVar}.IsCovariant = true;");
                }
 
                //TODO: symbol.HasNotNullConstraint causes no difference in the generated replacedembly?
                foreach (var type in typeParam.ConstraintTypes)
                {
                    exps.Add($"{genParamDefVar}.Constraints.Add(new GenericParameterConstraint({context.TypeResolver.Resolve(type)}));");
                }
            }
        }

19 View Source File : CecilDefinitionsFactory.cs
License : MIT License
Project Creator : adrianoc

private static void AddExtraAttributes(IList<string> exps, string paramVar, RefKind byRef)
        {
            if (byRef == RefKind.Out)
            {
                exps.Add($"{paramVar}.Attributes = ParameterAttributes.Out;");
            }
        }

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

public static string AddFormat(this IList<string> em, string fmt, params object[] args)
        {
            if (fmt == null)
                return null;
            var str = args == null ? fmt : string.Format(fmt, args);
            if (em == null)
            {
                return str;
            }
            em.Add(str);
            return str;
        }

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

public static void AddOnce(this IList<string> em, string value)
        {
            if (!string.IsNullOrWhiteSpace(value) && !em.Contains(value))
            {
                em.Add(value);
            }
        }

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

private static ICacheableKeyRingProvider SetupCreateCacheableKeyRingTestAndCreateKeyManager(
            IList<string> callSequence,
            IEnumerable<CancellationToken> getCacheExpirationTokenReturnValues,
            IEnumerable<IReadOnlyCollection<IKey>> getAllKeysReturnValues,
            IEnumerable<Tuple<DateTimeOffset, DateTimeOffset, IKey>> createNewKeyCallbacks,
            IEnumerable<Tuple<DateTimeOffset, IEnumerable<IKey>, DefaultKeyResolution>> resolveDefaultKeyPolicyReturnValues,
            KeyRotationOptions keyManagementOptions = null)
        {
            var getCacheExpirationTokenReturnValuesEnumerator = getCacheExpirationTokenReturnValues.GetEnumerator();
            var mockKeyManager = new Mock<IKeyManager>(MockBehavior.Strict);
            mockKeyManager.Setup(o => o.GetCacheExpirationToken())
                .Returns(() =>
                {
                    callSequence.Add("GetCacheExpirationToken");
                    getCacheExpirationTokenReturnValuesEnumerator.MoveNext();
                    return getCacheExpirationTokenReturnValuesEnumerator.Current;
                });

            var getAllKeysReturnValuesEnumerator = getAllKeysReturnValues.GetEnumerator();
            mockKeyManager.Setup(o => o.GetAllKeys())
              .Returns(() =>
              {
                  callSequence.Add("GetAllKeys");
                  getAllKeysReturnValuesEnumerator.MoveNext();
                  return getAllKeysReturnValuesEnumerator.Current;
              });

            if (createNewKeyCallbacks != null)
            {
                var createNewKeyCallbacksEnumerator = createNewKeyCallbacks.GetEnumerator();
                mockKeyManager.Setup(o => o.CreateNewKey(It.IsAny<DateTimeOffset>(), It.IsAny<DateTimeOffset>()))
                    .Returns<DateTimeOffset, DateTimeOffset>((activationDate, expirationDate) =>
                    {
                        callSequence.Add("CreateNewKey");
                        createNewKeyCallbacksEnumerator.MoveNext();
                        replacedert.Equal(createNewKeyCallbacksEnumerator.Current.Item1, activationDate);
                        replacedert.Equal(createNewKeyCallbacksEnumerator.Current.Item2, expirationDate);
                        return createNewKeyCallbacksEnumerator.Current.Item3;
                    });
            }

            var resolveDefaultKeyPolicyReturnValuesEnumerator = resolveDefaultKeyPolicyReturnValues.GetEnumerator();
            var mockDefaultKeyResolver = new Mock<IDefaultKeyResolver>(MockBehavior.Strict);
            mockDefaultKeyResolver.Setup(o => o.ResolveDefaultKeyPolicy(It.IsAny<DateTimeOffset>(), It.IsAny<IEnumerable<IKey>>()))
                .Returns<DateTimeOffset, IEnumerable<IKey>>((now, allKeys) =>
                {
                    callSequence.Add("ResolveDefaultKeyPolicy");
                    resolveDefaultKeyPolicyReturnValuesEnumerator.MoveNext();
                    replacedert.Equal(resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item1, now);
                    replacedert.Equal(resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item2, allKeys);
                    return resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item3;
                });

            return CreateKeyRingProvider(mockKeyManager.Object, mockDefaultKeyResolver.Object, keyManagementOptions);
        }

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

private void AddValue()
        {
            if (_value == null)
            {
                return;
            }
            Collection.Add(_value);
            HandleModificationState.EnreplacedyUpdated(Model);
            _value = null;
        }

19 View Source File : OpenIdConnectOptionsBuilder.cs
License : GNU General Public License v3.0
Project Creator : AISGorod

private void _FillScopes(ICollection<string> optionsScope)
        {
            optionsScope.Clear();
            optionsScope.Add("openid");
            if (esiaOptions.Scope != null)
            {
                foreach (var scope in esiaOptions.Scope)
                {
                    if (!scope.Equals("openid", StringComparison.OrdinalIgnoreCase))
                    {
                        optionsScope.Add(scope);
                    }
                }
            }
        }

19 View Source File : OpenIdConnectOptionsBuilder.cs
License : GNU General Public License v3.0
Project Creator : AISGorod

private void _FillScopes(ICollection<string> optionsScope)
        {
            optionsScope.Clear();
            optionsScope.Add("openid");
            if (esiaOptions.Scope != null)
            {
                foreach (var scope in esiaOptions.Scope)
                {
                    if (!scope.Equals("openid", StringComparison.OrdinalIgnoreCase))
                    {
                        optionsScope.Add(scope);
                    }
                }
            }
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : akaskela

[Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")]
        public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages)
        {
            IList<string> errors = new List<string>();

            source.Validate(schema, (sender, args) => errors.Add(args.Message));

            errorMessages = errors;
            return (errorMessages.Count == 0);
        }

19 View Source File : SignInManagerTest.cs
License : MIT License
Project Creator : alexandre-spieser

[Theory]
        [InlineData(true)]
        [InlineData(false)]
        public async Task RememberBrowserSkipsTwoFactorVerificationSignIn(bool isPersistent)
        {
            // Setup
            var user = new TestUser { UserName = "Foo" };
            var manager = SetupUserManager(user);
            manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            IList<string> providers = new List<string>();
            providers.Add("PhoneNumber");
            manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            manager.Setup(m => m.CheckPreplacedwordAsync(user, "preplacedword")).ReturnsAsync(true).Verifiable();
            var context = new DefaultHttpContext();
            var auth = MockAuth(context);
            SetupSignIn(context, auth);
            var id = new ClaimsIdenreplacedy(IdenreplacedyConstants.TwoFactorRememberMeScheme);
            id.AddClaim(new Claim(ClaimTypes.Name, user.Id));

            auth.Setup(a => a.AuthenticateAsync(It.IsAny<HttpContext>(), IdenreplacedyConstants.TwoFactorRememberMeScheme))
                .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(id), null, IdenreplacedyConstants.TwoFactorRememberMeScheme))).Verifiable();

            MockLoggerFactory loggerFactory = new MockLoggerFactory();
            var helper = SetupSignInManager(manager.Object, context, loggerFactory);

            // Act
            var result = await helper.PreplacedwordSignInAsync(user.UserName, "preplacedword", isPersistent, false);

            // replacedert
            replacedert.True(result.Succeeded);
            manager.Verify();
            auth.Verify();
        }

19 View Source File : SmartSystemMenuSettings.cs
License : MIT License
Project Creator : AlexanderPro

public object Clone()
        {
            var settings = new SmartSystemMenuSettings();

            foreach (var processExclusion in ProcessExclusions)
            {
                settings.ProcessExclusions.Add(processExclusion);
            }

            foreach (var menuItem in MenuItems.WindowSizeItems)
            {
                settings.MenuItems.WindowSizeItems.Add(new WindowSizeMenuItem { replacedle = menuItem.replacedle, Width = menuItem.Width, Height = menuItem.Height });
            }

            foreach (var menuItem in MenuItems.StartProgramItems)
            {
                settings.MenuItems.StartProgramItems.Add(new StartProgramMenuItem { replacedle = menuItem.replacedle, FileName = menuItem.FileName, Arguments = menuItem.Arguments });
            }

            foreach (var menuItem in MenuItems.Items)
            {
                settings.MenuItems.Items.Add(new MenuItem { Name = menuItem.Name, Key1 = menuItem.Key1, Key2 = menuItem.Key2, Key3 = menuItem.Key3 });
            }

            foreach (var languageItem in LanguageSettings.Items)
            {
                settings.LanguageSettings.Items.Add(new LanguageItem { Name = languageItem.Name, Value = languageItem.Value });
            }

            settings.Closer.Type = Closer.Type;
            settings.Closer.Key1 = Closer.Key1;
            settings.Closer.Key2 = Closer.Key2;
            settings.Closer.MouseButton = Closer.MouseButton;
            settings.Sizer = Sizer;
            settings.LanguageName = LanguageName;
            return settings;
        }

19 View Source File : SignInManagerTest.cs
License : MIT License
Project Creator : alexandre-spieser

[Theory]
        [InlineData(true)]
        [InlineData(false)]
        public async Task PreplacedwordSignInRequiresVerification(bool supportsLockout)
        {
            // Setup
            var user = new TestUser { UserName = "Foo" };
            var manager = SetupUserManager(user);
            manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
            if (supportsLockout)
            {
                manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
            }
            IList<string> providers = new List<string>();
            providers.Add("PhoneNumber");
            manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
            manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
            manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.CheckPreplacedwordAsync(user, "preplacedword")).ReturnsAsync(true).Verifiable();
            manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).ReturnsAsync(new string[1] { "Fake" }).Verifiable();
            var context = new DefaultHttpContext();

            MockLoggerFactory loggerFactory = new MockLoggerFactory();
            var helper = SetupSignInManager(manager.Object, context, loggerFactory);

            var auth = MockAuth(context);
            auth.Setup(a => a.SignInAsync(context, IdenreplacedyConstants.TwoFactorUserIdScheme,
                It.Is<ClaimsPrincipal>(id => id.FindFirstValue(ClaimTypes.Name) == user.Id),
                It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();

            // Act
            var result = await helper.PreplacedwordSignInAsync(user.UserName, "preplacedword", false, false);

            // replacedert
            replacedert.False(result.Succeeded);
            replacedert.True(result.RequiresTwoFactor);
            manager.Verify();
            auth.Verify();
        }

19 View Source File : TestLogger.cs
License : MIT License
Project Creator : alexandre-spieser

public IDisposable BeginScope<TState>(TState state)
        {
            LogMessages.Add(state?.ToString());
            return null;
        }

19 View Source File : TestLogger.cs
License : MIT License
Project Creator : alexandre-spieser

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (formatter == null)
            {
                LogMessages.Add(state.ToString());
            }
            else
            {
                LogMessages.Add(formatter(state, exception));
            }
        }

19 View Source File : SignInManagerTest.cs
License : MIT License
Project Creator : alexandre-spieser

[Theory]
        [InlineData(true)]
        [InlineData(false)]
        public async Task ExternalSignInRequiresVerificationIfNotBypreplaceded(bool bypreplaced)
        {
            // Setup
            var user = new TestUser { UserName = "Foo" };
            const string loginProvider = "login";
            const string providerKey = "fookey";
            var manager = SetupUserManager(user);
            manager.Setup(m => m.SupportsUserLockout).Returns(false).Verifiable();
            manager.Setup(m => m.FindByLoginAsync(loginProvider, providerKey)).ReturnsAsync(user).Verifiable();
            if (!bypreplaced)
            {
                IList<string> providers = new List<string>();
                providers.Add("PhoneNumber");
                manager.Setup(m => m.GetValidTwoFactorProvidersAsync(user)).Returns(Task.FromResult(providers)).Verifiable();
                manager.Setup(m => m.SupportsUserTwoFactor).Returns(true).Verifiable();
                manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
            }
            var context = new DefaultHttpContext();
            var auth = MockAuth(context);

            MockLoggerFactory loggerFactory = new MockLoggerFactory();
            var helper = SetupSignInManager(manager.Object, context, loggerFactory);

            if (bypreplaced)
            {
                SetupSignIn(context, auth, user.Id, false, loginProvider);
            }
            else
            {
                auth.Setup(a => a.SignInAsync(context, IdenreplacedyConstants.TwoFactorUserIdScheme,
                    It.Is<ClaimsPrincipal>(id => id.FindFirstValue(ClaimTypes.Name) == user.Id),
                    It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
            }

            // Act
            var result = await helper.ExternalLoginSignInAsync(loginProvider, providerKey, isPersistent: false, bypreplacedTwoFactor: bypreplaced);

            // replacedert
            replacedert.Equal(bypreplaced, result.Succeeded);
            replacedert.Equal(!bypreplaced, result.RequiresTwoFactor);
            manager.Verify();
            auth.Verify();
        }

19 View Source File : CategoryAxis.cs
License : MIT License
Project Creator : AlexGyver

internal void UpdateLabels(IEnumerable<Series> series)
        {
            if (this.ItemsSource != null)
            {
                this.Labels.Clear();
                ReflectionHelper.FillList(this.ItemsSource, this.LabelField, this.Labels);
            }

            if (this.Labels.Count == 0)
            {
                foreach (var s in series)
                {
                    if (!s.IsUsing(this))
                    {
                        continue;
                    }

                    var bsb = s as CategorizedSeries;
                    if (bsb != null)
                    {
                        int max = bsb.Gereplacedems().Count;
                        while (this.Labels.Count < max)
                        {
                            this.Labels.Add((this.Labels.Count + 1).ToString(CultureInfo.InvariantCulture));
                        }
                    }
                }
            }
        }

19 View Source File : StringFormatter.cs
License : MIT License
Project Creator : alexis-

public static IList<string> SplitAtLineBreaks(string str, bool removeEmptyLines)
    {
      IList<string> result = new List<string>();

      StringBuilder temp = new StringBuilder();
      for (int i = 0; i < str.Length; i++)
      {
        if (i < str.Length - 1 && str[i] == '\r' && str[i + 1] == '\n')
          i++;

        if (str[i] == '\n' || str[i] == '\r')
        {
          if (!removeEmptyLines || temp.Length > 0)
            result.Add(temp.ToString());
          temp.Length = 0;
        }
        else
        {
          temp.Append(str[i]);
        }
      }

      if (temp.Length > 0)
        result.Add(temp.ToString());
      return result;
    }

19 View Source File : StringTable.cs
License : MIT License
Project Creator : alexis-

public void Add(string label, object value)
    {
      m_labels.Add(label);
      m_values.Add(value == null ? null : value.ToString());
    }

19 View Source File : P2PClient.cs
License : MIT License
Project Creator : Amine-Smahi

public IList<string> GetServers()
        {
            IList<string> servers = new List<string>();
            foreach (var item in wsDict)
            {
                servers.Add(item.Key);
            }
            return servers;
        }

19 View Source File : Schema.cs
License : MIT License
Project Creator : Aminator

internal void SetValuesFromAnyOf()
        {
            if (this.Enum == null)
            {
                this.Enum = new List<object>();
            }
            if (this.Type?[0].Name == "integer" && this.EnumNames == null)
            {
                this.EnumNames = new List<string>();
            }

            foreach (var dict in this.AnyOf)
            {
                if (dict.Enum != null && dict.Enum.Count > 0)
                {
                    JsonElement enumElement = (JsonElement)dict.Enum[0];

                    if (this.Type?[0].Name == "integer")
                    {
                        this.Enum.Add(enumElement.GetInt32());
                        this.EnumNames.Add(dict.Description);
                    }
                    else if (this.Type?[0].Name == "string")
                    {
                        this.Enum.Add(enumElement.GetString());
                    }
                    else
                    {
                        throw new NotImplementedException("Enum of " + this.Type?[0].Name);
                    }
                }
            }
        }

19 View Source File : IssueSelector.cs
License : Apache License 2.0
Project Creator : AmpScm

private void Reload()
        {
            issuesView1.ClearItems();
            ICollection<string> issues = new List<string>();
            foreach (TextMarker im in _issueWalker)
            {
                // skip duplicate items
                if (!issues.Contains(im.Value))
                {
                    issuesView1.Items.Add(new IssuesViewItem(issuesView1, im.Value));
                    issues.Add(im.Value);
                }
            }
        }

19 View Source File : LogRevisionItem.cs
License : Apache License 2.0
Project Creator : AmpScm

private string GetIssueText()
        {
            StringBuilder sb = null;
            ICollection<string> issueList = new List<string>();
            foreach (TextMarker issue in Issues)
            {
                if (!issueList.Contains(issue.Value))
                {
                    if (sb == null)
                        sb = new StringBuilder();
                    else
                        sb.Append(',');

                    sb.Append(issue.Value);
                    issueList.Add(issue.Value);
                }
            }
            return sb != null ? sb.ToString() : "";
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : anastasios-stamoulis

static void summary(C.Function rootFunction, List<string> entries, ISet<string> visited) {
      if (visited == null) {
        visited = new HashSet<string>();
      }

      if (rootFunction.IsComposite) {
        summary(rootFunction.RootFunction, entries, visited);
        return;
      }

      if (visited.Contains(rootFunction.Uid)) {
        return;
      }
      visited.Add(rootFunction.Uid);

      var numParameters = 0;
      foreach (var rootInput in rootFunction.Inputs) {
        if (rootInput.IsParameter && !rootInput.IsConstant) {
          numParameters += rootInput.Shape.TotalSize;
        }
        if ((rootInput.Owner == null) || visited.Contains(rootInput.Owner.Uid)) { continue; }
        summary(rootInput.Owner, entries, visited);
      }
      for (int i = 0; i < rootFunction.Outputs.Count; i++) {
        var line = $"{rootFunction.Name,-29}{rootFunction.Outputs[i].Shape.replacedtring(),-26}{numParameters}";
        entries.Add(line);
      }
      entries.Add(underscores);
    }

19 View Source File : HomeController.cs
License : MIT License
Project Creator : andrewlock

[HttpPost]
        public IActionResult Protected(DataViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Data = _data;
                return View(viewModel);
            }
            _data.Add(viewModel.Name);
            return RedirectToAction(nameof(Protected));
        }

19 View Source File : HomeController.cs
License : MIT License
Project Creator : andrewlock

[HttpPost]
        public IActionResult Vulnerable(DataViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Data = _data;
                return View(viewModel);
            }
            _data.Add(viewModel.Name);
            return RedirectToAction(nameof(Vulnerable));
        }

19 View Source File : AssemblyResolver.cs
License : GNU General Public License v3.0
Project Creator : anydream

static void AddIfExists(IList<string> paths, string basePath, string extraPath) {
			var path = Path.Combine(basePath, extraPath);
			if (Directory.Exists(path))
				paths.Add(path);
		}

19 View Source File : Options.cs
License : MIT License
Project Creator : aolszowka

private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
		{
			if (def == null) {
				extra.Add (argument);
				return false;
			}
			c.OptionValues.Add (argument);
			c.Option = def;
			c.Option.Invoke (c);
			return false;
		}

19 View Source File : Options.cs
License : MIT License
Project Creator : aolszowka

private static void AddSeparators (string name, int end, ICollection<string> seps)
		{
			int start = -1;
			for (int i = end+1; i < name.Length; ++i) {
				switch (name [i]) {
					case '{':
						if (start != -1)
							throw new ArgumentException (
									string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
									"prototype");
						start = i+1;
						break;
					case '}':
						if (start == -1)
							throw new ArgumentException (
									string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
									"prototype");
						seps.Add (name.Substring (start, i-start));
						start = -1;
						break;
					default:
						if (start == -1)
							seps.Add (name [i].ToString ());
						break;
				}
			}
			if (start != -1)
				throw new ArgumentException (
						string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
						"prototype");
		}

19 View Source File : ExcelDataValidationFormulaList.cs
License : Apache License 2.0
Project Creator : Appdynamics

private void SetInitialValues()
        {
            var @value = GetXmlNodeString(_formulaPath);
            if (!string.IsNullOrEmpty(@value))
            {
                if (@value.StartsWith("\"") && @value.EndsWith("\""))
                {
                    @value = @value.TrimStart('"').TrimEnd('"');
                    var items = @value.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var item in items)
                    {
                        Values.Add(item);
                    }
                }
                else
                {
                    ExcelFormula = @value;
                }
            }
        }

19 View Source File : ExcelDataValidationFormulaList.cs
License : Apache License 2.0
Project Creator : Appdynamics

void ICollection<string>.Add(string item)
            {
                _items.Add(item);
                OnListChanged();
            }

19 View Source File : DBCMessage.cs
License : MIT License
Project Creator : Aptiv-WLL

public void UpdateFromReceived(CANMessage received)
        {
            if (!(Message_ID.Equals(received.Message_ID))) return;
            else
            {
                // Create a deep clone of this message
                var copy = new DBCMessage(this);

                // Copy over the new message's data.
                for (int i = 0; i < received.Data.Count && i < copy.Data.Count; i++)
                    ((IList<byte>)copy.Data)[i] = ((IList<byte>)received.Data)[i];

                IList<string> signalsList = new List<string>();

                // Update this message's signals with the copy's
                // new signal values.
                foreach (var sig in Signals)
                {
                    // Check for modified signals and store them
                    if (Signals[sig.Key].Value != copy.Signals[sig.Key].Value)
                    {
                        signalsList.Add(sig.Key);
                    }
                    Signals[sig.Key].Value = copy.Signals[sig.Key].Value;
                }

                // Call the onUpdate function that will call the handler
                OnDBCUpdate(new DBCMessageUpdateEventArgs(signalsList));
            }
        }

19 View Source File : ServiceDiscovery.cs
License : MIT License
Project Creator : araditc

IEnumerable<string> QueryFeatures(Jid jid) {
			jid.ThrowIfNull("jid");
			Iq iq = im.IqRequest(IqType.Get, jid, im.Jid,
				Xml.Element("query", "http://jabber.org/protocol/disco#info"));
			if (iq.Type != IqType.Result)
				throw new NotSupportedException("Could not query features: " + iq);
			// Parse the result.
			var query = iq.Data["query"];
			if (query == null || query.NamespaceURI != "http://jabber.org/protocol/disco#info")
				throw new NotSupportedException("Erroneous response: " + iq);
			ISet<string> ns = new HashSet<string>();
			foreach (XmlElement e in query.GetElementsByTagName("feature"))
				ns.Add(e.GetAttribute("var"));
			// Go through each extension we support and see if the enreplacedy supports
			// all of the extension's namespaces.
			ISet<string> feats = new HashSet<string>();
			foreach (XmppExtension ext in im.Extensions) {
				if (ns.IsSupersetOf(ext.Namespaces))
					feats.Add(ext.Xep);
			}
			return feats;
		}

19 View Source File : SecretStoreBuilderExtensionsTests.cs
License : MIT License
Project Creator : arcus-azure

private void SetSecret(string id, string key, string value)
        {
            string secretsFilePath = PathHelper.GetSecretsPathFromSecretsId(id);
            string secretsDirPath = Path.GetDirectoryName(secretsFilePath);
            Directory.CreateDirectory(secretsDirPath);
            _tempDirectories.Add(secretsDirPath);

            IConfiguration config = 
                new ConfigurationBuilder()
                    .AddJsonFile(secretsFilePath, optional: true)
                    .Build();

            IDictionary<string, string> secrets =
                config.AsEnumerable()
                      .Where(item => item.Value != null)
                      .ToDictionary(item => item.Key, i => i.Value, StringComparer.OrdinalIgnoreCase);

            secrets[key] = value;

            var contents = new JObject();
            foreach (KeyValuePair<string, string> secret in secrets.AsEnumerable())
            {
                contents[secret.Key] = secret.Value;
            }

            File.WriteAllText(secretsFilePath, contents.ToString(), Encoding.UTF8);
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Tuple<Type, string> SearchForStartupAttribute(string friendlyName, IList<string> errors, ref bool conflict)
        {
            friendlyName = friendlyName ?? string.Empty;
            bool foundAnyInstances = false;
            Tuple<Type, string> fullMatch = null;
            replacedembly matchedreplacedembly = null;
            foreach (var replacedembly in _referencedreplacedemblies)
            {
                Attribute[] attributes;
                try
                {
                    // checking attribute's name first and only then instantiating it
                    // then we are filtering attributes by name second time as inheritors could be added by calling to GetCustomAttributes(type)
                    attributes = replacedembly.GetCustomAttributesData()
                        .Where(data => MatchesStartupAttribute(data.AttributeType))
                        .Select(data => data.AttributeType)
                        .SelectMany(type => replacedembly.GetCustomAttributes(type))
                        .Distinct()
                        .ToArray();
                }
                catch (CustomAttributeFormatException)
                {
                    continue;
                }
                
                foreach (var owinStartupAttribute in attributes.Where(attribute => MatchesStartupAttribute(attribute.GetType())))
                {
                    Type attributeType = owinStartupAttribute.GetType();
                    foundAnyInstances = true;

                    // Find the StartupType property.
                    PropertyInfo startupTypeProperty = attributeType.GetProperty(Constants.StartupType, typeof(Type));
                    if (startupTypeProperty == null)
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyMissing,
                            attributeType.replacedemblyQualifiedName, replacedembly.FullName));
                        continue;
                    }

                    var startupType = startupTypeProperty.GetValue(owinStartupAttribute, null) as Type;
                    if (startupType == null)
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyEmpty, replacedembly.FullName));
                        continue;
                    }

                    // FriendlyName is an optional property.
                    string friendlyNameValue = string.Empty;
                    PropertyInfo friendlyNameProperty = attributeType.GetProperty(Constants.FriendlyName, typeof(string));
                    if (friendlyNameProperty != null)
                    {
                        friendlyNameValue = friendlyNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
                    }

                    if (!string.Equals(friendlyName, friendlyNameValue, StringComparison.OrdinalIgnoreCase))
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.FriendlyNameMismatch,
                            friendlyNameValue, friendlyName, replacedembly.FullName));
                        continue;
                    }

                    // MethodName is an optional property.
                    string methodName = string.Empty;
                    PropertyInfo methodNameProperty = attributeType.GetProperty(Constants.MethodName, typeof(string));
                    if (methodNameProperty != null)
                    {
                        methodName = methodNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
                    }

                    if (fullMatch != null)
                    {
                        conflict = true;
                        errors.Add(string.Format(CultureInfo.CurrentCulture,
                            LoaderResources.Exception_AttributeNameConflict,
                            matchedreplacedembly.GetName().Name, fullMatch.Item1, replacedembly.GetName().Name, startupType, friendlyName));
                    }
                    else
                    {
                        fullMatch = new Tuple<Type, string>(startupType, methodName);
                        matchedreplacedembly = replacedembly;
                    }
                }
            }

            if (!foundAnyInstances)
            {
                errors.Add(LoaderResources.NoOwinStartupAttribute);
            }
            if (conflict)
            {
                return null;
            }
            return fullMatch;
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private static void CheckForStartupType(string startupName, replacedembly replacedembly, ref Type matchedType, ref bool conflict, IList<string> errors)
        {
            Type startupType = replacedembly.GetType(startupName, throwOnError: false);
            if (startupType != null)
            {
                // Conflict?
                if (matchedType != null)
                {
                    conflict = true;
                    errors.Add(string.Format(CultureInfo.CurrentCulture,
                        LoaderResources.Exception_StartupTypeConflict,
                        matchedType.replacedemblyQualifiedName, startupType.replacedemblyQualifiedName));
                }
                else
                {
                    matchedType = startupType;
                }
            }
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Action<IAppBuilder> MakeDelegate(Type type, string methodName, IList<string> errors)
        {
            MethodInfo partialMatch = null;
            foreach (var methodInfo in type.GetMethods())
            {
                if (!methodInfo.Name.Equals(methodName))
                {
                    continue;
                }

                // void Configuration(IAppBuilder app)
                if (Matches(methodInfo, false, typeof(IAppBuilder)))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => methodInfo.Invoke(instance, new[] { builder });
                }

                // object Configuration(IDictionary<string, object> appProperties)
                if (Matches(methodInfo, true, typeof(IDictionary<string, object>)))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[] { builder.Properties })));
                }

                // object Configuration()
                if (Matches(methodInfo, true))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[0])));
                }

                partialMatch = partialMatch ?? methodInfo;
            }

            if (partialMatch == null)
            {
                errors.Add(string.Format(CultureInfo.CurrentCulture,
                    LoaderResources.MethodNotFoundInClreplaced, methodName, type.replacedemblyQualifiedName));
            }
            else
            {
                errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.UnexpectedMethodSignature,
                    methodName, type.replacedemblyQualifiedName));
            }
            return null;
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Tuple<Type, string> GetTypeAndMethodNameForConfigurationString(string configuration, IList<string> errors)
        {
            Tuple<string, replacedembly> typePair = HuntForreplacedembly(configuration, errors);
            if (typePair == null)
            {
                return null;
            }

            string longestPossibleName = typePair.Item1; // method or type name
            replacedembly replacedembly = typePair.Item2;

            // try the longest 2 possibilities at most (because you can't have a dot in the method name)
            // so, typeName could specify a method or a type. we're looking for a type.
            foreach (var typeName in DotByDot(longestPossibleName).Take(2))
            {
                Type type = replacedembly.GetType(typeName, false);
                if (type == null)
                {
                    errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.ClreplacedNotFoundInreplacedembly,
                        configuration, typeName, replacedembly.FullName));
                    // must have been a method name (or doesn't exist), next!
                    continue;
                }

                string methodName = typeName == longestPossibleName
                    ? null
                    : longestPossibleName.Substring(typeName.Length + 1);

                return new Tuple<Type, string>(type, methodName);
            }

            return null;
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Tuple<string, replacedembly> HuntForreplacedembly(string configuration, IList<string> errors)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            int commaIndex = configuration.IndexOf(',');
            if (commaIndex >= 0)
            {
                // replacedembly is given, break the type and replacedembly apart
                string methodOrTypeName = DotByDot(configuration.Substring(0, commaIndex)).FirstOrDefault();
                string replacedemblyName = configuration.Substring(commaIndex + 1).Trim();
                replacedembly replacedembly = TryreplacedemblyLoad(replacedemblyName);

                if (replacedembly == null)
                {
                    errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.replacedemblyNotFound,
                        configuration, replacedemblyName));
                    return null;
                }
                return Tuple.Create(methodOrTypeName, replacedembly);
            }

            // See if any referenced replacedemblies contain this type
            foreach (var replacedembly in _referencedreplacedemblies)
            {
                // NameSpace.Type or NameSpace.Type.Method
                foreach (var typeName in DotByDot(configuration).Take(2))
                {
                    if (replacedembly.GetType(typeName, throwOnError: false) != null)
                    {
                        return Tuple.Create(configuration, replacedembly);
                    }
                }
            }

            errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.TypeOrMethodNotFound, configuration));
            return null;
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Tuple<Type, string> SearchForStartupAttribute(string friendlyName, IList<string> errors, ref bool conflict)
        {
            friendlyName = friendlyName ?? string.Empty;
            bool foundAnyInstances = false;
            Tuple<Type, string> fullMatch = null;
            replacedembly matchedreplacedembly = null;
            foreach (var replacedembly in _referencedreplacedemblies)
            {
                Attribute[] attributes;
                try
                {
                    // checking attribute's name first and only then instantiating it
                    // then we are filtering attributes by name second time as inheritors could be added by calling to GetCustomAttributes(type)
                    attributes = replacedembly.GetCustomAttributesData()
                        .Where(data => MatchesStartupAttribute(data.AttributeType))
                        .Select(data => data.AttributeType)
                        .SelectMany(type => replacedembly.GetCustomAttributes(type))
                        .Distinct()
                        .ToArray();
                }
                catch (CustomAttributeFormatException)
                {
                    continue;
                }
                
                foreach (var owinStartupAttribute in attributes.Where(attribute => MatchesStartupAttribute(attribute.GetType())))
                {
                    Type attributeType = owinStartupAttribute.GetType();
                    foundAnyInstances = true;

                    // Find the StartupType property.
                    PropertyInfo startupTypeProperty = attributeType.GetProperty(Constants.StartupType, typeof(Type));
                    if (startupTypeProperty == null)
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyMissing,
                            attributeType.replacedemblyQualifiedName, replacedembly.FullName));
                        continue;
                    }

                    var startupType = startupTypeProperty.GetValue(owinStartupAttribute, null) as Type;
                    if (startupType == null)
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyEmpty, replacedembly.FullName));
                        continue;
                    }

                    // FriendlyName is an optional property.
                    string friendlyNameValue = string.Empty;
                    PropertyInfo friendlyNameProperty = attributeType.GetProperty(Constants.FriendlyName, typeof(string));
                    if (friendlyNameProperty != null)
                    {
                        friendlyNameValue = friendlyNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
                    }

                    if (!string.Equals(friendlyName, friendlyNameValue, StringComparison.OrdinalIgnoreCase))
                    {
                        errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.FriendlyNameMismatch,
                            friendlyNameValue, friendlyName, replacedembly.FullName));
                        continue;
                    }

                    // MethodName is an optional property.
                    string methodName = string.Empty;
                    PropertyInfo methodNameProperty = attributeType.GetProperty(Constants.MethodName, typeof(string));
                    if (methodNameProperty != null)
                    {
                        methodName = methodNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
                    }

                    if (fullMatch != null)
                    {
                        conflict = true;
                        errors.Add(string.Format(CultureInfo.CurrentCulture,
                            LoaderResources.Exception_AttributeNameConflict,
                            matchedreplacedembly.GetName().Name, fullMatch.Item1, replacedembly.GetName().Name, startupType, friendlyName));
                    }
                    else
                    {
                        fullMatch = new Tuple<Type, string>(startupType, methodName);
                        matchedreplacedembly = replacedembly;
                    }
                }
            }

            if (!foundAnyInstances)
            {
                errors.Add(LoaderResources.NoOwinStartupAttribute);
            }
            if (conflict)
            {
                return null;
            }
            return fullMatch;
        }

See More Examples