// May not be necessary in the future. See https://github.com/dotnet/corefx/issues/12039
        public async Task <int> RunAsync(ProcessSpec processSpec, CancellationToken cancellationToken)
        {
            Ensure.NotNull(processSpec, nameof(processSpec));

            int exitCode;

            var stopwatch = new Stopwatch();

            using (var process = CreateProcess(processSpec))
                using (var processState = new ProcessState(process, _reporter))
                {
                    cancellationToken.Register(() => processState.TryKill());

                    var readOutput = false;
                    var readError  = false;
                    if (processSpec.IsOutputCaptured)
                    {
                        readOutput = true;
                        readError  = true;
                        process.OutputDataReceived += (_, a) =>
                        {
                            if (!string.IsNullOrEmpty(a.Data))
                            {
                                processSpec.OutputCapture.AddLine(a.Data);
                            }
                        };
                        process.ErrorDataReceived += (_, a) =>
                        {
                            if (!string.IsNullOrEmpty(a.Data))
                            {
                                processSpec.OutputCapture.AddLine(a.Data);
                            }
                        };
                    }
                    else if (processSpec.OnOutput != null)
                    {
                        readOutput = true;
                        process.OutputDataReceived += processSpec.OnOutput;
                    }

                    stopwatch.Start();
                    process.Start();

                    _reporter.Verbose($"Started '{processSpec.Executable}' '{process.StartInfo.Arguments}' with process id {process.Id}");

                    if (readOutput)
                    {
                        process.BeginOutputReadLine();
                    }
                    if (readError)
                    {
                        process.BeginErrorReadLine();
                    }

                    await processState.Task;

                    exitCode = process.ExitCode;
                    stopwatch.Stop();
                    _reporter.Verbose($"Process id {process.Id} ran for {stopwatch.ElapsedMilliseconds}ms");
                }

            return(exitCode);
        }
 private ConventionBasedOperationAuthorizer(Type targetType)
 {
     Ensure.NotNull(targetType, "targetType");
     this.targetType = targetType;
 }
        /// <summary>
        /// Konstruktor ustawiający linie, które chcemy szukać
        /// </summary>
        /// <param name="lines"></param>
        public LinesSearcher(int[][] lines)
        {
            Ensure.TwoDimensionalArrayParamNotNullOrEmpty(lines, nameof(lines));

            this.Lines = lines;
        }
Exemple #4
0
 public IOngoingListBasedPredicateFunctionWithList In(Expression list)
 {
     Ensure.IsNotNull(list, "The list expression is required");
     _listExpression = list;
     return(this);
 }
Exemple #5
0
        public ObservableEnterpriseAdminStatsClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, nameof(client));

            _client = client.Enterprise.AdminStats;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MerchelloDatabaseSchemaResult"/> class.
 /// </summary>
 /// <param name="database">
 /// The database.
 /// </param>
 public MerchelloDatabaseSchemaResult(Database database)
 {
     Ensure.ParameterNotNull(database, "database");
     this._database = database;
 }
 public void Publish(Message message)
 {
     Ensure.NotNull(message, "message");
     PublishByType(message, message.GetType());
 }
Exemple #8
0
        public BitVectorAsSet(BitVectorAsSet s)
        {
            Ensure.That(s.Size).Is(maxSize);

            bits = new SortedSet <ulong>(s.bits);
        }
Exemple #9
0
 // constructors
 public FindFluent(IMongoCollection <TDocument> collection, FilterDefinition <TDocument> filter, FindOptions <TDocument, TProjection> options)
 {
     _collection = Ensure.IsNotNull(collection, nameof(collection));
     _filter     = Ensure.IsNotNull(filter, nameof(filter));
     _options    = Ensure.IsNotNull(options, nameof(options));
 }
Exemple #10
0
 public WebServer(JobWatcher jobWatcher)
 {
     Ensure.Requires <ArgumentNullException>(jobWatcher != null, "`jobWatcher` should not be null.");
     jobWatcher.OnChangeCompleted = Reload;
     this.jobWatcher = jobWatcher;
 }
