Пример #1
0
        public Result(string actionName, ResultValue value, string description)
        {
            this.value = value;
            this.description = description;
            this.actionName = actionName;

            time = DateTime.Now;
        }
        public void DeployConsole()
        {
            Trace.WriteLine("Installer::DeployConsole");

            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List<GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: custom path does not exist: '{0}'. U_U", _customPath);
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying to custom path: '{0}'.", _customPath);

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation)
                        || Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Trace.Write("   Git found: " + installation.Path);

                        // track known Git installtations
                        installations = new List<GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine("  {0}", installation.Path);
                        }
                    }
                }

                if (installations == null)
                {
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List<string> cleanedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying from '{0}' to '{1}'.", Program.Location, installation.Path);

                    if (CopyFiles(Program.Location, installation.Libexec, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) copied", cleanedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine("Deploying from '{0}' to '{1}'.", Program.Location, UserBinPath);

                if(!Directory.Exists(UserBinPath))
                {
                    Directory.CreateDirectory(UserBinPath);
                }

                if (CopyFiles(Program.Location, UserBinPath, out cleanedFiles))
                {
                    foreach (var file in cleanedFiles)
                    {
                        Console.Out.WriteLine("  {0}", file);
                    }

                    Console.Out.WriteLine("        {0} file(s) copied", cleanedFiles.Count);
                }
                else if (_isForced)
                {
                    Console.Error.WriteLine("  deployment failed. U_U");
                }
                else
                {
                    Console.Error.WriteLine("  deployment failed. U_U");
                    Pause();

                    Result = ResultValue.RemovalFailed;
                    return;
                }

                Configuration.Type types = Configuration.Type.Global;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necissary content has been deployed to the system
                Result = ResultValue.Success;

                Console.Out.WriteLine();
                Console.Out.WriteLine("Success! {0} was deployed! ^_^", Program.Title);
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Пример #3
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var metricSourceValueTypeDataviewGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid();
            var metricSourceValueTypeSqlGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid();

            var metricsQry = new MetricService( new RockContext() ).Queryable().AsNoTracking().Where(
                a => a.ScheduleId.HasValue
                && a.SourceValueTypeId.HasValue
                && ( a.SourceValueType.Guid == metricSourceValueTypeDataviewGuid || a.SourceValueType.Guid == metricSourceValueTypeSqlGuid ) );

            var metricIdList = metricsQry.OrderBy( a => a.Title ).ThenBy( a => a.Subtitle ).Select( a => a.Id ).ToList();

            var metricExceptions = new List<Exception>();
            int metricsCalculated = 0;
            int metricValuesCalculated = 0;
            Metric metric = null;

            foreach ( var metricId in metricIdList )
            {
                try
                {
                    using ( var rockContextForMetricEntity = new RockContext() )
                    {
                        var metricService = new MetricService( rockContextForMetricEntity );

                        metric = metricService.Get( metricId );
                        var lastRunDateTime = metric.LastRunDateTime ?? metric.CreatedDateTime ?? metric.ModifiedDateTime;
                        if ( lastRunDateTime.HasValue )
                        {
                            var currentDateTime = RockDateTime.Now;

                            // get all the schedule times that were supposed to run since that last time it was scheduled to run
                            var scheduledDateTimesToProcess = metric.Schedule.GetScheduledStartTimes( lastRunDateTime.Value, currentDateTime ).Where( a => a > lastRunDateTime.Value ).ToList();
                            foreach ( var scheduleDateTime in scheduledDateTimesToProcess )
                            {
                                using ( var rockContextForMetricValues = new RockContext() )
                                {
                                    var metricPartitions = new MetricPartitionService( rockContextForMetricValues ).Queryable().Where( a => a.MetricId == metric.Id ).ToList();
                                    var metricValueService = new MetricValueService( rockContextForMetricValues );
                                    List<ResultValue> resultValues = new List<ResultValue>();
                                    bool getMetricValueDateTimeFromResultSet = false;
                                    if ( metric.SourceValueType.Guid == metricSourceValueTypeDataviewGuid )
                                    {
                                        // get the metric value from the DataView
                                        if ( metric.DataView != null )
                                        {
                                            var errorMessages = new List<string>();
                                            var qry = metric.DataView.GetQuery( null, null, out errorMessages );
                                            if ( metricPartitions.Count > 1 || metricPartitions.First().EntityTypeId.HasValue )
                                            {
                                                throw new NotImplementedException( "Partitioned Metrics using DataViews is not supported." );
                                            }
                                            else
                                            {
                                                var resultValue = new ResultValue();
                                                resultValue.Value = Convert.ToDecimal( qry.Count() );
                                                resultValue.Partitions = new List<ResultValuePartition>();
                                                resultValue.MetricValueDateTime = scheduleDateTime;
                                                resultValues.Add( resultValue );
                                            }
                                        }
                                    }
                                    else if ( metric.SourceValueType.Guid == metricSourceValueTypeSqlGuid )
                                    {
                                        //// calculate the metricValue using the results from the SQL
                                        //// assume SQL is in one of the following forms:
                                        //// -- "SELECT Count(*), Partion0EntityId, Partion1EntityId, Partion2EntityId,.. FROM ..."
                                        //// -- "SELECT Count(*), [MetricValueDateTime], Partion0EntityId, Partion1EntityId, Partion2EntityId,.. FROM ..."
                                        if ( !string.IsNullOrWhiteSpace( metric.SourceSql ) )
                                        {
                                            string formattedSql = metric.SourceSql.ResolveMergeFields( metric.GetMergeObjects( scheduleDateTime ) );
                                            var tableResult = DbService.GetDataTable( formattedSql, System.Data.CommandType.Text, null );

                                            if ( tableResult.Columns.Count >= 2 && tableResult.Columns[1].ColumnName == "MetricValueDateTime" )
                                            {
                                                getMetricValueDateTimeFromResultSet = true;
                                            }

                                            foreach ( var row in tableResult.Rows.OfType<System.Data.DataRow>() )
                                            {
                                                var resultValue = new ResultValue();

                                                resultValue.Value = Convert.ToDecimal( row[0] );
                                                if ( getMetricValueDateTimeFromResultSet )
                                                {
                                                    resultValue.MetricValueDateTime = Convert.ToDateTime( row[1] );
                                                }
                                                else
                                                {
                                                    resultValue.MetricValueDateTime = scheduleDateTime;
                                                }

                                                resultValue.Partitions = new List<ResultValuePartition>();
                                                int partitionPosition = 0;
                                                int partitionFieldIndex = getMetricValueDateTimeFromResultSet ? 2 : 1;
                                                int partitionColumnCount = tableResult.Columns.Count - 1;
                                                while ( partitionFieldIndex <= partitionColumnCount )
                                                {
                                                    resultValue.Partitions.Add( new ResultValuePartition
                                                    {
                                                        PartitionPosition = partitionPosition,
                                                        EntityId = row[partitionFieldIndex] as int?
                                                    } );

                                                    partitionPosition++;
                                                    partitionFieldIndex++;
                                                }

                                                resultValues.Add( resultValue );
                                            }
                                        }
                                    }

                                    metric.LastRunDateTime = scheduleDateTime;
                                    metricsCalculated++;
                                    metricValuesCalculated += resultValues.Count();

                                    if ( resultValues.Any() )
                                    {
                                        List<MetricValue> metricValuesToAdd = new List<MetricValue>();
                                        foreach ( var resultValue in resultValues )
                                        {
                                            var metricValue = new MetricValue();
                                            metricValue.MetricId = metric.Id;
                                            metricValue.MetricValueDateTime = resultValue.MetricValueDateTime;
                                            metricValue.MetricValueType = MetricValueType.Measure;
                                            metricValue.YValue = resultValue.Value;
                                            metricValue.CreatedDateTime = RockDateTime.Now;
                                            metricValue.ModifiedDateTime = RockDateTime.Now;
                                            metricValue.MetricValuePartitions = new List<MetricValuePartition>();
                                            var metricPartitionsByPosition = metricPartitions.OrderBy( a => a.Order ).ToList();

                                            if ( !resultValue.Partitions.Any() && metricPartitionsByPosition.Count() == 1 && !metricPartitionsByPosition[0].EntityTypeId.HasValue )
                                            {
                                                // a metric with just the default partition (not partitioned by Entity)
                                                var metricPartition = metricPartitionsByPosition[0];
                                                var metricValuePartition = new MetricValuePartition();
                                                metricValuePartition.MetricPartition = metricPartition;
                                                metricValuePartition.MetricPartitionId = metricPartition.Id;
                                                metricValuePartition.MetricValue = metricValue;
                                                metricValuePartition.EntityId = null;
                                                metricValue.MetricValuePartitions.Add( metricValuePartition );
                                            }
                                            else
                                            {
                                                foreach ( var partitionResult in resultValue.Partitions )
                                                {
                                                    if ( metricPartitionsByPosition.Count > partitionResult.PartitionPosition )
                                                    {
                                                        var metricPartition = metricPartitionsByPosition[partitionResult.PartitionPosition];
                                                        var metricValuePartition = new MetricValuePartition();
                                                        metricValuePartition.MetricPartition = metricPartition;
                                                        metricValuePartition.MetricPartitionId = metricPartition.Id;
                                                        metricValuePartition.MetricValue = metricValue;
                                                        metricValuePartition.EntityId = partitionResult.EntityId;
                                                        metricValue.MetricValuePartitions.Add( metricValuePartition );
                                                    }
                                                }
                                            }

                                            if ( metricValue.MetricValuePartitions == null || !metricValue.MetricValuePartitions.Any() )
                                            {
                                                // shouldn't happen, but just in case
                                                throw new Exception( "MetricValue requires at least one Partition Value" );
                                            }
                                            else
                                            {
                                                metricValuesToAdd.Add( metricValue );
                                            }
                                        }

                                        // if a single metricValueDateTime was specified, delete any existing metric values for this date and refresh with the current results
                                        var dbTransaction = rockContextForMetricValues.Database.BeginTransaction();
                                        if ( getMetricValueDateTimeFromResultSet )
                                        {
                                            var metricValueDateTimes = metricValuesToAdd.Select( a => a.MetricValueDateTime ).Distinct().ToList();
                                            foreach ( var metricValueDateTime in metricValueDateTimes )
                                            {
                                                bool alreadyHasMetricValues = metricValueService.Queryable().Where( a => a.MetricId == metric.Id && a.MetricValueDateTime == metricValueDateTime ).Any();
                                                if ( alreadyHasMetricValues )
                                                {
                                                    // use direct SQL to clean up any existing metric values
                                                    rockContextForMetricValues.Database.ExecuteSqlCommand( @"
                                                        DELETE
                                                        FROM MetricValuePartition
                                                        WHERE MetricValueId IN (
                                                            SELECT Id
                                                            FROM MetricValue
                                                            WHERE MetricId = @metricId
                                                            AND MetricValueDateTime = @metricValueDateTime
                                                        )
                                                    ", new SqlParameter( "@metricId", metric.Id ), new SqlParameter( "@metricValueDateTime", metricValueDateTime ) );

                                                    rockContextForMetricValues.Database.ExecuteSqlCommand( @"
                                                        DELETE
                                                        FROM MetricValue
                                                        WHERE MetricId = @metricId
                                                        AND MetricValueDateTime = @metricValueDateTime
                                                    ", new SqlParameter( "@metricId", metric.Id ), new SqlParameter( "@metricValueDateTime", metricValueDateTime ) );
                                                }
                                            }
                                        }

                                        metricValueService.AddRange( metricValuesToAdd );

                                        // disable savechanges PrePostProcessing since there could be hundreds or thousands of metric values getting inserted/updated
                                        rockContextForMetricValues.SaveChanges( true );
                                        dbTransaction.Commit();
                                    }

                                    rockContextForMetricEntity.SaveChanges();
                                }
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    metricExceptions.Add( new Exception( string.Format( "Exception when calculating metric for {0} ", metric ), ex ) );
                }
            }

            context.Result = string.Format( "Calculated a total of {0} metric values for {1} metrics", metricValuesCalculated, metricsCalculated );

            if ( metricExceptions.Any() )
            {
                throw new AggregateException( "One or more metric calculations failed ", metricExceptions );
            }
        }
Пример #4
0
        private void HandleResponse(
            State state,
            Func<State, HttpWebResponse> getResponse,
            Func<Stream, string> getResponseOutput)
        {
            state.Stopwatch.Stop();
            // activeAsyncList.Remove(state);
            var result = new ResultValue();

            try
            {
                using (var response = getResponse(state))
                {
                    result.StatusCode = response.StatusCode;
                    using (var stream = response.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            var strOut = getResponseOutput(stream);

                            if (!string.IsNullOrEmpty(strOut))
                            {
                                Interlocked.Add(ref totalTransferedBytes, strOut.Length);
                                if (SampleResponse == null)
                                {
                                    SampleResponse = strOut;
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                state.Stopwatch.Stop();
                if (ex.Response != null)
                {
                    using (var resp = (HttpWebResponse)ex.Response)
                    {
                        result.StatusCode = resp.StatusCode;
                        HandleError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                state.Stopwatch.Stop();
                HandleError(ex);
            }

            result.TimeTaken = state.Stopwatch.Elapsed;
            results.Add(result);

            Interlocked.Increment(ref executedRequests);
            HandleProgress(result);
            SetOperationStatus();
        }
Пример #5
0
        private void RemoveElevated()
        {
            if (_isPassive)
            {
                this.Result = ResultValue.Unprivileged;
            }
            else
            {
                /* cannot uninstall while not elevated (need access to %PROGRAMFILES%), re-launch
                 * self as an elevated process with identical arguments. */

                // build arguments
                var arguments = new System.Text.StringBuilder("remove");
                if (_isPassive)
                {
                    arguments.Append(" ")
                    .Append(ParamPassiveKey);
                }
                if (_isForced)
                {
                    arguments.Append(" ")
                    .Append(ParamForceKey);
                }
                if (!String.IsNullOrEmpty(_customPath))
                {
                    arguments.Append(" ")
                    .Append(ParamForceKey)
                    .Append(" \"")
                    .Append(_customPath)
                    .Append("\"");
                }

                // build process start options
                var options = new ProcessStartInfo()
                {
                    FileName         = "cmd",
                    Arguments        = $"/c \"{Program.ExecutablePath}\" {arguments}",
                    UseShellExecute  = true,    // shellexecute for verb usage
                    Verb             = "runas", // used to invoke elevation
                    WorkingDirectory = Program.Location,
                };

                Git.Trace.WriteLine($"create process: cmd '{options.Verb}' '{options.FileName}' '{options.Arguments}' .");

                try
                {
                    // create the process
                    var elevated = Process.Start(options);

                    // wait for the process to complete
                    elevated.WaitForExit();

                    Git.Trace.WriteLine($"process exited with {elevated.ExitCode}.");

                    // exit with the elevated process' exit code
                    this.ExitCode = elevated.ExitCode;
                }
                catch (Exception exception)
                {
                    Git.Trace.WriteLine($"! process failed with '{exception.Message}'.");
                    this.Result = ResultValue.Unprivileged;
                }
            }
        }
Пример #6
0
        public void RemoveConsole()
        {
            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    RemoveElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine($"Fatal: custom path does not exist: '{_customPath}'. U_U");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Removing from custom path: '{_customPath}'.");

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Git.Trace.WriteLine($"Git found: '{installation.Path}'.");

                        // track known Git installations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine($"  {installation.Path}");
                        }
                    }
                }

                if (installations == null)
                {
                    Program.LogEvent($"Git was not detected, unable to continue with removal.", EventLogEntryType.Error);
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                Configuration.Type types = Configuration.Type.Global | Configuration.Type.System;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Unset, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.System) == Configuration.Type.System)
                    {
                        Console.Out.WriteLine();
                        Console.Out.WriteLine("Updated your /etc/gitconfig [git config --system]");
                    }
                    else
                    {
                        Console.Out.WriteLine();

                        // updating /etc/gitconfig should not fail installation when forced
                        if (!_isForced)
                        {
                            // only 'fatal' when not forced
                            Console.Error.Write("Fatal: ");

                            Result = ResultValue.GitConfigSystemFailed;
                            return;
                        }

                        Console.Error.WriteLine("Unable to update your /etc/gitconfig correctly.");
                    }

                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                List <string> cleanedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Removing from '{installation.Path}'.");

                    if (CleanFiles(installation.Libexec, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        // clean help documents
                        if (Directory.Exists(installation.Doc) &&
                            CleanFiles(installation.Doc, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Console.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine($"  removal failed. {FailFace}");
                    }
                    else
                    {
                        Console.Error.WriteLine($"  removal failed. {FailFace}");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (Directory.Exists(UserBinPath))
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Removing from '{UserBinPath}'.");

                    if (CleanFiles(UserBinPath, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        if (CleanFiles(UserBinPath, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Console.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine($"  removal failed. {FailFace}");
                    }
                    else
                    {
                        Console.Error.WriteLine($"  removal failed. {FailFace}");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CleanFiles(CygwinPath, FileList, out cleanedFiles))
                    {
                        int cleanedCount = cleanedFiles.Count;

                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        if (CleanFiles(CygwinPath, DocsList, out cleanedFiles))
                        {
                            cleanedCount += cleanedFiles.Count;

                            foreach (var file in cleanedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Console.Out.WriteLine($"     {cleanedCount} file(s) cleaned");
                    }
                }

                // all necissary content has been deployed to the system
                Result = ResultValue.Success;

                Program.LogEvent($"{Program.Title} successfully removed.", EventLogEntryType.Information);

                Console.Out.WriteLine();
                Console.Out.WriteLine($"Success! {Program.Title} was removed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
        public void RemoveConsole()
        {
            Trace.WriteLine("Installer::RemoveConsole");

            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    RemoveElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: custom path does not exist: '{0}'. U_U", _customPath);
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Removing from custom path: '{0}'.", _customPath);

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Trace.Write("   Git found: " + installation.Path);

                        // track known Git installtations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine("  {0}", installation.Path);
                        }
                    }
                }

                if (installations == null)
                {
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                // only update the system configs if using a custom path
                Configuration.Type types = String.IsNullOrWhiteSpace(_customPath)
                    ? Configuration.Type.Global | Configuration.Type.System
                    : Configuration.Type.System;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Unset, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.System) == Configuration.Type.System)
                    {
                        Console.Out.WriteLine();
                        Console.Out.WriteLine("Updated your /etc/gitconfig [git config --system]");
                    }
                    else
                    {
                        Console.Out.WriteLine();

                        // updating /etc/gitconfig should not fail installation when forced
                        if (!_isForced)
                        {
                            // only 'fatal' when not forced
                            Console.Error.Write("Fatal: ");

                            Result = ResultValue.GitConfigSystemFailed;
                            return;
                        }

                        Console.Error.WriteLine("Unable to update your /etc/gitconfig correctly.");
                    }

                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                List <string> cleanedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Removing from '{0}'.", installation.Path);

                    if (CleanFiles(installation.Libexec, out cleanedFiles))
                    {
                        foreach (var file in cleanedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) cleaned", cleanedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  removal failed. U_U");
                        Pause();

                        Result = ResultValue.RemovalFailed;
                        return;
                    }
                }

                // all necissary content has been deployed to the system
                Result = ResultValue.Success;

                Console.Out.WriteLine();
                Console.Out.WriteLine("Success! {0} was removed! ^_^", Program.Title);
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Пример #8
0
        /// <summary>
        /// Pobiera listę komponentow dla zadanego id komponentu-rodzica
        /// </summary>
        /// <param name="user">zalogowany użytkownik</param>
        /// <param name="id">id komponentu-rodzica</param>
        /// <returns></returns>
        public Dictionary <int, string> GetBillingComponents(Entities.User user, int id)
        {
            ResultValue <Dictionary <int, string> > result = manager.HPService.GetBillingComponents(user, id);

            return(result.GetResult());
        }
Пример #9
0
 public FieldValueWrapper(int fieldId, ResultValue value)
 {
     FieldId = fieldId;
     Value = value;
 }
Пример #10
0
        private ResultValue CheckInfo(UserInfo info)
        {
            ResultValue res = new ResultValue();

            if (info == null)
            {
                res.Status  = -1;
                res.Message = "数据异常";
                return(res);
            }

            info.ID       = Utility.GetValue(info.ID);
            info.Name     = Utility.GetValue(info.Name);
            info.Province = Utility.GetValue(info.Province);

            if (string.IsNullOrEmpty(info.ID))
            {
                res.Status  = -1;
                res.Message = "身份证号码不能为空";
                return(res);
            }
            else
            {
                if (!CheckId(info.ID))
                {
                    res.Status  = -1;
                    res.Message = "无效的身份证号码";

                    return(res);
                }
            }

            if (info.Amount <= 0 || info.Amount > 100000000)
            {
                res.Status  = -1;
                res.Message = "无效的金额";

                return(res);
            }

            if (string.IsNullOrEmpty(info.Name))
            {
                res.Status  = -1;
                res.Message = "无效的姓名";

                return(res);
            }
            else
            {
                if (info.Name.Length > 100)
                {
                    res.Status  = -1;
                    res.Message = "姓名非法";
                    return(res);
                }
            }

            if (string.IsNullOrEmpty(info.Province))
            {
                res.Status  = -1;
                res.Message = "无效的省份";

                return(res);
            }
            else
            {
                if (info.Province.Length > 100)
                {
                    res.Status  = -1;
                    res.Message = "省份数据非法";
                    return(res);
                }
            }

            res.Status  = 0;
            res.Message = "";

            return(res);
        }
Пример #11
0
 private void btn_Translate_Click(object sender, EventArgs e)
 {
     Result = new ResultValue(this);
 }
Пример #12
0
        /// <summary>
        /// 添加一个工作调度
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task <ResultValue> AddScheduleJobAsync(ScheduleEntity entity)
        {
            var result = new ResultValue();

            try
            {
                //检查任务是否已存在
                var jobKey = new JobKey(entity.JobName, entity.JobGroup);
                if (await Scheduler.CheckExists(jobKey))
                {
                    result.MsgCode = 3;
                    result.Msg     = "任务已存在";
                    return(result);
                }

                ////加载程序集(dll文件地址),使用Assembly类
                //var asstypes = Assembly.Load("BusDataExchan").GetTypes()
                //    .Where(t => t.GetInterfaces().Contains(typeof(IJob)))
                //    .ToArray();

                if (entity.TargetCall.IndexOf(",") < 0)
                {
                    result.MsgCode = 3;
                    result.Msg     = "对象名称格式不符合Job-Type";
                    return(result);
                }
                var    Assemblys = entity.TargetCall.Split(',');
                string dllname   = Assemblys[1];
                string jobname   = Assemblys[0];

                //获取类型,参数(名称空间+类)
                Type _ijob = null;
                try
                {
                    _ijob = Assembly.Load(dllname).GetType(jobname);
                }
                catch (Exception err)
                {
                    //日志err
                    result.MsgCode = 3;
                    result.Msg     = "未找到描述的对象";
                    return(result);
                }

                //配置
                var DataDir = new Dictionary <string, string>()
                {
                    { Constant.TARGETCALL, entity.TargetCall },
                    { Constant.TARGETTYPE, entity.TargetType },
                    //{ Constant.MAILMESSAGE, ((int)entity.MailMessage).ToString()},
                };
                if (_ijob == null)
                {
                    result.MsgCode = 3;
                    result.Msg     = "未找到调度器";
                    return(result);
                }

                // 定义这个工作,并将其绑定到我们的IJob实现类
                IJobDetail job = JobBuilder.Create(_ijob)
                                 .SetJobData(new JobDataMap(DataDir))
                                 .WithDescription(entity.Description)
                                 .WithIdentity(entity.JobName, entity.JobGroup)
                                 .Build();
                // 创建触发器
                ITrigger trigger;

                entity.TriggerType = TriggerTypeEnum.Cron;

                //校验是否正确的执行周期表达式
                if (entity.TriggerType == TriggerTypeEnum.Cron)//CronExpression.IsValidExpression(entity.Cron))
                {
                    trigger = CreateCronTrigger(entity);
                }
                else
                {
                    trigger = CreateSimpleTrigger(entity);
                }

                // 告诉Quartz使用我们的触发器来安排作业
                await Scheduler.ScheduleJob(job, trigger);

                result.MsgCode = 1;
                result.Msg     = "添加成功";
            }
            catch (Exception ex)
            {
                result.MsgCode = 3;
                result.Msg     = ex.Message;
            }
            return(result);
        }
Пример #13
0
 private void OKButton_Click(object sender, EventArgs e)
 {
     Result = new ResultValue(this);
 }
Пример #14
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var metricSourceValueTypeDataviewGuid = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_DATAVIEW.AsGuid();
            var metricSourceValueTypeSqlGuid      = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_SQL.AsGuid();
            var metricSourceValueTypeLavaGuid     = Rock.SystemGuid.DefinedValue.METRIC_SOURCE_VALUE_TYPE_LAVA.AsGuid();

            Guid[] calculatedSourceTypes = new Guid[] {
                metricSourceValueTypeDataviewGuid,
                metricSourceValueTypeSqlGuid,
                metricSourceValueTypeLavaGuid
            };

            var metricsQry = new MetricService(new RockContext()).Queryable().AsNoTracking().Where(
                a => a.ScheduleId.HasValue &&
                a.SourceValueTypeId.HasValue &&
                calculatedSourceTypes.Contains(a.SourceValueType.Guid));

            var metricIdList = metricsQry.OrderBy(a => a.Title).ThenBy(a => a.Subtitle).Select(a => a.Id).ToList();

            var    metricExceptions       = new List <Exception>();
            int    metricsCalculated      = 0;
            int    metricValuesCalculated = 0;
            Metric metric = null;

            foreach (var metricId in metricIdList)
            {
                try
                {
                    using (var rockContextForMetricEntity = new RockContext())
                    {
                        var metricService = new MetricService(rockContextForMetricEntity);

                        metric = metricService.Get(metricId);

                        /*  Get the last time the metric has run, if it has never run then set it as the first day of the current week to give it a chance to run now.
                         *  NOTE: This is being used instead of Min Date to prevent a schedule with a start date of months or years back from running for each period since then.
                         *  This would be the case for the "out-of-the-box" Rock daily metrics "Active Records", "Active Families", and "Active Connection Requests" if they
                         *  have never run before. Or if a new user created metric uses a schedule that has an older start date.
                         */
                        DateTime currentDateTime = RockDateTime.Now;
                        DateTime?startOfWeek     = currentDateTime.StartOfWeek(RockDateTime.FirstDayOfWeek);
                        DateTime?lastRunDateTime = metric.LastRunDateTime ?? startOfWeek;

                        // get all the schedule times that were supposed to run since that last time it was scheduled to run
                        var scheduledDateTimesToProcess = metric.Schedule.GetScheduledStartTimes(lastRunDateTime.Value, currentDateTime).Where(a => a > lastRunDateTime.Value).ToList();
                        foreach (var scheduleDateTime in scheduledDateTimesToProcess)
                        {
                            using (var rockContextForMetricValues = new RockContext())
                            {
                                var metricPartitions                     = new MetricPartitionService(rockContextForMetricValues).Queryable().Where(a => a.MetricId == metric.Id).ToList();
                                var metricValueService                   = new MetricValueService(rockContextForMetricValues);
                                List <ResultValue> resultValues          = new List <ResultValue>();
                                bool getMetricValueDateTimeFromResultSet = false;
                                if (metric.SourceValueType.Guid == metricSourceValueTypeDataviewGuid)
                                {
                                    // get the metric value from the DataView
                                    if (metric.DataView != null)
                                    {
                                        var errorMessages = new List <string>();
                                        var qry           = metric.DataView.GetQuery(null, null, out errorMessages);
                                        if (metricPartitions.Count > 1 || metricPartitions.First().EntityTypeId.HasValue)
                                        {
                                            throw new NotImplementedException("Partitioned Metrics using DataViews is not supported.");
                                        }
                                        else
                                        {
                                            var resultValue = new ResultValue();
                                            resultValue.Value               = Convert.ToDecimal(qry.Count());
                                            resultValue.Partitions          = new List <ResultValuePartition>();
                                            resultValue.MetricValueDateTime = scheduleDateTime;
                                            resultValues.Add(resultValue);
                                        }
                                    }
                                }
                                else if (metric.SourceValueType.Guid == metricSourceValueTypeSqlGuid)
                                {
                                    //// calculate the metricValue using the results from the SQL
                                    //// assume SQL is in one of the following forms:
                                    //// -- "SELECT Count(*) FROM ..."
                                    //// -- "SELECT Count(*), [MetricValueDateTime] FROM ..."
                                    //// -- "SELECT Count(*), Partition0EntityId, Partition1EntityId, Partition2EntityId,.. FROM ..."
                                    //// -- "SELECT Count(*), [MetricValueDateTime], Partition0EntityId, Partition1EntityId, Partition2EntityId,.. FROM ..."
                                    if (!string.IsNullOrWhiteSpace(metric.SourceSql))
                                    {
                                        string formattedSql = metric.SourceSql.ResolveMergeFields(metric.GetMergeObjects(scheduleDateTime));
                                        var    tableResult  = DbService.GetDataTable(formattedSql, System.Data.CommandType.Text, null);

                                        if (tableResult.Columns.Count >= 2 && tableResult.Columns[1].ColumnName == "MetricValueDateTime")
                                        {
                                            getMetricValueDateTimeFromResultSet = true;
                                        }

                                        foreach (var row in tableResult.Rows.OfType <System.Data.DataRow>())
                                        {
                                            var resultValue = new ResultValue();

                                            resultValue.Value = Convert.ToDecimal(row[0]);
                                            if (getMetricValueDateTimeFromResultSet)
                                            {
                                                resultValue.MetricValueDateTime = Convert.ToDateTime(row[1]);
                                            }
                                            else
                                            {
                                                resultValue.MetricValueDateTime = scheduleDateTime;
                                            }

                                            resultValue.Partitions = new List <ResultValuePartition>();
                                            int partitionPosition    = 0;
                                            int partitionFieldIndex  = getMetricValueDateTimeFromResultSet ? 2 : 1;
                                            int partitionColumnCount = tableResult.Columns.Count - 1;
                                            while (partitionFieldIndex <= partitionColumnCount)
                                            {
                                                resultValue.Partitions.Add(new ResultValuePartition
                                                {
                                                    PartitionPosition = partitionPosition,
                                                    EntityId          = row[partitionFieldIndex] as int?
                                                });

                                                partitionPosition++;
                                                partitionFieldIndex++;
                                            }

                                            resultValues.Add(resultValue);
                                        }
                                    }
                                }
                                else if (metric.SourceValueType.Guid == metricSourceValueTypeLavaGuid)
                                {
                                    //// calculate the metricValue using the results from Lava
                                    //// assume Lava Output is in one of the following forms:
                                    //// A single Count
                                    //// 42
                                    //// A List of Count, MetricValueDateTime
                                    //// 42, 1/1/2017
                                    //// 40, 1/2/2017
                                    //// 49, 1/3/2017
                                    //// A List of Count, Partition0EntityId, Partition1EntityId, Partition2EntityId
                                    //// 42, 201, 450, 654
                                    //// 42, 202, 450, 654
                                    //// 42, 203, 450, 654
                                    //// A List of Count, MetricValueDateTime,  Partition0EntityId, Partition1EntityId, Partition2EntityId
                                    //// 42, 1/1/2017, 201, 450, 654
                                    //// 42, 1/2/2017, 202, 450, 654
                                    //// 42, 1/3/2017, 203, 450, 654
                                    if (!string.IsNullOrWhiteSpace(metric.SourceLava))
                                    {
                                        var           mergeObjects = metric.GetMergeObjects(scheduleDateTime);
                                        string        lavaResult   = metric.SourceLava.ResolveMergeFields(mergeObjects, enabledLavaCommands: "All", throwExceptionOnErrors: true);
                                        List <string> resultLines  = lavaResult.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
                                                                     .Select(a => a.Trim()).Where(a => !string.IsNullOrEmpty(a)).ToList();
                                        List <string[]> resultList = resultLines.Select(a => a.SplitDelimitedValues()).ToList();

                                        if (resultList.Any())
                                        {
                                            if (resultList[0].Length >= 2)
                                            {
                                                // if the value of the data in the 2nd column is a Date, assume that is is the MetricValueDateTime
                                                if (resultList[0][1].AsDateTime().HasValue)
                                                {
                                                    getMetricValueDateTimeFromResultSet = true;
                                                }
                                            }
                                        }

                                        foreach (var row in resultList)
                                        {
                                            var resultValue = new ResultValue();

                                            resultValue.Value = row[0].AsDecimal();
                                            if (getMetricValueDateTimeFromResultSet)
                                            {
                                                resultValue.MetricValueDateTime = row[1].AsDateTime() ?? scheduleDateTime;
                                            }
                                            else
                                            {
                                                resultValue.MetricValueDateTime = scheduleDateTime;
                                            }

                                            resultValue.Partitions = new List <ResultValuePartition>();
                                            int partitionPosition    = 0;
                                            int partitionFieldIndex  = getMetricValueDateTimeFromResultSet ? 2 : 1;
                                            int partitionColumnCount = row.Length - 1;
                                            while (partitionFieldIndex <= partitionColumnCount)
                                            {
                                                resultValue.Partitions.Add(new ResultValuePartition
                                                {
                                                    PartitionPosition = partitionPosition,
                                                    EntityId          = row[partitionFieldIndex].AsIntegerOrNull()
                                                });

                                                partitionPosition++;
                                                partitionFieldIndex++;
                                            }

                                            resultValues.Add(resultValue);
                                        }
                                    }
                                }

                                metric.LastRunDateTime = scheduleDateTime;
                                metricsCalculated++;
                                metricValuesCalculated += resultValues.Count();

                                if (resultValues.Any())
                                {
                                    List <MetricValue> metricValuesToAdd = new List <MetricValue>();
                                    foreach (var resultValue in resultValues)
                                    {
                                        var metricValue = new MetricValue();
                                        metricValue.MetricId            = metric.Id;
                                        metricValue.MetricValueDateTime = resultValue.MetricValueDateTime;
                                        metricValue.MetricValueType     = MetricValueType.Measure;
                                        metricValue.YValue                = resultValue.Value;
                                        metricValue.CreatedDateTime       = RockDateTime.Now;
                                        metricValue.ModifiedDateTime      = RockDateTime.Now;
                                        metricValue.MetricValuePartitions = new List <MetricValuePartition>();
                                        var metricPartitionsByPosition = metricPartitions.OrderBy(a => a.Order).ToList();

                                        if (!resultValue.Partitions.Any() && metricPartitionsByPosition.Count() == 1 && !metricPartitionsByPosition[0].EntityTypeId.HasValue)
                                        {
                                            // a metric with just the default partition (not partitioned by Entity)
                                            var metricPartition      = metricPartitionsByPosition[0];
                                            var metricValuePartition = new MetricValuePartition();
                                            metricValuePartition.MetricPartition   = metricPartition;
                                            metricValuePartition.MetricPartitionId = metricPartition.Id;
                                            metricValuePartition.MetricValue       = metricValue;
                                            metricValuePartition.EntityId          = null;
                                            metricValue.MetricValuePartitions.Add(metricValuePartition);
                                        }
                                        else
                                        {
                                            foreach (var partitionResult in resultValue.Partitions)
                                            {
                                                if (metricPartitionsByPosition.Count > partitionResult.PartitionPosition)
                                                {
                                                    var metricPartition      = metricPartitionsByPosition[partitionResult.PartitionPosition];
                                                    var metricValuePartition = new MetricValuePartition();
                                                    metricValuePartition.MetricPartition   = metricPartition;
                                                    metricValuePartition.MetricPartitionId = metricPartition.Id;
                                                    metricValuePartition.MetricValue       = metricValue;
                                                    metricValuePartition.EntityId          = partitionResult.EntityId;
                                                    metricValue.MetricValuePartitions.Add(metricValuePartition);
                                                }
                                            }
                                        }

                                        if (metricValue.MetricValuePartitions == null || !metricValue.MetricValuePartitions.Any())
                                        {
                                            // shouldn't happen, but just in case
                                            throw new Exception("MetricValue requires at least one Partition Value");
                                        }
                                        else
                                        {
                                            metricValuesToAdd.Add(metricValue);
                                        }
                                    }

                                    // if a single metricValueDateTime was specified, delete any existing metric values for this date and refresh with the current results
                                    var dbTransaction = rockContextForMetricValues.Database.BeginTransaction();
                                    if (getMetricValueDateTimeFromResultSet)
                                    {
                                        var metricValueDateTimes = metricValuesToAdd.Select(a => a.MetricValueDateTime).Distinct().ToList();
                                        foreach (var metricValueDateTime in metricValueDateTimes)
                                        {
                                            bool alreadyHasMetricValues = metricValueService.Queryable().Where(a => a.MetricId == metric.Id && a.MetricValueDateTime == metricValueDateTime).Any();
                                            if (alreadyHasMetricValues)
                                            {
                                                // use direct SQL to clean up any existing metric values
                                                rockContextForMetricValues.Database.ExecuteSqlCommand(@"
                                                    DELETE
                                                    FROM MetricValuePartition
                                                    WHERE MetricValueId IN (
                                                        SELECT Id
                                                        FROM MetricValue
                                                        WHERE MetricId = @metricId
                                                        AND MetricValueDateTime = @metricValueDateTime
                                                    )
                                                ", new SqlParameter("@metricId", metric.Id), new SqlParameter("@metricValueDateTime", metricValueDateTime));

                                                rockContextForMetricValues.Database.ExecuteSqlCommand(@"
                                                    DELETE
                                                    FROM MetricValue
                                                    WHERE MetricId = @metricId
                                                    AND MetricValueDateTime = @metricValueDateTime
                                                ", new SqlParameter("@metricId", metric.Id), new SqlParameter("@metricValueDateTime", metricValueDateTime));
                                            }
                                        }
                                    }

                                    metricValueService.AddRange(metricValuesToAdd);

                                    // disable savechanges PrePostProcessing since there could be hundreds or thousands of metric values getting inserted/updated
                                    rockContextForMetricValues.SaveChanges(true);
                                    dbTransaction.Commit();
                                }

                                rockContextForMetricEntity.SaveChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    metricExceptions.Add(new Exception(string.Format("Exception when calculating metric for {0} ", metric), ex));
                }
            }

            context.Result = string.Format("Calculated a total of {0} metric values for {1} metrics", metricValuesCalculated, metricsCalculated);

            if (metricExceptions.Any())
            {
                throw new AggregateException("One or more metric calculations failed ", metricExceptions);
            }
        }
        public ResultValue AddEditEmployeeById(EmployeeEntity employee)
        {
            var response = new ResultValue();

            try
            {
                var empIDParam = new SqlParameter
                {
                    ParameterName = "Id",
                    DbType        = DbType.Int32,
                    Value         = (object)employee.Id ?? DBNull.Value
                };
                var firstNameParam = new SqlParameter
                {
                    ParameterName = "FirstName",
                    DbType        = DbType.String,
                    Value         = employee.FirstName
                };
                var lastNameParam = new SqlParameter
                {
                    ParameterName = "LastName",
                    DbType        = DbType.String,
                    Value         = (object)employee.LastName ?? DBNull.Value
                };
                var joiningDateParam = new SqlParameter
                {
                    ParameterName = "JoiningDate",
                    DbType        = DbType.DateTime,
                    Value         = employee.JoiningDate
                };
                var salaryParam = new SqlParameter
                {
                    ParameterName = "Salary",
                    DbType        = DbType.Decimal,
                    Value         = employee.Salary
                };
                var result = _repositoryEmployee.ExecuteSQL <string>("AddEditEmployee",
                                                                     empIDParam,
                                                                     firstNameParam,
                                                                     lastNameParam,
                                                                     joiningDateParam,
                                                                     salaryParam).FirstOrDefault();
                if (result != "")
                {
                    response.Success = true;
                    response.Message = result;
                }
                else
                {
                    response.Success = false;
                    response.Message = "";
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                return(response);
            }
        }
Пример #16
0
 public ResultConst(ResultValue value)
 {
     Value = value;
 }
Пример #17
0
        private static async Task <BindResult> EvalBindResult(Results bindResult, AD7PendingBreakpoint pbreak)
        {
            string errormsg = "Unknown error";

            if (bindResult.ResultClass == ResultClass.error)
            {
                if (bindResult.Contains("msg"))
                {
                    errormsg = bindResult.FindString("msg");
                }
                if (String.IsNullOrWhiteSpace(errormsg))
                {
                    errormsg = "Unknown error";
                }
                return(new BindResult(errormsg));
            }
            else if (bindResult.ResultClass != ResultClass.done)
            {
                return(new BindResult(errormsg));
            }
            TupleValue     bkpt = null;
            ValueListValue list = null;

            if (bindResult.Contains("bkpt"))
            {
                ResultValue b = bindResult.Find("bkpt");
                if (b is TupleValue)
                {
                    bkpt = b as TupleValue;
                }
                else if (b is ValueListValue)
                {
                    // "<MULTIPLE>" sometimes includes a list of bound breakpoints
                    list = b as ValueListValue;
                    bkpt = list.Content[0] as TupleValue;
                }
            }
            else
            {
                // If the source file is not found, "done" is the result without a binding
                // (the error is sent via an "&" string and hence lost)
                return(new BindResult(errormsg));
            }
            string bkptType = bkpt.FindString("type");

            // gdb reports breakpoint type "hw breakpoint" for `-break-insert -h` command
            Debug.Assert(bkptType == "breakpoint" || bkptType == "hw breakpoint");

            string number  = bkpt.FindString("number");
            string warning = bkpt.TryFindString("warning");
            string addr    = bkpt.TryFindString("addr");

            PendingBreakpoint bp;

            if (!string.IsNullOrEmpty(warning))
            {
                Debug.Assert(string.IsNullOrEmpty(addr));
                return(new BindResult(new PendingBreakpoint(pbreak, number, MIBreakpointState.Pending), warning));
            }
            bp = new PendingBreakpoint(pbreak, number, StringToBreakpointState(addr));
            if (list == null)   // single breakpoint
            {
                BoundBreakpoint bbp = await bp.GetBoundBreakpoint(bkpt);

                if (bbp == null)
                {
                    return(new BindResult(bp, MICoreResources.Status_BreakpointPending));
                }
                return(new BindResult(bp, bbp));
            }
            else   // <MULTIPLE> with list of addresses
            {
                BindResult res = new BindResult(bp);
                for (int i = 1; i < list.Content.Length; ++i)
                {
                    BoundBreakpoint bbp = await bp.GetBoundBreakpoint(list.Content[i] as TupleValue);

                    res.BoundBreakpoints.Add(bbp);
                }
                return(res);
            }
        }
Пример #18
0
        /// <summary>
        /// Pobiera dostepne kroki dla danej sprawy BPM
        /// </summary>
        /// <param name="issueId">id sprawy BPM</param>
        /// <param name="userId">id użytkownika</param>
        /// <returns></returns>
        public Dictionary <int, string> GetActionForIssue(int issueId, int userId)
        {
            ResultValue <Dictionary <int, string> > moves = manager.HPService.GetActionForIssue(loggedUser, issueId, userId);

            return(moves.GetResult());
        }
Пример #19
0
        internal async Task <List <BoundBreakpoint> > SyncBreakpoint(DebuggedProcess process)
        {
            ResultValue bkpt = await process.MICommandFactory.BreakInfo(Number);

            return(await BindAddresses(bkpt));
        }
Пример #20
0
        public void DeployConsole()
        {
            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Program.LogEvent("No Git installation found, unable to continue deployment.", EventLogEntryType.Error);
                        Console.Out.WriteLine();
                        Console.Error.WriteLine($"Fatal: custom path does not exist: '{_customPath}'. {FailFace}");
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying to custom path: '{_customPath}'.");

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Git.Trace.WriteLine($"   Git found: '{installation.Path}'.");

                        // track known Git installations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }

                    Program.LogEvent($"Custom path deployed to: '{_customPath}'", EventLogEntryType.Information);
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine($"  {installation.Path}");
                        }
                    }
                }

                if (installations == null)
                {
                    Program.LogEvent("No Git installation found, unable to continue.", EventLogEntryType.Error);
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. {FailFace}");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List <string> copiedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{installation.Path}'.");

                    if (CopyFiles(Program.Location, installation.Libexec, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        // copy help documents
                        if (Directory.Exists(installation.Doc) &&
                            CopyFiles(Program.Location, installation.Doc, DocsList, out copiedFiles))
                        {
                            copiedCount += copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{installation.Path}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Warning);
                        Console.Error.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{installation.Path}' failed.", EventLogEntryType.Error);
                        Console.Error.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine($"Deploying from '{Program.Location}' to '{UserBinPath}'.");

                if (!Directory.Exists(UserBinPath))
                {
                    Directory.CreateDirectory(UserBinPath);
                }

                if (CopyFiles(Program.Location, UserBinPath, FileList, out copiedFiles))
                {
                    int copiedCount = copiedFiles.Count;

                    foreach (var file in copiedFiles)
                    {
                        Console.Out.WriteLine($"  {file}");
                    }

                    if (CopyFiles(Program.Location, UserBinPath, DocsList, out copiedFiles))
                    {
                        copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }
                    }

                    Program.LogEvent($"Deployment to '{UserBinPath}' succeeded.", EventLogEntryType.Information);
                    Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                }
                else if (_isForced)
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Warning);
                    Console.Error.WriteLine($"  deployment failed. {FailFace}");
                }
                else
                {
                    Program.LogEvent($"Deployment to '{UserBinPath}' failed.", EventLogEntryType.Error);
                    Console.Error.WriteLine($"  deployment failed. {FailFace}");
                    Pause();

                    Result = ResultValue.DeploymentFailed;
                    return;
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CopyFiles(Program.Location, CygwinPath, FileList, out copiedFiles))
                    {
                        int copiedCount = copiedFiles.Count;

                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine($"  {file}");
                        }

                        if (CopyFiles(Program.Location, CygwinPath, DocsList, out copiedFiles))
                        {
                            copiedCount = copiedFiles.Count;

                            foreach (var file in copiedFiles)
                            {
                                Console.Out.WriteLine($"  {file}");
                            }
                        }

                        Program.LogEvent($"Deployment to '{CygwinPath}' succeeded.", EventLogEntryType.Information);
                        Console.Out.WriteLine($"     {copiedCount} file(s) copied");
                    }
                    else if (_isForced)
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Warning);
                        Console.Error.WriteLine($"  deployment failed. {FailFace}");
                    }
                    else
                    {
                        Program.LogEvent($"Deployment to '{CygwinPath}' failed.", EventLogEntryType.Error);
                        Console.Error.WriteLine($"  deployment failed. {FailFace}");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Configuration.Type types = Configuration.Type.Global;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necessary content has been deployed to the system
                Result = ResultValue.Success;

                Program.LogEvent($"{Program.Title} v{Program.Version.ToString(3)} successfully deployed.", EventLogEntryType.Information);
                Console.Out.WriteLine();
                Console.Out.WriteLine($"Success! {Program.Title} was deployed! {TadaFace}");
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
Пример #21
0
 public Result(KeyValuePair <int, int> B, KeyValuePair <int, int> R, ResultValue result)
 {
     this.B      = B;
     this.R      = R;
     this.result = result;
 }
Пример #22
0
 public Result(string actionName, ResultValue value)
     : this(actionName, value, "")
 {
 }
Пример #23
0
        protected override void OnCalculate()
        {
            ////we need more contrast
            //this.BarColor = Color.White;

            //calculate data
            ResultValue returnvalue = this.calculate(InSeries, Open, High, null, null, this.Bollinger_Period, this.Bollinger_Standard_Deviation, this.Momentum_Period, this.RSI_Period, this.RSI_Smooth, this.RSI_Level_Low, this.RSI_Level_High, this.Momentum_Level_Low, this.Momentum_Level_High);

            //If the calculate method was not finished we need to stop and show an alert message to the user.
            if (returnvalue.ErrorOccured)
            {
                //Display error just one time
                if (!this.ErrorOccured)
                {
                    GlobalUtilities.DrawAlertTextOnChart(this, Const.DefaultStringErrorDuringCalculation);
                    this.ErrorOccured = true;
                }
                return;
            }

            Plot_1.Set(bb_upper);
            Plot_2.Set(bb_middle);
            Plot_3.Set(bb_lower);

            //Entry
            if (returnvalue.Entry.HasValue)
            {
                switch (returnvalue.Entry)
                {
                case OrderDirection.Buy:
                    AddChartDot("ArrowLong_Entry" + Bars[0].Time.Ticks, true, Bars[0].Time, Bars[0].Open, Color.LightGreen);
                    //this.Indicator_Curve_Entry.Set(1);
                    break;

                case OrderDirection.Sell:
                    AddChartDiamond("ArrowShort_Entry" + Bars[0].Time.Ticks, true, Bars[0].Time, Bars[0].Open, Color.LightGreen);
                    //this.Indicator_Curve_Entry.Set(-1);
                    break;
                }
            }
            //else
            //{
            //    //Value was null so nothing to do.
            //    this.Indicator_Curve_Entry.Set(0);
            //}

            //Exit
            if (returnvalue.Exit.HasValue)
            {
                switch (returnvalue.Exit)
                {
                case OrderDirection.Buy:
                    AddChartDiamond("ArrowShort_Exit" + Bars[0].Time.Ticks, true, Bars[0].Time, Bars[0].Open, Color.Red);
                    //this.Indicator_Curve_Exit.Set(0.5);
                    break;

                case OrderDirection.Sell:
                    AddChartDot("ArrowLong_Exit" + Bars[0].Time.Ticks, true, Bars[0].Time, Bars[0].Open, Color.Red);
                    //this.Indicator_Curve_Exit.Set(-0.5);
                    break;
                }
            }
            //else
            //{
            //    //Value was null so nothing to do.
            //    this.Indicator_Curve_Exit.Set(0);
            //}
        }
Пример #24
0
 private void HandleProgress(ResultValue result)
 {
     if (onProgressAction != null)
     {
         onProgressAction(ExecutedRequests, result);
     }
 }
Пример #25
0
        internal async Task ThreadCreatedEvent(int id, string groupId)
        {
            // Mark that the threads have changed
            lock (_threadList)
            {
                {
                    var thread = _threadList.Find(t => t.Id == id);
                    if (thread == null)
                    {
                        _stateChange = true;
                    }
                }

                // This must go before getting the thread-info for the thread since that method call is async.
                // The threadId must be added to the thread-group before the new thread is created or else it will
                // be marked as a child thread and then thread-created and thread-exited won't be sent to the UI
                if (string.IsNullOrEmpty(groupId))
                {
                    groupId = c_defaultGroupId;
                }

                if (!_threadGroups.ContainsKey(groupId))
                {
                    _threadGroups[groupId] = new List <int>();
                }
                _threadGroups[groupId].Add(id);
            }

            // Run Thread-info now to get the target-id
            // ClrDbg doesn't support getting threadInfo while running.
            ResultValue resVal = null;

            if (id >= 0 && _debugger.LaunchOptions.DebuggerMIMode != MIMode.Clrdbg)
            {
                uint?tid = null;
                tid = (uint)id;
                Results results = await _debugger.MICommandFactory.ThreadInfo(tid);

                if (results.ResultClass != ResultClass.done)
                {
                    // This can happen on some versions of gdb where thread-info is not supported while running, so only assert if we're also not running.
                    if (this._debugger.ProcessState != ProcessState.Running)
                    {
                        Debug.Fail("Thread info not successful");
                    }
                }
                else
                {
                    var tlist = results.Find <ValueListValue>("threads");

                    // tlist.Content.Length could be 0 when the thread exits between it getting created and we request thread-info
                    Debug.Assert(tlist.Content.Length <= 1, "Expected at most 1 thread, received more than one thread.");
                    resVal = tlist.Content.FirstOrDefault(item => item.FindInt("id") == id);
                }
            }

            if (resVal != null)
            {
                lock (_threadList)
                {
                    bool bNew   = false;
                    var  thread = SetThreadInfoFromResultValue(resVal, out bNew);
                    Debug.Assert(thread.Id == id, "thread.Id and id should match");

                    if (bNew)
                    {
                        NewThreads.Add(thread);
                        SendThreadEvents(null, null);
                    }
                }
            }
        }
Пример #26
0
 public MIResultFormatException(string field, ResultValue value, Exception innerException)
     : base(COMQC_E_BAD_MESSAGE, innerException)
 {
     Field = field;
     Result = value;
 }
        public void DeployConsole()
        {
            Trace.WriteLine("Installer::DeployConsole");

            SetOutput(_isPassive, _isPassive && _isForced);
            try
            {
                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    DeployElevated();
                    return;
                }

                List <GitInstallation> installations = null;

                // use the custom installation path if supplied
                if (!String.IsNullOrEmpty(_customPath))
                {
                    if (!Directory.Exists(_customPath))
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: custom path does not exist: '{0}'. U_U", _customPath);
                        Pause();

                        Result = ResultValue.InvalidCustomPath;
                        return;
                    }

                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying to custom path: '{0}'.", _customPath);

                    // if the custom path points to a git location then treat it properly
                    GitInstallation installation;
                    if (Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows64v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v2, out installation) ||
                        Where.FindGitInstallation(_customPath, KnownGitDistribution.GitForWindows32v1, out installation))
                    {
                        Trace.Write("   Git found: " + installation.Path);

                        // track known Git installations
                        installations = new List <GitInstallation>();
                        installations.Add(installation);
                    }
                }
                // since no custom installation path was supplied, use default logic
                else
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Looking for Git installation(s)...");

                    if (Where.FindGitInstallations(out installations))
                    {
                        foreach (var installation in installations)
                        {
                            Console.Out.WriteLine("  {0}", installation.Path);
                        }
                    }
                }

                if (installations == null)
                {
                    Console.Out.WriteLine();
                    Console.Error.WriteLine("Fatal: Git was not detected, unable to continue. U_U");
                    Pause();

                    Result = ResultValue.GitNotFound;
                    return;
                }

                List <string> copiedFiles;
                foreach (var installation in installations)
                {
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Deploying from '{0}' to '{1}'.", Program.Location, installation.Path);

                    if (CopyFiles(Program.Location, installation.Libexec, out copiedFiles))
                    {
                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) copied", copiedFiles.Count);
                    }
                    else if (_isForced)
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                    }
                    else
                    {
                        Console.Error.WriteLine("  deployment failed. U_U");
                        Pause();

                        Result = ResultValue.DeploymentFailed;
                        return;
                    }
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine("Deploying from '{0}' to '{1}'.", Program.Location, UserBinPath);

                if (!Directory.Exists(UserBinPath))
                {
                    Directory.CreateDirectory(UserBinPath);
                }

                if (CopyFiles(Program.Location, UserBinPath, out copiedFiles))
                {
                    foreach (var file in copiedFiles)
                    {
                        Console.Out.WriteLine("  {0}", file);
                    }

                    Console.Out.WriteLine("        {0} file(s) copied", copiedFiles.Count);
                }
                else if (_isForced)
                {
                    Console.Error.WriteLine("  deployment failed. U_U");
                }
                else
                {
                    Console.Error.WriteLine("  deployment failed. U_U");
                    Pause();

                    Result = ResultValue.DeploymentFailed;
                    return;
                }

                if (CygwinPath != null && Directory.Exists(CygwinPath))
                {
                    if (CopyFiles(Program.Location, UserBinPath, out copiedFiles))
                    {
                        foreach (var file in copiedFiles)
                        {
                            Console.Out.WriteLine("  {0}", file);
                        }

                        Console.Out.WriteLine("        {0} file(s) copied", copiedFiles.Count);
                    }
                }

                Configuration.Type types = Configuration.Type.Global;

                Configuration.Type updateTypes;
                if (SetGitConfig(installations, GitConfigAction.Set, types, out updateTypes))
                {
                    if ((updateTypes & Configuration.Type.Global) == Configuration.Type.Global)
                    {
                        Console.Out.WriteLine("Updated your ~/.gitconfig [git config --global]");
                    }
                    else
                    {
                        Console.Out.WriteLine();
                        Console.Error.WriteLine("Fatal: Unable to update your ~/.gitconfig correctly.");

                        Result = ResultValue.GitConfigGlobalFailed;
                        return;
                    }
                }

                // all necessary content has been deployed to the system
                Result = ResultValue.Success;

                Console.Out.WriteLine();
                Console.Out.WriteLine("Success! {0} was deployed! ^_^", Program.Title);
                Pause();
            }
            finally
            {
                SetOutput(true, true);
            }
        }
        private void RemoveElevated()
        {
            Trace.WriteLine("Installer::RemoveElevated");

            if (_isPassive)
            {
                this.Result = ResultValue.Unprivileged;
            }
            else
            {
                /* cannot uninstall while not elevated (need access to %PROGRAMFILES%), re-launch 
                   self as an elevated process with identical arguments. */

                // build arguments
                var arguments = new System.Text.StringBuilder("remove");
                if (_isPassive)
                {
                    arguments.Append(" ")
                             .Append(ParamPassiveKey);
                }
                if (_isForced)
                {
                    arguments.Append(" ")
                             .Append(ParamForceKey);
                }
                if (!String.IsNullOrEmpty(_customPath))
                {
                    arguments.Append(" ")
                             .Append(ParamForceKey)
                             .Append(" \"")
                             .Append(_customPath)
                             .Append("\"");
                }

                // build process start options
                var options = new ProcessStartInfo()
                {
                    FileName = "cmd",
                    Arguments = String.Format("/c \"{0}\" {1}", Program.ExecutablePath, arguments.ToString()),
                    UseShellExecute = true, // shellexecute for verb usage
                    Verb = "runas", // used to invoke elevation
                    WorkingDirectory = Program.Location,
                };

                Trace.WriteLine("   cmd " + options.Verb + " " + options.FileName + " " + options.Arguments);

                try
                {
                    // create the process
                    var elevated = Process.Start(options);

                    // wait for the process to complete
                    elevated.WaitForExit();

                    Trace.WriteLine("   process exited with " + elevated.ExitCode + ".");

                    // exit with the elevated process' exit code
                    this.ExitCode = elevated.ExitCode;
                }
                catch (Exception exception)
                {
                    Trace.WriteLine("   process failed with " + exception.Message);
                    this.Result = ResultValue.Unprivileged;
                }
            }
        }
        private void DeployElevated()
        {
            Trace.WriteLine("Installer::DeployElevated");

            if (_isPassive)
            {
                this.Result = ResultValue.Unprivileged;
            }
            else
            {
                /* cannot install while not elevated (need access to %PROGRAMFILES%), re-launch
                 * self as an elevated process with identical arguments. */

                // build arguments
                var arguments = new System.Text.StringBuilder("install");
                if (_isPassive)
                {
                    arguments.Append(" ")
                    .Append(ParamPassiveKey);
                }
                if (_isForced)
                {
                    arguments.Append(" ")
                    .Append(ParamForceKey);
                }
                if (!String.IsNullOrEmpty(_customPath))
                {
                    arguments.Append(" ")
                    .Append(ParamForceKey)
                    .Append(" \"")
                    .Append(_customPath)
                    .Append("\"");
                }

                // build process start options
                var options = new ProcessStartInfo()
                {
                    FileName         = "cmd",
                    Arguments        = String.Format("/c \"{0}\" {1}", Program.ExecutablePath, arguments.ToString()),
                    UseShellExecute  = true,    // shellexecute for verb usage
                    Verb             = "runas", // used to invoke elevation
                    WorkingDirectory = Program.Location,
                };

                Trace.WriteLine("   cmd " + options.Verb + " " + options.FileName + " " + options.Arguments);

                try
                {
                    // create the process
                    var elevated = Process.Start(options);

                    // wait for the process to complete
                    elevated.WaitForExit();

                    Trace.WriteLine("   process exited with " + elevated.ExitCode + ".");

                    // exit with the elevated process' exit code
                    this.ExitCode = elevated.ExitCode;
                }
                catch (Exception exception)
                {
                    Trace.WriteLine("   process failed with " + exception.Message);
                    this.Result = ResultValue.Unprivileged;
                }
            }
        }
Пример #30
0
 internal List<BoundBreakpoint> BindAddresses(ResultValue bkpt)
 {
     List<BoundBreakpoint> resultList = new List<BoundBreakpoint>();
     if (bkpt == null)
     {
         return resultList;
     }
     BoundBreakpoint bbp = null;
     if (bkpt is ValueListValue)
     {
         var list = (ValueListValue)bkpt;
         for (int i = 1; i < list.Content.Length; ++i)
         {
             bbp = GetBoundBreakpoint(list.Content[i] as TupleValue);
             if (bbp != null)
                 resultList.Add(bbp);
         }
     }
     else
     {
         _breakState = StringToBreakpointState(bkpt.TryFindString("addr"));
         bbp = GetBoundBreakpoint(bkpt as TupleValue);
         if (bbp != null)
             resultList.Add(bbp);
     }
     return resultList;
 }
Пример #31
0
 public bool Contains(ResultValue eFlag)
 {
     return(0 == (m_nRsltFlags & (int)eFlag));
 }