private void UpdateFormData()
 {
     if (_model != null && _model.Data != null && _model.Data.Location != null && cbLocation.Items.Contains(_model.Data.Location))
     {
         cbLocation.SelectedItem = _model.Data.Location;
     }
     if (_model.Data.ArrivalTime?.Time != null)
     {
         _model.Data.ArrivalTime.Time.SetTime(tbArrivalHour, tbArrivalMinute, cbArrivalHalfOfDay, _model.InputMode);
     }
     else
     {
         TimeHelpers.ClearTimeBoxes(tbArrivalHour, tbArrivalMinute, cbArrivalHalfOfDay);
     }
     if (_model.Data.DepartureTime?.Time != null)
     {
         _model.Data.DepartureTime?.Time.SetTime(tbDepartureHour, tbDepartureMinute, cbDepartureHalfOfDay, _model.InputMode);
     }
     else
     {
         TimeHelpers.ClearTimeBoxes(tbDepartureHour, tbDepartureMinute, cbDepartureHalfOfDay);
     }
     ckPassingTime.Checked = _model.Data.Pass;
     tbPath.Text           = _model.Data.Path;
     tbPlatform.Text       = _model.Data.Platform;
     tbLine.Text           = _model.Data.Line;
 }
    public async Task <TxDetails> LoadTxDetails(string txid, NeblioAccount account)
    {
        var tinfo = await NeblioTransactionHelpers.GetTransactionInfo(txid);

        string sender = await NeblioTransactionHelpers.GetTransactionSender(txid, tinfo);

        bool fromAnotherAccount = true;
        bool fromSubAccount     = true;

        if (sender == account.Address)
        {
            sender             = "Main Account";
            fromAnotherAccount = false;
            fromSubAccount     = false;
        }
        else if (account.SubAccounts.TryGetValue(sender, out var sacc))
        {
            if (!string.IsNullOrEmpty(sacc.Name))
            {
                sender = sacc.Name;
            }
            else
            {
                sender = sacc.BookmarkFromAccount.Name;
            }
            fromAnotherAccount = false;
            fromSubAccount     = true;
        }

        string rec = await NeblioTransactionHelpers.GetTransactionReceiver(txid, tinfo);

        string receiver = string.Empty;
        var    recbkm   = account.IsInTheBookmarks(rec);

        if (rec == account.Address)
        {
            receiver = "Main Account";
        }
        else if (recbkm.Item1)
        {
            receiver = recbkm.Item2.Name;
        }

        if (string.IsNullOrEmpty(receiver))
        {
            receiver = NeblioTransactionHelpers.ShortenAddress(rec);
        }

        var time = TimeHelpers.UnixTimestampToDateTime((double)tinfo.Blocktime);

        return(new TxDetails()
        {
            FromAnotherAccount = fromAnotherAccount,
            FromSubAccount = fromSubAccount,
            Info = tinfo,
            Receiver = receiver,
            Sender = sender,
            Time = time,
        });
    }
Пример #3
0
 private void UpdateViewFromModel()
 {
     if (Model?.Data == null)
     {
         return;
     }
     _inViewUpdate   = true;
     lblBoxName.Text = Model.Data.Signalbox?.EditorDisplayName ?? Resources.SignalboxHoursEditForm_Signalbox_Name_Unknown;
     _model.InputMode.SetControlsVisibleIn12HourMode(new[] { cbStartHalfOfDay, cbEndHalfOfDay });
     if (_model.Data.StartTime != null)
     {
         _model.Data.StartTime.SetTime(tbStartHours, tbStartMinutes, cbStartHalfOfDay, _model.InputMode);
     }
     else
     {
         TimeHelpers.ClearTimeBoxes(tbStartMinutes, tbStartMinutes, cbStartHalfOfDay);
     }
     if (_model.Data.EndTime != null)
     {
         _model.Data.EndTime.SetTime(tbEndHours, tbEndMinutes, cbEndHalfOfDay, _model.InputMode);
     }
     else
     {
         TimeHelpers.ClearTimeBoxes(tbEndMinutes, tbEndMinutes, cbEndHalfOfDay);
     }
     ckTokenWarning.Checked = _model.Data.TokenBalanceWarning;
     _inViewUpdate          = false;
 }