Exemple #11
0
        public static string prompt_for_confirmation(string prompt, IEnumerable <string> choices, string defaultChoice, bool requireAnswer, int repeat = 10)
        {
            if (repeat < 0)
            {
                throw new ApplicationException("Too many bad attempts. Stopping before application crash.");
            }
            Ensure.that(() => prompt).is_not_null();
            Ensure.that(() => choices).is_not_null();
            Ensure
            .that(() => choices)
            .meets(
                c => c.Count() > 0,
                (name, value) => { throw new ApplicationException("No choices passed in. Please ensure you pass choices"); });
            if (defaultChoice != null)
            {
                Ensure
                .that(() => choices)
                .meets(
                    c => c.Contains(defaultChoice),
                    (name, value) => { throw new ApplicationException("Default choice value must be one of the given choices."); });
            }

            "chocolatey".Log().Info(ChocolateyLoggers.Important, prompt);

            int counter = 1;
            IDictionary <int, string> choiceDictionary = new Dictionary <int, string>();

            foreach (var choice in choices.or_empty_list_if_null())
            {
                choiceDictionary.Add(counter, choice);
                "chocolatey".Log().Info(" {0}) {1}{2}".format_with(counter, choice.to_string(), choice == defaultChoice ? " [Default - Press Enter]" : ""));
                counter++;
            }

            var selection = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(selection) && defaultChoice != null)
            {
                return(defaultChoice);
            }

            int selected = -1;

            if (!int.TryParse(selection, out selected) || selected <= 0 || selected > (counter - 1))
            {
                // check to see if value was passed
                var selectionFound = false;
                foreach (var pair in choiceDictionary)
                {
                    if (pair.Value.is_equal_to(selection))
                    {
                        selected       = pair.Key;
                        selectionFound = true;
                        break;
                    }
                }

                if (!selectionFound)
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, "Your choice of '{0}' is not a valid selection.".format_with(selection));
                    if (requireAnswer)
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, "You must select an answer");
                        return(prompt_for_confirmation(prompt, choices, defaultChoice, requireAnswer, repeat - 1));
                    }
                    return(null);
                }
            }

            return(choiceDictionary[selected]);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CreateIndexModel{TDocument}"/> class.
 /// </summary>
 /// <param name="keys">The keys.</param>
 /// <param name="options">The options.</param>
 public CreateIndexModel(IndexKeysDefinition <TDocument> keys, CreateIndexOptions options = null)
 {
     _keys    = Ensure.IsNotNull(keys, "keys");
     _options = options;
 }
        /// <summary>
        /// Create a new local branch with the specified name
        /// </summary>
        /// <param name="name">The name of the branch.</param>
        /// <param name="commit">The target commit.</param>
        /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing branch, false otherwise.</param>
        /// <returns>A new <see cref="Branch"/>.</returns>
        public virtual Branch Add(string name, Commit commit, bool allowOverwrite)
        {
            Ensure.ArgumentNotNull(commit, "commit");

            return(Add(name, commit.Sha, allowOverwrite));
        }
 public PutAttachmentRequest(string docId, string docRev, string name, string contentType, byte[] content) 
     : this(docId, name, contentType, content)
 {
     Ensure.That(docRev, "docRev").IsNotNullOrWhiteSpace();
     DocRev = docRev;
 }
 internal void AddPressingHandler(EventHandler <AccessKeyPressingEventArgs> handler)
 {
     Ensure.NotNull(handler, "handler");
     pressingHandler += handler;
 }
 // constructors
 public ReplyMessageJsonEncoder(TextReader textReader, TextWriter textWriter, MessageEncoderSettings encoderSettings, IBsonSerializer <TDocument> serializer)
     : base(textReader, textWriter, encoderSettings)
 {
     _serializer = Ensure.IsNotNull(serializer, "serializer");
 }
 internal bool RemovePressingHandler(EventHandler <AccessKeyPressingEventArgs> handler)
 {
     Ensure.NotNull(handler, "handler");
     pressingHandler -= handler;
     return(TryDetachEvents());
 }