Пример #4
0
        private void OnShare(object sender, EventArgs e)
        {
            var shareArgs = (ShareEventArgs)e;
            var miner     = shareArgs.Miner;

            if (miner == null)
            {
                return;
            }

            int now = TimeHelpers.NowInUnixTime();

            if (miner.VardiffBuffer == null)
            {
                miner.LastVardiffRetarget  = now - (Config.RetargetTime / 2);
                miner.LastVardiffTimestamp = now;
                miner.VardiffBuffer        = new RingBuffer(_bufferSize);
                return;
            }

            var sinceLast = now - miner.LastVardiffTimestamp; // how many seconds elapsed since last share?

            miner.VardiffBuffer.Append(sinceLast);            // append it to vardiff buffer.
            miner.LastVardiffTimestamp = now;

            if (now - miner.LastVardiffRetarget < Config.RetargetTime && miner.VardiffBuffer.Size > 0) // check if we need a re-target.
            {
                return;
            }

            miner.LastVardiffRetarget = now;
            var average   = miner.VardiffBuffer.Average;
            var deltaDiff = Config.TargetTime / average;

            if (average > _tMax && miner.Difficulty > Config.MinimumDifficulty)
            {
                if (deltaDiff * miner.Difficulty < Config.MinimumDifficulty)
                {
                    deltaDiff = Config.MinimumDifficulty / miner.Difficulty;
                }
            }
            else if (average < _tMin)
            {
                if (deltaDiff * miner.Difficulty > Config.MaximumDifficulty)
                {
                    deltaDiff = Config.MaximumDifficulty / miner.Difficulty;
                }
            }
            else
            {
                return;
            }

            var newDifficulty = miner.Difficulty * deltaDiff; // calculate the new difficulty.

            miner.SetDifficulty(newDifficulty);               // set the new difficulty and send it.
            _logger.Debug("Difficulty updated to {0} for miner: {1:l}", miner.Difficulty, miner.Username);

            miner.VardiffBuffer.Clear();
        }
Пример #5
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string @string = value as string;

            if (@string != null)
            {
                Duration duration;
                if (TimeHelpers.GetDurationPatterns(culture).TryParseAny(@string.Trim(), out duration))
                {
                    return(duration);
                }

                TimeSpan timeSpan;
                if (TimeSpan.TryParse(@string, out timeSpan))
                {
                    return(Duration.FromTimeSpan(timeSpan));
                }

                throw new NotSupportedException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resources.DurationConverter_ConvertFrom_CannotParse, @string));
            }
            if (value is TimeSpan)
            {
                TimeSpan timeSpan = (TimeSpan)value;
                return(Duration.FromTimeSpan(timeSpan));
            }

            return(base.ConvertFrom(context, culture, value));
        }
Пример #6
0
        public void AddShare(IShare share)
        {
            try
            {
                if (!IsEnabled || !_redisProvider.IsConnected)
                {
                    return;
                }

                //_client.StartPipe(); // batch the commands.

                // add the share to round
                var currentKey = string.Format("{0}:shares:round:current", _coin);
                _redisProvider.Client.HIncrByFloat(currentKey, share.Miner.Username, share.Difficulty);

                // increment shares stats.
                var statsKey = string.Format("{0}:stats", _coin);
                _redisProvider.Client.HIncrBy(statsKey, share.IsValid ? "validShares" : "invalidShares", 1);

                // add to hashrate
                if (share.IsValid)
                {
                    var hashrateKey = string.Format("{0}:hashrate", _coin);
                    var entry       = string.Format("{0}:{1}", share.Difficulty, share.Miner.Username);
                    _redisProvider.Client.ZAdd(hashrateKey, Tuple.Create(TimeHelpers.NowInUnixTime(), entry));
                }

                //_client.EndPipe(); // execute the batch commands.
            }
            catch (Exception e)
            {
                _logger.Error("An exception occured while comitting share: {0:l}", e.Message);
            }
        }
        public void GetTimeDayReturnsCorrectUtcTime()
        {
            var dateString = "2017-08-09T10:00:00Z"; // Weds, Aug 9th, 2017 10 AM UTC
            var result     = TimeHelpers.GetUtcTimeDayFromString(dateString);

            Assert.Equal(result.DayOfWeek, IsoDayOfWeek.Wednesday);
            Assert.Equal(result.TimeOfDay, 1000);
        }
 /// <summary>
 /// Default constructor.
 /// </summary>
 public TrainEditForm()
 {
     InitializeComponent();
     _inViewUpdate = true;
     cbLinePattern.Items.AddRange(HumanReadableEnumFactory.GetDashStyles());
     TimeHelpers.PopulateHalfOfDayComboBoxes(cbToWorkHalfOfDay, cbLocoToWorkHalfOfDay);
     _inViewUpdate = false;
 }
Пример #9
0
        /// <summary>
        /// Creates a new instance of generation transaction.
        /// </summary>
        /// <param name="extraNonce">The extra nonce.</param>
        /// <param name="daemonClient">The daemon client.</param>
        /// <param name="blockTemplate">The block template.</param>
        /// <param name="poolConfig">The associated pool's configuration</param>
        /// <remarks>
        /// Reference implementations:
        /// https://github.com/zone117x/node-stratum-pool/blob/b24151729d77e0439e092fe3a1cdbba71ca5d12e/lib/transactions.js
        /// https://github.com/Crypto-Expert/stratum-mining/blob/master/lib/coinbasetx.py
        /// </remarks>
        public GenerationTransaction(IExtraNonce extraNonce, IDaemonClient daemonClient, IBlockTemplate blockTemplate, IPoolConfig poolConfig)
        {
            // TODO: we need a whole refactoring here.
            // we should use DI and it shouldn't really require daemonClient connection to function.

            BlockTemplate = blockTemplate;
            ExtraNonce    = extraNonce;
            PoolConfig    = poolConfig;

            Version   = 1;//change version for bitcoin like
            TxMessage = Serializers.SerializeString(poolConfig.Meta.TxMessage);
            LockTime  = 0;



            // transaction inputs
            Inputs = new List <TxIn>
            {
                new TxIn
                {
                    PreviousOutput = new OutPoint
                    {
                        Hash  = Hash.ZeroHash,
                        Index = (UInt32)Math.Pow(2, 32) - 1
                    },
                    Sequence        = (UInt32)Math.Pow(2, 32) - 1,
                    SignatureScript =
                        new SignatureScript(
                            blockTemplate.Height,
                            //blockTemplate.CoinBaseAux.Flags,
                            "",
                            TimeHelpers.NowInUnixTimestamp(),
                            (byte)extraNonce.ExtraNoncePlaceholder.Length,
                            "")
                }
            };

            // transaction outputs
            Outputs = new Outputs(daemonClient, poolConfig.Coin);


            double blockReward = BlockTemplate.Coinbasevalue; // the amount rewarded by the block.



            // generate output transactions for recipients (set in config).

            /*foreach (var pair in poolConfig.Rewards)
             * {
             *  var amount = blockReward * pair.Value / 100; // calculate the amount he recieves based on the percent of his shares.
             *  blockReward -= amount;
             *
             *  Outputs.AddRecipient(pair.Key, amount);
             * }*/

            // send the remaining coins to pool's central wallet.
            Outputs.AddPoolWallet(poolConfig.Wallet.Adress, blockReward);
        }