Exemple #18
0
        public BitVectorAsSet(SortedSet <ulong> s)
        {
            Ensure.That((ulong)s.Count).IsLte(maxSize);

            bits = new SortedSet <ulong>(s);
        }
 public static void SetIsKeyboardCues(DependencyObject targetObject, bool value)
 {
     Ensure.NotNull(targetObject, "targetObject");
     targetObject.SetValue(IsKeyboardCuesProperty, value);
 }
 public CliActionHelpPrinter(ICliActionHelpGenerator helpGenerator, ISysConsole sysConsole)
 {
     _sysConsole    = Ensure.NotNull(sysConsole, nameof(sysConsole));
     _helpGenerator = Ensure.NotNull(helpGenerator, nameof(helpGenerator));
 }
 public static bool GetIsKeyboardCues(DependencyObject targetObject)
 {
     Ensure.NotNull(targetObject, "targetObject");
     return((bool)targetObject.GetValue(IsKeyboardCuesProperty));
 }
        public static string prompt_for_confirmation(string prompt, IEnumerable <string> choices, string defaultChoice, bool requireAnswer, bool allowShortAnswer = true, bool shortPrompt = false, int repeat = 10)
        {
            if (repeat < 0)
            {
                throw new ApplicationException("Too many bad attempts. Stopping before application crash.");
            }
            Ensure.that(() => prompt).is_not_null();
            Ensure.that(() => choices).is_not_null();
            Ensure
            .that(() => choices)
            .meets(
                c => c.Count() > 0,
                (name, value) => { throw new ApplicationException("No choices passed in. Please ensure you pass choices"); });

            if (defaultChoice != null)
            {
                Ensure
                .that(() => choices)
                .meets(
                    c => c.Contains(defaultChoice),
                    (name, value) => { throw new ApplicationException("Default choice value must be one of the given choices."); });
            }

            if (allowShortAnswer)
            {
                Ensure
                .that(() => choices)
                .meets(
                    c => !c.Any(String.IsNullOrWhiteSpace),
                    (name, value) => { throw new ApplicationException("Some choices are empty. Please ensure you provide no empty choices."); });

                Ensure
                .that(() => choices)
                .meets(
                    c => c.Select(entry => entry.FirstOrDefault()).Distinct().Count() == c.Count(),
                    (name, value) => { throw new ApplicationException("Multiple choices have the same first letter. Please ensure you pass choices with different first letters."); });
            }

            if (shortPrompt)
            {
                Console.Write(prompt + "(");
            }

            "chocolatey".Log().Info(shortPrompt ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Important, prompt);

            int counter = 1;
            IDictionary <int, string> choiceDictionary = new Dictionary <int, string>();

            foreach (var choice in choices.or_empty_list_if_null())
            {
                choiceDictionary.Add(counter, choice);
                "chocolatey".Log().Info(shortPrompt ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Normal, " {0}) {1}{2}".format_with(counter, choice.to_string(), choice.is_equal_to(defaultChoice) ? " [Default - Press Enter]" : ""));
                if (shortPrompt)
                {
                    var choicePrompt = choice.is_equal_to(defaultChoice) ?
                                       shortPrompt ?
                                       "[[{0}]{1}]".format_with(choice.Substring(0, 1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) :
                                       "[{0}]".format_with(choice.ToUpperInvariant())
                        :
                                       shortPrompt ?
                                       "[{0}]{1}".format_with(choice.Substring(0, 1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) :
                                       choice;

                    if (counter != 1)
                    {
                        Console.Write("/");
                    }
                    Console.Write(choicePrompt);
                }

                counter++;
            }

            Console.Write(shortPrompt ? "): " : "> ");

            var selection = Console.ReadLine();

            if (shortPrompt)
            {
                Console.WriteLine();
            }

            if (string.IsNullOrWhiteSpace(selection) && defaultChoice != null)
            {
                "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choosing default choice of '{0}'".format_with(defaultChoice.escape_curly_braces()));
                return(defaultChoice);
            }

            int selected = -1;

            if (!int.TryParse(selection, out selected) || selected <= 0 || selected > (counter - 1))
            {
                // check to see if value was passed
                var selectionFound = false;
                foreach (var pair in choiceDictionary)
                {
                    if (pair.Value.is_equal_to(selection) || (allowShortAnswer && pair.Value.Substring(0, 1).is_equal_to(selection)))
                    {
                        selected       = pair.Key;
                        selectionFound = true;
                        "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choice selected: '{0}'".format_with(pair.Value.escape_curly_braces()));
                        break;
                    }
                }

                if (!selectionFound)
                {
                    "chocolatey".Log().Error(ChocolateyLoggers.Important, "Your choice of '{0}' is not a valid selection.".format_with(selection.escape_curly_braces()));
                    if (requireAnswer)
                    {
                        "chocolatey".Log().Warn(ChocolateyLoggers.Important, "You must select an answer");
                        return(prompt_for_confirmation(prompt, choices, defaultChoice, requireAnswer, allowShortAnswer, shortPrompt, repeat - 1));
                    }
                    return(null);
                }
            }

            return(choiceDictionary[selected]);
        }