Пример #10
0
        /// <summary>
        /// Creates a new instance of generation transaction.
        /// </summary>
        /// <param name="extraNonce">The extra nonce.</param>
        /// <param name="daemonClient">The daemon client.</param>
        /// <param name="blockTemplate">The block template.</param>
        /// <param name="poolConfig">The associated pool's configuration</param>
        /// <remarks>
        /// Reference implementations:
        /// https://github.com/zone117x/node-stratum-pool/blob/b24151729d77e0439e092fe3a1cdbba71ca5d12e/lib/transactions.js
        /// https://github.com/Crypto-Expert/stratum-mining/blob/master/lib/coinbasetx.py
        /// </remarks>
        public GenerationTransaction(IExtraNonce extraNonce, IDaemonClient daemonClient,
                                     IBlockTemplate blockTemplate, IPoolConfig poolConfig)
        {
            // TODO: we need a whole refactoring here.
            // we should use DI and it shouldn't really require daemonClient connection to function.

            BlockTemplate = blockTemplate;
            ExtraNonce    = extraNonce;
            PoolConfig    = poolConfig;

            Version   = blockTemplate.Version;
            TxMessage = Serializers.SerializeString(poolConfig.Meta.TxMessage);
            LockTime  = 0;

            // transaction inputs
            Inputs = new List <TxIn>
            {
                new TxIn
                {
                    PreviousOutput = new OutPoint
                    {
                        Hash  = Hash.ZeroHash,
                        Index = (UInt32)Math.Pow(2, 32) - 1
                    },
                    Sequence        = 0x0,
                    SignatureScript =
                        new SignatureScript(
                            blockTemplate.Height,
                            blockTemplate.CoinBaseAux.Flags,
                            TimeHelpers.NowInUnixTimestamp(),
                            (byte)extraNonce.ExtraNoncePlaceholder.Length,
                            "/CoiniumServ/")
                }
            };

            // transaction outputs
            Outputs = new Outputs(daemonClient, poolConfig.Coin);
            double blockReward = BlockTemplate.Coinbasevalue; // the amount rewarded by the block.

            // generate output transactions for recipients (set in config).
            foreach (var pair in poolConfig.Rewards)
            {
                var amount = blockReward * pair.Value / 100; // calculate the amount the recieves based on the percent of his shares.
                blockReward -= amount;
                Outputs.AddRecipient(pair.Key, amount);
            }

            // send the remaining coins to pool's central wallet.
            Outputs.AddPoolWallet(poolConfig.Wallet.Adress, blockReward);

            // Final output is witness
            //https://github.com/slush0/stratum-mining/pull/16/files?diff=unified
            if (!string.IsNullOrEmpty(BlockTemplate.Default_witness_commitment))
            {
                Outputs.AddWitnessOutput(BlockTemplate.Default_witness_commitment.HexToByteArray());
            }
        }
Пример #11
0
 private void StoreEndTime()
 {
     if (_model?.Data == null)
     {
         return;
     }
     TimeHelpers.SetTimeProperty(_model.Data, _model.Data.GetType().GetProperty("EndTime"), tbEndHours, tbEndMinutes,
                                 _model.InputMode == ClockType.TwelveHourClock ? cbEndHalfOfDay : null, _model.Data.EndTime?.Seconds ?? 0);
 }
 private void StoreDepartureTime()
 {
     if (_model.Data == null)
     {
         return;
     }
     TimeHelpers.SetTimeProperty(_model.Data.DepartureTime, _model.Data.DepartureTime.GetType().GetProperty("Time"), tbDepartureHour, tbDepartureMinute,
                                 _model.InputMode == ClockType.TwelveHourClock ? cbDepartureHalfOfDay : null, _model.Data.DepartureTime?.Time != null ? _model.Data.DepartureTime.Time.Seconds : 0);
 }
Пример #13
0
        public byte[] Hash(byte[] input)
        {
            var now = (UInt64)TimeHelpers.NowInUnixTimestamp();

            var index   = _timeTable.OrderBy(x => x.Key).First(x => x.Value < now).Key;
            var nFactor = (int)(Math.Log(index) / Math.Log(2));
            var n       = 1 << nFactor;

            return(SCrypt.ComputeDerivedKey(input, input, n, _r, _p, null, 32));
        }
Пример #14
0
        private IExpenseModel expense_dtoToModel(ExpenseDTO dto)
        {
            ExpenseModel model = new ExpenseModel();

            model.ExpenseId     = dto.ExpenseId;
            model.ExpenseTypeId = dto.ExpenseTypeId;
            model.Cost          = dto.Cost;
            model.Date          = TimeHelpers.dateTimeToString(dto.Date);
            model.UserId        = dto.UserId;
            return(model);
        }
Пример #15
0
        public void ToFormatedStringTest()
        {
            TimeSpan time     = new TimeSpan(10, 5, 39);
            string   expected = "10:05:39";

            string actual;

            actual = TimeHelpers.ToFormatedString(time);

            Assert.AreEqual(expected, actual);
        }
Пример #16
0
        public void FromFormatedString99Test()
        {
            string   formatedString = "12:99";
            TimeSpan expected       = new TimeSpan(0, 13, 39);

            TimeSpan actual;

            actual = TimeHelpers.FromFormatedString(formatedString);

            Assert.AreEqual(expected, actual);
        }
Пример #17
0
        private void ReadHashrate()
        {
            // read hashrate stats.
            var windowTime = TimeHelpers.NowInUnixTime() - _statisticsConfig.HashrateWindow;

            _storage.DeleteExpiredHashrateData(windowTime);
            var hashrates = _storage.GetHashrateData(windowTime);

            double total = hashrates.Sum(pair => pair.Value);

            Hashrate = Convert.ToUInt64(_shareMultiplier * total / _statisticsConfig.HashrateWindow);
        }
Пример #18
0
        public void TimeHelpersClass_ClearTimeBoxesMethod_ThrowsArgumentNullException_IfThirdParameterIsNull()
        {
            ComboBox testParam2 = null;

            using (TextBox testParam1 = new TextBox())
                using (TextBox testParam0 = new TextBox())
                {
                    TimeHelpers.ClearTimeBoxes(testParam0, testParam1, testParam2);

                    Assert.Fail();
                }
        }
 private void createBtn_Click(object sender, EventArgs e)
 {
     try
     {
         ExpenseAddViewModel vm = new ExpenseAddViewModel();
         vm.ExpenseTypeId = (expenseTypeCombobox.SelectedItem as ExpenseTypeDTO).ExpenseTypeId;
         vm.Date          = TimeHelpers.dateTimeToString(datePicker.Value);
         vm.Cost          = (double)costPicker.Value;
         EventHelpers.RaiseEvent(this, ExpenseAddConfirmEventRaised, vm);
         Close();
     }
     catch (Exception) { }
 }