Exemple #23
0
        /// <summary>
        ///   Push specified references to the <see cref="Remote"/>.
        /// </summary>
        /// <param name="remote">The <see cref = "Remote" /> to push to.</param>
        /// <param name="pushRefSpecs">The pushRefSpecs to push.</param>
        /// <param name="onPushStatusError">Handler for reporting failed push updates.</param>
        /// <param name="credentials">Credentials to use for user/pass authentication</param>
        public virtual void Push(
            Remote remote,
            IEnumerable<string> pushRefSpecs,
            PushStatusErrorHandler onPushStatusError,
            Credentials credentials = null)
        {
            Ensure.ArgumentNotNull(remote, "remote");
            Ensure.ArgumentNotNull(pushRefSpecs, "pushRefSpecs");

            // We need to keep a reference to the git_cred_acquire_cb callback around
            // so it will not be garbage collected before we are done with it.
            // Note that we also have a GC.KeepAlive call at the end of the method.
            NativeMethods.git_cred_acquire_cb credentialCallback = null;

            // Return early if there is nothing to push.
            if (!pushRefSpecs.Any())
            {
                return;
            }

            PushCallbacks pushStatusUpdates = new PushCallbacks(onPushStatusError);

            // Load the remote.
            using (RemoteSafeHandle remoteHandle = Proxy.git_remote_load(repository.Handle, remote.Name, true))
            {
                if (credentials != null)
                {
                    credentialCallback = (out IntPtr cred, IntPtr url, IntPtr username_from_url, uint types, IntPtr payload) =>
                        NativeMethods.git_cred_userpass_plaintext_new(out cred, credentials.Username, credentials.Password);

                    Proxy.git_remote_set_cred_acquire_cb(
                        remoteHandle,
                        credentialCallback,
                        IntPtr.Zero);
                }

                try
                {
                    Proxy.git_remote_connect(remoteHandle, GitDirection.Push);

                    // Perform the actual push.
                    using (PushSafeHandle pushHandle = Proxy.git_push_new(remoteHandle))
                    {
                        // Add refspecs.
                        foreach (string pushRefSpec in pushRefSpecs)
                        {
                            Proxy.git_push_add_refspec(pushHandle, pushRefSpec);
                        }

                        Proxy.git_push_finish(pushHandle);

                        if (!Proxy.git_push_unpack_ok(pushHandle))
                        {
                            throw new LibGit2SharpException("Push failed - remote did not successfully unpack.");
                        }

                        Proxy.git_push_status_foreach(pushHandle, pushStatusUpdates.Callback);

                        Proxy.git_push_update_tips(pushHandle);
                    }
                }
                finally
                {
                    Proxy.git_remote_disconnect(remoteHandle);
                }
            }

            // To be safe, make sure the credential callback is kept until
            // alive until at least this point.
            GC.KeepAlive(credentialCallback);
        }
Exemple #24
0
        public InterfaceId(int value)
        {
            Ensure.That(value, "value").IsGte(0);

            _value = value;
        }
Exemple #25
0
 // methods
 public IConnection CreateConnection(ServerId serverId, EndPoint endPoint)
 {
     Ensure.IsNotNull(serverId, nameof(serverId));
     Ensure.IsNotNull(endPoint, nameof(endPoint));
     return(new BinaryConnection(serverId, endPoint, _settings, _streamFactory, _connectionInitializer, _eventSubscriber));
 }
Exemple #26
0
        public ProcessRunner(IReporter reporter)
        {
            Ensure.NotNull(reporter, nameof(reporter));

            _reporter = reporter;
        }
        public CodeTupleExpression(IEnumerable <CodeExpression> items)
        {
            Ensure.That(nameof(items)).IsNotNull(items);

            Items.AddRange(items);
        }