Пример #20
0
        private bool BanExpired(IPAddress ip)
        {
            var banTime = _bannedIps[ip];

            var elapsedTime = TimeHelpers.NowInUnixTimestamp() - banTime; // elapsed time since his ban.
            var timeLeft    = Config.Duration - elapsedTime;              // time left for his ban

            if (timeLeft > 0)                                             // if he has still remaining time
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string @string = value as string;

            if (@string != null)
            {
                LocalDateTime localDateTime;
                if (TimeHelpers.GetLocalDateTimePatterns(culture).TryParseAny(@string.Trim(), out localDateTime))
                {
                    return(localDateTime);
                }

                DateTime dateTime;
                if (DateTime.TryParse(@string, out dateTime))
                {
                    return(LocalDateTime.FromDateTime(dateTime));
                }

                throw new NotSupportedException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resources.LocalDateTimeConverter_ConvertFrom_CannotParse, @string));
            }
            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;
                return(LocalDateTime.FromDateTime(dateTime));
            }
            if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                return(LocalDateTime.FromDateTime(dateTimeOffset.LocalDateTime));
            }
            if (value is OffsetDateTime)
            {
                OffsetDateTime offsetDateTime = (OffsetDateTime)value;
                return(offsetDateTime.LocalDateTime);
            }
            if (value is Instant)
            {
                Instant instant = (Instant)value;
                return(instant.InUtc().LocalDateTime);
            }
            if (value is ZonedDateTime)
            {
                ZonedDateTime zonedDateTime = (ZonedDateTime)value;
                return(zonedDateTime.LocalDateTime);
            }

            return(base.ConvertFrom(context, culture, value));
        }
        private void StoreLocoToWorkTime()
        {
            if (_model.Data == null)
            {
                return;
            }
            if (_model.Data.LocoToWork == null)
            {
                _model.Data.LocoToWork = new ToWork();
            }

            TimeHelpers.SetTimeProperty(_model.Data.LocoToWork, _model.Data.LocoToWork.GetType().GetProperty(nameof(_model.Data.LocoToWork.AtTime)), tbLocoToWorkHour, tbLocoToWorkMinute,
                                        _model.DocumentOptions.ClockType == ClockType.TwelveHourClock ? cbLocoToWorkHalfOfDay : null, _model.Data.LocoToWork.AtTime != null ? _model.Data.LocoToWork.AtTime.Seconds : 0);
        }
Пример #23
0
        public void TimeHelpersClass_SetTimePropertyMethod_ThrowsArgumentNullException_IfFourthParameterIsNull()
        {
            object       testParam0 = new MockData();
            PropertyInfo testParam1 = testParam0.GetType().GetProperty("MockTimeProperty");
            TextBox      testParam3 = null;
            int          testParam5 = _rnd.Next();

            using (TextBox testParam2 = new TextBox())
                using (ComboBox testParam4 = new ComboBox())
                {
                    TimeHelpers.SetTimeProperty(testParam0, testParam1, testParam2, testParam3, testParam4, testParam5);

                    Assert.Fail();
                }
        }
Пример #24
0
        private static long Parse(string startTimeStr, string dayString = "")
        {
            if (startTimeStr.Length == 0 | dayString.Length == 0)
            {
                var now = DateTime.Now;
                return(TimeHelpers.ConstructUnixTime((int)now.DayOfWeek - 1, now.Hour, now.Minute));
            }

            int d = Int32.Parse(dayString);
            var x = startTimeStr.Split(':');
            int h = Int32.Parse(x[0]);
            int m = Int32.Parse(x[1]);

            return(TimeHelpers.ConstructUnixTime(d, h, m));
        }
Пример #25
0
        private void CalculateHashrate()
        {
            // read hashrate stats.
            var windowTime = TimeHelpers.NowInUnixTimestamp() - _configManager.StatisticsConfig.HashrateWindow;

            _storage.DeleteExpiredHashrateData(windowTime);
            var hashrates = _storage.GetHashrateData(windowTime);

            double total = hashrates.Sum(pair => pair.Value);

            Hashrate = _shareMultiplier * total / _configManager.StatisticsConfig.HashrateWindow;

            // TODO: fix pool hashrate calculation
            _logger.Debug("Pool hashrate window: {0} total: {1} hashrate: {2:0.000000000}", _configManager.StatisticsConfig.HashrateWindow, total, Hashrate);
        }
Пример #26
0
        public string Get([FromQuery] Guid?groupId, [FromQuery] string begin, [FromQuery] string end)
        {
            var beginTime = TimeHelpers.GetUtcTimeDayFromString(begin);
            var endTime   = TimeHelpers.GetUtcTimeDayFromString(end);

            if (beginTime == null || endTime == null)
            {
                throw new ArgumentException($"Rate request time range could not be parsed from {groupId} {begin} {end}");
            }

            // Temporary hardcoded group id for sample project
            groupId = groupId ?? Guid.Empty;

            var rate = ProviderService.GetRateForRange(groupId.Value, beginTime, endTime);

            return(rate.HasValue ? rate.Value.ToString() : NoRateResponse);
        }
Пример #27
0
        private void Ban(IMiner miner)
        {
            // TODO: add vanilla miners to banlist too.
            if (miner is IGetworkMiner) // as vanilla miners doesn't use persistent connections, we don't need to disconect him
            {
                return;                 // but just blacklist his ip.
            }
            var client = (IClient)miner;
            var ip     = client.Connection.RemoteEndPoint.Address;

            if (!_bannedIps.ContainsKey(ip))
            {
                _bannedIps.Add(ip, TimeHelpers.NowInUnixTimestamp());
            }

            client.Connection.Disconnect();
        }
Пример #28
0
        public async Task <IActionResult> Get(int pageIndex = 1, int pageSize = 10)
        {
            PaginatedList <CurrentTimeQuery> pastTimes;

            await using (var db = new ClockworkContext())
            {
                pastTimes = await PaginatedList <CurrentTimeQuery> .CreateAsync(db.CurrentTimeQueries.AsNoTracking(), pageIndex, pageSize);
            }

            var returnPastTimes = pastTimes.Select(pt => new
            {
                Id       = pt.CurrentTimeQueryId,
                Time     = TimeHelpers.ConvertTimeToTimeZone(pt.Time, pt.TimeZone).ToString("g"),
                TimeZone = pt.TimeZone
            });

            return(Ok(new { pastTimes = returnPastTimes, pageIndex = pageIndex, totalPages = pastTimes.TotalPages }));
        }
Пример #29
0
        public void TimeHelpersClass_ClearTimeBoxesMethod_ThrowsArgumentNullExceptionWithCorrectParamNameProperty_IfSecondParameterIsNull()
        {
            TextBox testParam1 = null;

            using (TextBox testParam0 = new TextBox())
                using (ComboBox testParam2 = new ComboBox())
                {
                    try
                    {
                        TimeHelpers.ClearTimeBoxes(testParam0, testParam1, testParam2);
                        Assert.Fail();
                    }
                    catch (ArgumentNullException ex)
                    {
                        Assert.AreEqual("tbMinutes", ex.ParamName);
                    }
                }
        }
Пример #30
0
        private void OnRefresh()
        {
            try
            {
                var jobMethod = string.Format(JobUrlFormat, Id);
                var job       = _restClient.MakeRequest <Job>(BaseUrl, jobMethod, null, null);

                LastChecked         = DateTime.Now;
                CurrentBuild        = job.LastBuild.ToString();
                LastSuccessfulBuild = job.LastSuccessfulBuild == null ? string.Empty : job.LastSuccessfulBuild.ToString();
                LastCompletedBuild  = job.LastCompletedBuild.Number.ToString();

                if (job.LastSuccessfulBuild == null)
                {
                    if (job.LastCompletedBuild != null)
                    {
                        Pass = false;
                    }
                    else
                    {
                        Pass = null;
                    }
                }
                else
                {
                    Pass = job.LastCompletedBuild.Number == job.LastSuccessfulBuild.Number || WasLastActualBuildSuccess(job);
                }

                InProgress = job.LastBuild.Number != job.LastCompletedBuild.Number;

                var detailsMethod = string.Format(DetailsUrlFormat, Id, CurrentBuild);
                var details       = _restClient.MakeRequest <BuildDetails>(BaseUrl, detailsMethod, null, null);

                var durationTicks = (InProgress ? details.EstimatedDuration : details.Duration) * 10000;
                Duration  = new TimeSpan(durationTicks);
                TimeBuilt = TimeHelpers.TimeFromEpochTimestamp(details.Timestamp);
            }
            catch (Exception ex)
            {
                Log.TraceErr("JenkinsBuildJobViewModel.OnRefresh: Error retrieving results for '{0}'. {1}", Id, ex.ToString());
                LastChecked = null;
                Pass        = null;
            }
        }