Exemple #28
0
        public ChunkManagerConfig(string basePath,
                                  IFileNamingStrategy fileNamingStrategy,
                                  int chunkDataSize,
                                  int chunkDataUnitSize,
                                  int chunkDataCount,
                                  int flushChunkIntervalMilliseconds,
                                  bool enableCache,
                                  bool syncFlush,
                                  int chunkReaderCount,
                                  int maxLogRecordSize,
                                  int chunkWriteBuffer,
                                  int chunkReadBuffer,
                                  int chunkCacheMaxPercent,
                                  int chunkCacheMinPercent,
                                  int preCacheChunkCount,
                                  int chunkInactiveTimeMaxSeconds,
                                  int chunkLocalCacheSize,
                                  bool enableChunkWriteStatistic,
                                  bool enableChunkReadStatistic)
        {
            Ensure.NotNullOrEmpty(basePath, "basePath");
            Ensure.NotNull(fileNamingStrategy, "fileNamingStrategy");
            Ensure.Nonnegative(chunkDataSize, "chunkDataSize");
            Ensure.Nonnegative(chunkDataUnitSize, "chunkDataUnitSize");
            Ensure.Nonnegative(chunkDataCount, "chunkDataCount");
            Ensure.Positive(flushChunkIntervalMilliseconds, "flushChunkIntervalMilliseconds");
            Ensure.Positive(maxLogRecordSize, "maxLogRecordSize");
            Ensure.Positive(chunkWriteBuffer, "chunkWriteBuffer");
            Ensure.Positive(chunkReadBuffer, "chunkReadBuffer");
            Ensure.Positive(chunkCacheMaxPercent, "chunkCacheMaxPercent");
            Ensure.Positive(chunkCacheMinPercent, "chunkCacheMinPercent");
            Ensure.Nonnegative(preCacheChunkCount, "preCacheChunkCount");
            Ensure.Nonnegative(chunkInactiveTimeMaxSeconds, "chunkInactiveTimeMaxSeconds");
            Ensure.Positive(chunkLocalCacheSize, "chunkLocalCacheSize");

            if (chunkDataSize <= 0 && (chunkDataUnitSize <= 0 || chunkDataCount <= 0))
            {
                throw new ArgumentException(string.Format("Invalid chunk data size arugment. chunkDataSize: {0}, chunkDataUnitSize: {1}, chunkDataCount: {2}", chunkDataSize, chunkDataUnitSize, chunkDataCount));
            }

            BasePath                       = basePath;
            FileNamingStrategy             = fileNamingStrategy;
            ChunkDataSize                  = chunkDataSize;
            ChunkDataUnitSize              = chunkDataUnitSize;
            ChunkDataCount                 = chunkDataCount;
            FlushChunkIntervalMilliseconds = flushChunkIntervalMilliseconds;
            EnableCache                    = enableCache;
            SyncFlush                      = syncFlush;
            ChunkReaderCount               = chunkReaderCount;
            MaxLogRecordSize               = maxLogRecordSize;
            ChunkWriteBuffer               = chunkWriteBuffer;
            ChunkReadBuffer                = chunkReadBuffer;
            ChunkCacheMaxPercent           = chunkCacheMaxPercent;
            ChunkCacheMinPercent           = chunkCacheMinPercent;
            PreCacheChunkCount             = preCacheChunkCount;
            ChunkInactiveTimeMaxSeconds    = chunkInactiveTimeMaxSeconds;
            ChunkLocalCacheSize            = chunkLocalCacheSize;
            EnableChunkWriteStatistic      = enableChunkWriteStatistic;
            EnableChunkReadStatistic       = enableChunkReadStatistic;

            if (GetChunkDataSize() > 1024 * 1024 * 1024)
            {
                throw new ArgumentException("Chunk data size cannot bigger than 1G");
            }
        }
 /// <summary>
 /// Initializes a new instance of the MongoConnectionException class.
 /// </summary>
 /// <param name="connectionId">The connection identifier.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerException">The inner exception.</param>
 public MongoConnectionException(ConnectionId connectionId, string message, Exception innerException)
     : base(message, innerException)
 {
     _connectionId = Ensure.IsNotNull(connectionId, "connectionId");
 }
 public static void EnsureImplant(this TimeEntry entry, CultureInfo culture, Ensure implant)
 {
     (implant ?? entry.Ensure)(culture);
 }
        // public methods
        public IntPtr GetFunctionPointer(string name)
        {
            Ensure.IsNotNullOrEmpty(name, nameof(name));

            return(NativeMethods.dlsym(_handle, name));
        }