System.Convert.ToInt64(string, int)

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

791 Examples 7

19 View Source File : ResponseExtensions.cs
License : Apache License 2.0
Project Creator : 0xFireball

public static Response FromPartialStream(this IResponseFormatter response, Request request, Stream stream,
            string contentType)
        {
            // Store the len
            var len = stream.Length;
            // Create the response now
            var res = response.FromStream(stream, contentType)
                .WithHeader("Connection", "Keep-alive")
                .WithHeader("Accept-ranges", "Bytes");
            // Use the partial status code
            res.StatusCode = HttpStatusCode.PartialContent;
            long startPos = 0;
            foreach (var s in request.Headers["Range"])
            {
                var start = s.Split('=')[1];
                var m = Regex.Match(start, @"(\d+)-(\d+)?");
                start = m.Groups[1].Value;
                var end = len - 1;
                if (!string.IsNullOrWhiteSpace(m.Groups[2]?.Value))
                {
                    end = Convert.ToInt64(m.Groups[2].Value);
                }

                startPos = Convert.ToInt64(start);
                var length = len - startPos;
                res.WithHeader("Content-range", "Bytes " + start + "-" + end + "/" + len);
                res.WithHeader("Content-length", length.ToString(CultureInfo.InvariantCulture));
            }
            stream.Seek(startPos, SeekOrigin.Begin);
            return res;
        }

19 View Source File : Send_0x0319.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x0A, 0x0C, 0x08 });
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvQQ)));
            data.Write((byte) 0x10);
            data.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data.Write(new byte[] { 0x20, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

19 View Source File : Send_0x0360.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x03, 0x08, 0x03, 0x22, 0x46, 0x08 });
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvGroupQQ)));
            data.Write((byte) 0x10);
            data.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data.Write(new byte[] { 0x20, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

19 View Source File : Send_0x03FC.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            var data_0A = new BinaryWriter(new MemoryStream());
            data_0A.Write((byte) 0x08);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(User.QQ)));
            data_0A.Write((byte) 0x10);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvQQ)));
            data_0A.Write((byte) 0x18);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(_msgSequence))); //消息包序
            data_0A.Write((byte) 0x28);
            data_0A.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data_0A.Write(new byte[] { 0x30 });
            data_0A.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageId).Replace(" ", ""), 16)))); //消息Id
            data_0A.Write(new byte[] { 0x38, 0x01, 0x40, 0x00, 0x48, 0x00 });
            data.Write((byte) 0x0A);
            data.Write((byte) data_0A.BaseStream.Length); //length
            data.Write(data_0A.BaseStream.ToBytesArray());
            data.Write(new byte[] { 0x10, 0x01, 0x18, 0x01, 0x20, 0x00, 0x2a, 0x04, 0x08, 0x00, 0x10, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static string GetQQNum(string six)
        {
            return Convert.ToInt64(six.Replace(" ", ""), 16).ToString();
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static string PB_toLength(long d)
        {
            var binary = Convert.ToString(d, 2); //转换length为二级制
            var temp = "";
            while (!string.IsNullOrEmpty(binary))
            {
                var binary1 = "0000000" + binary;
                temp = temp + "1" + binary1.Substring(binary1.Length - 7, 7);
                if (binary.Length >= 7)
                {
                    binary = binary.Substring(0, binary.Length - 7);
                }
                else
                {
                    //temp = temp + "0" + binary;
                    break;
                }
            }

            var temp1 = temp.Substring(temp.Length - 7, 7);
            temp = temp.Substring(0, temp.Length - 8) + "0" + temp1;
            return LongToHexString(Convert.ToInt64(temp, 2));
        }

19 View Source File : DateTimeConverter.cs
License : MIT License
Project Creator : 4egod

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return Convert.ToInt64(reader.Value).FromTwitterTimestamp();
        }

19 View Source File : Send_0x0391.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x0D });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x0A, 0x12, 0x08 });
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(GroupQQ)));
            data.Write(new byte[] { 0x12, 0x0a, 0x38, 0x00, 0x40, 0x00, 0x4a, 0x04, 0x08, 0x00, 0x10, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x09 });

            var data12 = new BinaryWriter(new MemoryStream());
            data12.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageIndex).Replace(" ", ""), 16))));
            data12.Write(new byte[] { 0x88, 0x01, 0x04, 0x98, 0x01, 0x00 });

            BodyWriter.Write((byte) data12.BaseStream.Length);
            BodyWriter.Write(data12.BaseStream.ToBytesArray());

            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

19 View Source File : Send_0x03F7.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            var pbGroupId = Util.HexStringToByteArray(Util.PB_toLength(_groupId));
            var pbMessageId =
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(_messageId).Replace(" ", ""), 16)));
            var pbMessageIndex =
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(_messageIndex).Replace(" ", ""), 16)));
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x08, 0x01, 0x10, 0x00, 0x18 });
            data.Write(pbGroupId);
            data.Write(new byte[] { 0x22, 0x09, 0x08 });
            data.Write(pbMessageIndex); //消息索引
            data.Write((byte) 0x10);
            data.Write(pbMessageId); //消息Id
            var data_2A = new BinaryWriter(new MemoryStream());
            data_2A.Write(new byte[] { 0x08, 0x00 });
            var data12 = new BinaryWriter(new MemoryStream());
            data12.Write((byte) 0x08);
            data12.Write(pbMessageIndex); //消息索引
            data12.Write((byte) 0x10);
            data12.Write(new byte[] { 0x00, 0x18, 0x01, 0x20, 0x00 });
            data_2A.Write((byte) 0x12);
            data_2A.Write((byte) data12.BaseStream.Length);
            data_2A.Write(data12.BaseStream.ToBytesArray());
            data.Write((byte) 0x2a);
            data.Write((byte) data_2A.BaseStream.Length);
            data.Write(data_2A.BaseStream.ToBytesArray());
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

19 View Source File : OculusWrapVirtualRealityProvider.cs
License : MIT License
Project Creator : ab4d

public DXDevice InitializeOvrAndDXDevice(int requestedOculusSdkMinorVersion = 17)
        {
            if (_sessionPtr != IntPtr.Zero)
                throw new Exception("InitializeOvrAndDXDevice cannot be called after the sessionPtr was already set.");

            
            // Define initialization parameters with debug flag.
            var initializationParameters = new InitParams();

            // In Oculus SDK 1.8 and newer versions, it is required to specify to which version the application is build
            initializationParameters.Flags = InitFlags.RequestVersion;
            initializationParameters.RequestedMinorVersion = (uint)requestedOculusSdkMinorVersion;

            // Initialize the Oculus runtime.
            var result = _ovr.Initialize(initializationParameters);

            if (result < Result.Success)
                throw new OvrException("Failed to initialize the Oculus runtime library.", result);


            // Use the head mounted display.
            var adapterLuid = new GraphicsLuid();
            result = _ovr.Create(ref _sessionPtr, ref adapterLuid);

            if (result < Result.Success)
                throw new OvrException("Oculus Rift not detected", result);


            _hmdDesc = _ovr.GetHmdDesc(_sessionPtr);


            // Get adapter (graphics card) used by Oculus
            Adapter1 hmdAdapter;
            if (adapterLuid.Reserved != null && adapterLuid.Reserved.Length == 4)
            {
                var allSystemAdapters = DXDevice.GetAllSystemAdapters();

                long adapterUid = Convert.ToInt64(adapterLuid.Reserved); // adapterLuid.Reserved is byte array
                hmdAdapter = allSystemAdapters.FirstOrDefault(a => a.Description1.Luid == adapterUid);
            }
            else
            {
                hmdAdapter = null;
            }

            // Create DXEngine's DirectX Device with the same adapter (graphics card) that is used for Oculus Rift
            var dxDeviceConfiguration = new DXDeviceConfiguration();

            if (hmdAdapter != null)
                dxDeviceConfiguration.Adapter = hmdAdapter;

            dxDeviceConfiguration.DriverType = DriverType.Hardware;
            dxDeviceConfiguration.SupportedFeatureLevels = new FeatureLevel[] {FeatureLevel.Level_11_0};

            // Create DirectX device
            var dxDevice = new DXDevice(dxDeviceConfiguration);
            dxDevice.InitializeDevice();

            return dxDevice;
        }

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

public static bool TryParse64(string str, out long value)
        {
            value = long.MinValue;

            if (str is null)
                return false;
            
            var (numStr, @base, negate) = Configure(str);

            try
            {
                value = Convert.ToInt64(numStr, @base);
                if (negate)
                    value = -value;
                return true;
            }
            catch
            {
                return false;
            }
        }

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

private void JobServerQueueThrottling_EventReceived(object sender, ThrottlingEventArgs data)
        {
            Interlocked.Add(ref _totalThrottlingDelayInMilliseconds, Convert.ToInt64(data.Delay.TotalMilliseconds));

            if (!_throttlingReported &&
                _totalThrottlingDelayInMilliseconds > _throttlingDelayReportThreshold)
            {
                this.Warning(string.Format("The job is currently being throttled by the server. You may experience delays in console line output, job status reporting, and action log uploads."));

                _throttlingReported = true;
            }
        }

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

protected object GetValue(JToken token, AttributeTypeCode attributeType)
		{
			var value = token.ToObject<object>();

			if (value == null)
			{
				return null;
			}

			if (attributeType == AttributeTypeCode.Customer || attributeType == AttributeTypeCode.Lookup || attributeType == AttributeTypeCode.Owner)
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return enreplacedyReference;
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.LogicalName, typeof(EnreplacedyReference)));
			}

			// Option set values will be in Int64 form from the JSON deserialization -- convert those to OptionSetValues
			// for option set attributes.
			if (attributeType == AttributeTypeCode.EnreplacedyName || attributeType == AttributeTypeCode.Picklist || attributeType == AttributeTypeCode.State || attributeType == AttributeTypeCode.Status)
			{
				return new OptionSetValue(Convert.ToInt32(value));
			}

			if (attributeType == AttributeTypeCode.Memo || attributeType == AttributeTypeCode.String)
			{
				return value is string ? value : value.ToString();
			}

			if (attributeType == AttributeTypeCode.BigInt)
			{
				return Convert.ToInt64(value);
			}

			if (attributeType == AttributeTypeCode.Boolean)
			{
				return Convert.ToBoolean(value);
			}

			if (attributeType == AttributeTypeCode.DateTime)
			{
				var dateTimeValue = Convert.ToDateTime(value);

				return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
			}

			if (attributeType == AttributeTypeCode.Decimal)
			{
				return Convert.ToDecimal(value);
			}

			if (attributeType == AttributeTypeCode.Double)
			{
				return Convert.ToDouble(value);
			}

			if (attributeType == AttributeTypeCode.Integer)
			{
				return Convert.ToInt32(value);
			}

			if (attributeType == AttributeTypeCode.Money)
			{
				return new Money(Convert.ToDecimal(value));
			}

			if (attributeType == AttributeTypeCode.Uniqueidentifier)
			{
				return value is Guid ? value : new Guid(value.ToString());
			}

			return value;
		}

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

protected object GetValue(JToken token, Type propertyType)
		{
			var value = token.ToObject<object>();

			if (value == null)
			{
				return null;
			}

			if (propertyType == typeof(bool?))
			{
				return Convert.ToBoolean(value);
			}

			if (propertyType == typeof(CrmEnreplacedyReference))
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return new CrmEnreplacedyReference(enreplacedyReference.LogicalName, enreplacedyReference.Id);
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
			}

			if (propertyType == typeof(DateTime?))
			{
				var dateTimeValue = value is DateTime ? (DateTime)value : Convert.ToDateTime(value);

				return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
			}

			if (propertyType == typeof(double?))
			{
				return Convert.ToDouble(value);
			}

			if (propertyType == typeof(decimal))
			{
				return Convert.ToDecimal(value);
			}

			if (propertyType == typeof(EnreplacedyReference))
			{
				EnreplacedyReference enreplacedyReference;

				if (TryGetEnreplacedyReference(value, out enreplacedyReference))
				{
					return enreplacedyReference;
				}

				throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
			}

			if (propertyType == typeof(Guid?))
			{
				return value is Guid ? value : new Guid(value.ToString());
			}

			if (propertyType == typeof(int?))
			{
				return Convert.ToInt32(value);
			}

			if (propertyType == typeof(long?))
			{
				return Convert.ToInt64(value);
			}

			if (propertyType == typeof(string))
			{
				return value is string ? value : value.ToString();
			}

			if (propertyType.IsreplacedignableFrom(value.GetType()))
			{
				return value;
			}

			throw new InvalidOperationException("Unable to convert value of type".FormatWith(value.GetType(), propertyType, Attribute.CrmPropertyAttribute.LogicalName));
		}

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

private static string GetTokenString(IList<Claim> claims)
		{
			string tokenString = null;
			using (var cryptoServiceProvider = GetCryptoProvider(true))
			{
				string issuer = PortalSettings.Instance.DomainName;
				string audience = string.Empty;
				DateTime notBefore = DateTime.Now;
				DateTime expires = notBefore.AddHours(1);

				var tokenHandler = new JwtSecurityTokenHandler();
				var signingCredentials = new SigningCredentials(new RsaSecurityKey(cryptoServiceProvider),
					SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

				// need to explicitly add "iat" claim
				DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
				var iat = Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(notBefore) - unixEpoch).TotalSeconds - 1);
				claims.Add(new Claim("iat", iat.ToString(), ClaimValueTypes.Integer));

				var header = new JwtHeader(signingCredentials);
				var payload = new JwtPayload(issuer, audience, claims, notBefore, expires);

				// Need to adjust this because Claim clreplaced ignores value type
				payload["iat"] = Convert.ToInt64(payload["iat"]);

				var jwtToken = new JwtSecurityToken(header, payload);

				tokenString = tokenHandler.WriteToken(jwtToken);
			}
			return tokenString;
		}

19 View Source File : TokenConverterContract.cs
License : MIT License
Project Creator : AElfProject

public override Empty Sell(SellInput input)
        {
            var fromConnector = State.Connectors[input.Symbol];
            replacedert(fromConnector != null, "[Sell]Can't find from connector.");
            replacedert(fromConnector.IsPurchaseEnabled, "can't purchase");
            var toConnector = State.Connectors[fromConnector.RelatedSymbol];
            replacedert(toConnector != null, "[Sell]Can't find to connector.");
            var amountToReceive = BancorHelper.GetReturnFromPaid(
                GetSelfBalance(fromConnector), GetWeight(fromConnector),
                GetSelfBalance(toConnector), GetWeight(toConnector),
                input.Amount
            );

            var fee = Convert.ToInt64(amountToReceive * GetFeeRate());

            if (Context.Sender == Context.GetContractAddressByName(SmartContractConstants.TreasuryContractSystemName))
            {
                fee = 0;
            }

            var amountToReceiveLessFee = amountToReceive.Sub(fee);
            replacedert(input.ReceiveLimit == 0 || amountToReceiveLessFee >= input.ReceiveLimit, "Price not good.");

            // Pay fee
            if (fee > 0)
            {
                HandleFee(fee);
            }

            // Transfer base token
            State.TokenContract.Transfer.Send(
                new TransferInput
                {
                    Symbol = State.BaseTokenSymbol.Value,
                    To = Context.Sender,
                    Amount = amountToReceive
                });
            State.DepositBalance[toConnector.Symbol] =
                State.DepositBalance[toConnector.Symbol].Sub(amountToReceive);
            // Transfer sold token
            State.TokenContract.TransferFrom.Send(
                new TransferFromInput
                {
                    Symbol = input.Symbol,
                    From = Context.Sender,
                    To = Context.Self,
                    Amount = input.Amount
                });
            Context.Fire(new TokenSold
            {
                Symbol = input.Symbol,
                SoldAmount = input.Amount,
                BaseAmount = amountToReceive,
                FeeAmount = fee
            });
            return new Empty();
        }

19 View Source File : EconomicContractInitializationProvider.cs
License : MIT License
Project Creator : AElfProject

public List<ContractInitializationMethodCall> GetInitializeMethodList(byte[] contractCode)
        {
            return new List<ContractInitializationMethodCall>
            {
                new ContractInitializationMethodCall{
                    MethodName = nameof(EconomicContractContainer.EconomicContractStub.InitialEconomicSystem),
                    Params = new InitialEconomicSystemInput
                    {
                        NativeTokenDecimals = _economicOptions.Decimals,
                        IsNativeTokenBurnable = _economicOptions.IsBurnable,
                        NativeTokenSymbol = _economicOptions.Symbol,
                        NativeTokenName = _economicOptions.TokenName,
                        NativeTokenTotalSupply = _economicOptions.TotalSupply,
                        MiningRewardTotalAmount =
                            Convert.ToInt64(_economicOptions.TotalSupply * _economicOptions.DividendPoolRatio),
                        TransactionSizeFeeUnitPrice = _economicOptions.TransactionSizeFeeUnitPrice
                    }.ToByteString()
                },
                new ContractInitializationMethodCall{
                    MethodName = nameof(EconomicContractContainer.EconomicContractStub.IssueNativeToken),
                    Params = new IssueNativeTokenInput
                    {
                        Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                        To = Address.FromPublicKey(
                            ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList.First())),
                        Memo = "Issue native token"
                    }.ToByteString()
                }
            };
        }

19 View Source File : TokenConverterContract.cs
License : MIT License
Project Creator : AElfProject

public override Empty Buy(BuyInput input)
        {
            var toConnector = State.Connectors[input.Symbol];
            replacedert(toConnector != null, "[Buy]Can't find to connector.");
            replacedert(toConnector.IsPurchaseEnabled, "can't purchase");
            replacedert(!string.IsNullOrEmpty(toConnector.RelatedSymbol), "can't find related symbol'");
            var fromConnector = State.Connectors[toConnector.RelatedSymbol];
            replacedert(fromConnector != null, "[Buy]Can't find from connector.");
            var amountToPay = BancorHelper.GetAmountToPayFromReturn(
                GetSelfBalance(fromConnector), GetWeight(fromConnector),
                GetSelfBalance(toConnector), GetWeight(toConnector),
                input.Amount);
            var fee = Convert.ToInt64(amountToPay * GetFeeRate());

            var amountToPayPlusFee = amountToPay.Add(fee);
            replacedert(input.PayLimit == 0 || amountToPayPlusFee <= input.PayLimit, "Price not good.");

            // Pay fee
            if (fee > 0)
            {
                HandleFee(fee);
            }

            // Transfer base token
            State.TokenContract.TransferFrom.Send(
                new TransferFromInput()
                {
                    Symbol = State.BaseTokenSymbol.Value,
                    From = Context.Sender,
                    To = Context.Self,
                    Amount = amountToPay,
                });
            State.DepositBalance[fromConnector.Symbol] = State.DepositBalance[fromConnector.Symbol].Add(amountToPay);
            // Transfer bought token
            State.TokenContract.Transfer.Send(
                new TransferInput
                {
                    Symbol = input.Symbol,
                    To = Context.Sender,
                    Amount = input.Amount
                });

            Context.Fire(new TokenBought
            {
                Symbol = input.Symbol,
                BoughtAmount = input.Amount,
                BaseAmount = amountToPay,
                FeeAmount = fee
            });
            return new Empty();
        }

19 View Source File : UnitTestTokenContractInitializationProvider.cs
License : MIT License
Project Creator : AElfProject

public override List<ContractInitializationMethodCall> GetInitializeMethodList(byte[] contractCode)
        {
            var address = Address.FromPublicKey(
                ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList[0]));
            var list = new List<ContractInitializationMethodCall>
            {
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Create),
                    Params = new CreateInput
                    {
                        Decimals = _economicOptions.Decimals,
                        Issuer = address,
                        IsBurnable = _economicOptions.IsBurnable,
                        Symbol = _economicOptions.Symbol,
                        TokenName = _economicOptions.TokenName,
                        TotalSupply = _economicOptions.TotalSupply,
                    }.ToByteString(),
                },
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Issue),
                    Params = new IssueInput
                    {
                        Symbol = _economicOptions.Symbol,
                        Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                        To = address,
                        Memo = "Issue native token"
                    }.ToByteString()
                }
            };
            return list;
        }

19 View Source File : UnitTestTokenContractInitializationProvider.cs
License : MIT License
Project Creator : AElfProject

public override List<ContractInitializationMethodCall> GetInitializeMethodList(byte[] contractCode)
        {
            var address = Address.FromPublicKey(
                ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList[0]));
            var list = new List<ContractInitializationMethodCall>
            {
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Create),
                    Params = new CreateInput
                    {
                        Decimals = _economicOptions.Decimals,
                        Issuer = address,
                        IsBurnable = _economicOptions.IsBurnable,
                        Symbol = _economicOptions.Symbol,
                        TokenName = _economicOptions.TokenName,
                        TotalSupply = _economicOptions.TotalSupply,
                    }.ToByteString(),
                },
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Issue),
                    Params = new IssueInput
                    {
                        Symbol = _economicOptions.Symbol,
                        Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                        To = address,
                        Memo = "Issue native token"
                    }.ToByteString()
                },
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.SetPrimaryTokenSymbol),
                    Params = new SetPrimaryTokenSymbolInput
                    {
                        Symbol = _economicOptions.Symbol
                    }.ToByteString()
                },
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.InitialCoefficients),
                    Params = new Empty().ToByteString()
                }
            };
            return list;
        }

19 View Source File : TokenConverterContractTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task Buy_Success_Test()
        {
            await CreateRamToken();
            await InitializeTreasuryContractAsync();
            await InitializeTokenConverterContract();
            await PrepareToBuyAndSell();

            //check the price and fee
            var fromConnectorBalance = ELFConnector.VirtualBalance;
            var fromConnectorWeight = decimal.Parse(ELFConnector.Weight);
            var toConnectorBalance = await GetBalanceAsync(WriteSymbol, TokenConverterContractAddress);
            var toConnectorWeight = decimal.Parse(WriteConnector.Weight);

            var amountToPay = BancorHelper.GetAmountToPayFromReturn(fromConnectorBalance, fromConnectorWeight,
                toConnectorBalance, toConnectorWeight, 1000L);
            var depositAmountBeforeBuy = await DefaultStub.GetDepositConnectorBalance.CallAsync(new StringValue
            {
                Value = WriteConnector.Symbol
            });
            var fee = Convert.ToInt64(amountToPay * 5 / 1000);

            var buyResult = (await DefaultStub.Buy.SendAsync(
                new BuyInput
                {
                    Symbol = WriteConnector.Symbol,
                    Amount = 1000L,
                    PayLimit = amountToPay + fee + 10L
                })).TransactionResult;
            buyResult.Status.ShouldBe(TransactionResultStatus.Mined);

            //Verify the outcome of the transaction
            var depositAmountAfterBuy = await DefaultStub.GetDepositConnectorBalance.CallAsync(new StringValue
            {
                Value = WriteConnector.Symbol
            });
            depositAmountAfterBuy.Value.Sub(depositAmountBeforeBuy.Value).ShouldBe(amountToPay);
            var balanceOfTesterWrite = await GetBalanceAsync(WriteSymbol, DefaultSender);
            balanceOfTesterWrite.ShouldBe(1000L);

            var ElfBalanceLoggedInTokenConvert = await DefaultStub.GetDepositConnectorBalance.CallAsync(new StringValue
            {
                Value = WriteConnector.Symbol
            });
            ElfBalanceLoggedInTokenConvert.Value.ShouldBe(ELFConnector.VirtualBalance + amountToPay);
            var balanceOfElfToken = await GetBalanceAsync(NativeSymbol, TokenConverterContractAddress);
            balanceOfElfToken.ShouldBe(amountToPay);

            var donatedFee = await TreasuryContractStub.GetUndistributedDividends.CallAsync(new Empty());
            donatedFee.Value[NativeSymbol].ShouldBe(fee.Div(2));

            var balanceOfRamToken = await GetBalanceAsync(WriteSymbol, TokenConverterContractAddress);
            balanceOfRamToken.ShouldBe(100_0000L - 1000L);

            var balanceOfTesterToken = await GetBalanceAsync(NativeSymbol, DefaultSender);
            balanceOfTesterToken.ShouldBe(100_0000L - amountToPay - fee);
        }

19 View Source File : TokenConverterContractTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task Sell_Success_Test()
        {
            await CreateRamToken();
            await InitializeTreasuryContractAsync();
            await InitializeTokenConverterContract();
            await PrepareToBuyAndSell();

            var buyResult = (await DefaultStub.Buy.SendAsync(
                new BuyInput
                {
                    Symbol = WriteConnector.Symbol,
                    Amount = 1000L,
                    PayLimit = 1010L
                })).TransactionResult;
            buyResult.Status.ShouldBe(TransactionResultStatus.Mined);

            //Balance  before Sell
            var treasuryBeforeSell = (await TreasuryContractStub.GetUndistributedDividends.CallAsync(new Empty())).Value[NativeSymbol];
            var balanceOfElfToken = await GetBalanceAsync(NativeSymbol, TokenConverterContractAddress);
            var balanceOfTesterToken = await GetBalanceAsync(NativeSymbol, DefaultSender);

            //check the price and fee
            var toConnectorBalance = ELFConnector.VirtualBalance + balanceOfElfToken;
            var toConnectorWeight = decimal.Parse(ELFConnector.Weight);
            var fromConnectorBalance = await GetBalanceAsync(WriteSymbol, TokenConverterContractAddress);
            var fromConnectorWeight = decimal.Parse(WriteConnector.Weight);

            var amountToReceive = BancorHelper.GetReturnFromPaid(fromConnectorBalance, fromConnectorWeight,
                toConnectorBalance, toConnectorWeight, 1000L);
            var depositAmountBeforeSell = await DefaultStub.GetDepositConnectorBalance.CallAsync(new StringValue
            {
                Value = WriteConnector.Symbol
            });
            var fee = Convert.ToInt64(amountToReceive * 5 / 1000);

            var sellResult = (await DefaultStub.Sell.SendAsync(new SellInput
            {
                Symbol = WriteConnector.Symbol,
                Amount = 1000L,
                ReceiveLimit = amountToReceive - fee - 10L
            })).TransactionResult;
            sellResult.Status.ShouldBe(TransactionResultStatus.Mined);

            //Verify the outcome of the transaction
            var depositAmountAfterSell = await DefaultStub.GetDepositConnectorBalance.CallAsync(new StringValue
            {
                Value = WriteConnector.Symbol
            });
            depositAmountBeforeSell.Value.Sub(depositAmountAfterSell.Value).ShouldBe(amountToReceive);
            var balanceOfTesterRam = await GetBalanceAsync(WriteSymbol, DefaultSender);
            balanceOfTesterRam.ShouldBe(0L);

            var treasuryAfterSell = await TreasuryContractStub.GetUndistributedDividends.CallAsync(new Empty());
            treasuryAfterSell.Value[NativeSymbol].ShouldBe(fee.Div(2) + treasuryBeforeSell);

            var balanceOfElfTokenAfterSell = await GetBalanceAsync(NativeSymbol, TokenConverterContractAddress);
            balanceOfElfTokenAfterSell.ShouldBe(balanceOfElfToken - amountToReceive);

            var balanceOfRamToken = await GetBalanceAsync(WriteSymbol, TokenConverterContractAddress);
            balanceOfRamToken.ShouldBe(100_0000L);

            var balanceOfTesterTokenAfterSell = await GetBalanceAsync(NativeSymbol, DefaultSender);
            balanceOfTesterTokenAfterSell.ShouldBe(balanceOfTesterToken + amountToReceive - fee);
        }

19 View Source File : Session.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public void Load(string path)
	{
        using (XmlReader xmlReader = XmlReader.Create(path)) {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.Load(xmlReader);

            XmlNodeList fileList = xmlDoc.GetElementsByTagName("file");

            foreach(XmlNode fileNode in fileList) {
                XmlNodeList childNodes = fileNode.ChildNodes;
                SessionFileInfo sfi = new SessionFileInfo();
                foreach(XmlNode node in childNodes) {
                    switch (node.Name) {
                        case "path":
                            sfi.Path = node.InnerText;
                            break;
                        case "offset":
                            sfi.Offset = Convert.ToInt64(node.InnerText);
                            break;
                        case "cursoroffset":
                            sfi.CursorOffset = Convert.ToInt64(node.InnerText);
                            break;
                        case "cursordigit":
                            sfi.CursorDigit = Convert.ToInt32(node.InnerText);
                            break;
                        case "layout":
                            sfi.Layout = node.InnerText;
                            break;
                        case "focusedarea":
                            sfi.FocusedArea = Convert.ToInt32(node.InnerText);
                            break;
                        default:
                            break;
                    }
                }
                files.Add(sfi);
            }

            XmlNodeList heightList = xmlDoc.GetElementsByTagName("windowheight");
            foreach(XmlNode heightNode in heightList) {
                windowHeight = Convert.ToInt32(heightNode.InnerText);
            }

            XmlNodeList widthList = xmlDoc.GetElementsByTagName("windowwidth");
            foreach(XmlNode widthNode in widthList) {
                windowWidth = Convert.ToInt32(widthNode.InnerText);
            }

            XmlNodeList activeList = xmlDoc.GetElementsByTagName("activefile");
            foreach(XmlNode activeNode in activeList) {
                activeFile = activeNode.InnerText;
            }
		}
	}

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

public static List<EnumInfomation<T>> KeyValue<T>(bool keepNone = false) where T : struct
        {
            var t = typeof(T);
            var enumValues = t.GetEnumValues();
            return (from T value in enumValues
                    let lv = Convert.ToInt64(value)
                    let caption = t.GetFieldDescription(value.ToString())
                    where caption != null && (!keepNone || lv != 0)
                    select new EnumInfomation<T>
                    {
                        Value = value,
                        LValue = Convert.ToInt64(value),
                        Caption = caption
                    }).ToList();
        }

19 View Source File : SerialNumber.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static SerialNumber DeSerialize(string str)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = Global.Config.InstallTime;
					sn.ExpireTime = Global.Config.InstallTime.Add(span);
				}
			}
			return sn;
		}

19 View Source File : SerialNumber.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static SerialNumber DeSerialize(string str, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 View Source File : SerialNumber.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static SerialNumber DeSerialize(string licContent, string keyName, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(licContent))
			{
				string[] ss = RSA.Decrypt(licContent, keyName).Split(',');
				if (ss.Length > 4)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						LicenseType = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3],
						MaxActivity = Convert.ToInt32(ss[4])
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 View Source File : ImageStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public byte[] ReadImageData(string snapshotId)
		{
			byte[] bsImage = null;
			try
			{
				var sshot = Database.Invoke(db => db.SelectRow("Snapshots", new { SnapshotId = snapshotId },
					"SessionId", "WindowRect", "MouseState", "ImagePos", "ImageLength"));
				if (sshot != null)
				{
					Guid sessionId = new Guid(sshot["SessionId"].ToString());
					string path = Path.Combine(DataPath, sessionId.ToString("n") + ".rdm");
					if (File.Exists(path))
					{
						using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
						using (BinaryReader br = new BinaryReader(fs))
						{
							br.BaseStream.Seek(Convert.ToInt64(sshot["ImagePos"]), SeekOrigin.Begin);
							bsImage = br.ReadBytes(Convert.ToInt32(sshot["ImageLength"]));
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return bsImage;
		}

19 View Source File : LocalStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Obsolete]
		public byte[] ReadImage(string snapshotId)
		{
			byte[] bsImage = null;
			try
			{
				var sshot = Database.Invoke(db => db.SelectRow("Snapshots", new { SnapshotId = snapshotId },
					"SessionId", "WindowRect", "MouseState", "ImagePos", "ImageLength"));
				if (sshot != null)
				{
					Guid sessionId = new Guid(sshot["SessionId"].ToString());
					string path = Path.Combine(DataPath, sessionId.ToString("n") + ".rdt");
					if (File.Exists(path))
					{
						using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
						using (BinaryReader br = new BinaryReader(fs))
						{
							br.BaseStream.Seek(Convert.ToInt64(sshot["ImagePos"]), SeekOrigin.Begin);
							bsImage = br.ReadBytes(Convert.ToInt32(sshot["ImageLength"]));
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return bsImage;
		}

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

private void ParseNumber(ReadType readType)
        {
            ShiftBufferIfNeeded();

            char firstChar = _chars[_charPos];
            int initialPosition = _charPos;

            ReadNumberIntoBuffer();

            // set state to PostValue now so that if there is an error parsing the number then the reader can continue
            SetPostValueState(true);

            _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);

            object numberValue;
            JsonToken numberType;

            bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
            bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');

            if (readType == ReadType.Readreplacedtring)
            {
                string number = _stringReference.ToString();

                // validate that the string is a valid number
                if (nonBase10)
                {
                    try
                    {
                        if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                        {
                            Convert.ToInt64(number, 16);
                        }
                        else
                        {
                            Convert.ToInt64(number, 8);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    double value;
                    if (!double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.String;
                numberValue = number;
            }
            else if (readType == ReadType.ReadAsInt32)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8);

                        numberValue = integer;
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    int value;
                    ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
                    if (parseResult == ParseResult.Success)
                    {
                        numberValue = value;
                    }
                    else if (parseResult == ParseResult.Overflow)
                    {
                        throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Integer;
            }
            else if (readType == ReadType.ReadAsDecimal)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (decimal)firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        // decimal.Parse doesn't support parsing hexadecimal values
                        long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);

                        numberValue = Convert.ToDecimal(integer);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    string number = _stringReference.ToString();

                    decimal value;
                    if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
                    {
                        numberValue = value;
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Float;
            }
            else if (readType == ReadType.ReadAsDouble)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (double)firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        // double.Parse doesn't support parsing hexadecimal values
                        long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);

                        numberValue = Convert.ToDouble(integer);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    string number = _stringReference.ToString();

                    double value;
                    if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        numberValue = value;
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Float;
            }
            else
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (long)firstChar - 48;
                    numberType = JsonToken.Integer;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }

                    numberType = JsonToken.Integer;
                }
                else
                {
                    long value;
                    ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
                    if (parseResult == ParseResult.Success)
                    {
                        numberValue = value;
                        numberType = JsonToken.Integer;
                    }
                    else if (parseResult == ParseResult.Overflow)
                    {
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                        string number = _stringReference.ToString();

                        if (number.Length > MaximumJavascriptIntegerCharacterLength)
                        {
                            throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                        }

                        numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture);
                        numberType = JsonToken.Integer;
#else
                        throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
                    }
                    else
                    {
                        string number = _stringReference.ToString();

                        if (_floatParseHandling == FloatParseHandling.Decimal)
                        {
                            decimal d;
                            if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
                            {
                                numberValue = d;
                            }
                            else
                            {
                                throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
                            }
                        }
                        else
                        {
                            double d;
                            if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
                            {
                                numberValue = d;
                            }
                            else
                            {
                                throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
                            }
                        }

                        numberType = JsonToken.Float;
                    }
                }
            }

            ClearRecentString();

            // index has already been updated
            SetToken(numberType, numberValue, false);
        }

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

private void WriteTokenInternal(BsonToken t)
        {
            switch (t.Type)
            {
                case BsonType.Object:
                {
                    BsonObject value = (BsonObject)t;
                    _writer.Write(value.CalculatedSize);
                    foreach (BsonProperty property in value)
                    {
                        _writer.Write((sbyte)property.Value.Type);
                        WriteString((string)property.Name.Value, property.Name.ByteCount, null);
                        WriteTokenInternal(property.Value);
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Array:
                {
                    BsonArray value = (BsonArray)t;
                    _writer.Write(value.CalculatedSize);
                    ulong index = 0;
                    foreach (BsonToken c in value)
                    {
                        _writer.Write((sbyte)c.Type);
                        WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
                        WriteTokenInternal(c);
                        index++;
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Integer:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Long:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Number:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.String:
                {
                    BsonString value = (BsonString)t;
                    WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
                }
                    break;
                case BsonType.Boolean:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write((bool)value.Value);
                }
                    break;
                case BsonType.Null:
                case BsonType.Undefined:
                    break;
                case BsonType.Date:
                {
                    BsonValue value = (BsonValue)t;

                    long ticks = 0;

                    if (value.Value is DateTime)
                    {
                        DateTime dateTime = (DateTime)value.Value;
                        if (DateTimeKindHandling == DateTimeKind.Utc)
                        {
                            dateTime = dateTime.ToUniversalTime();
                        }
                        else if (DateTimeKindHandling == DateTimeKind.Local)
                        {
                            dateTime = dateTime.ToLocalTime();
                        }

                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
                    }
#if !NET20
                    else
                    {
                        DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
                    }
#endif

                    _writer.Write(ticks);
                }
                    break;
                case BsonType.Binary:
                {
                    BsonBinary value = (BsonBinary)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data.Length);
                    _writer.Write((byte)value.BinaryType);
                    _writer.Write(data);
                }
                    break;
                case BsonType.Oid:
                {
                    BsonValue value = (BsonValue)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data);
                }
                    break;
                case BsonType.Regex:
                {
                    BsonRegex value = (BsonRegex)t;

                    WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
                    WriteString((string)value.Options.Value, value.Options.ByteCount, null);
                }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
            }
        }

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

private string ConvertTokenToXmlValue(JsonReader reader)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return (reader.Value != null) ? reader.Value.ToString() : null;
            }
            else if (reader.TokenType == JsonToken.Integer)
            {
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
                if (reader.Value is BigInteger)
                {
                    return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture);
                }
#endif

                return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Float)
            {
                if (reader.Value is decimal)
                {
                    return XmlConvert.ToString((decimal)reader.Value);
                }
                if (reader.Value is float)
                {
                    return XmlConvert.ToString((float)reader.Value);
                }

                return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Boolean)
            {
                return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
            }
            else if (reader.TokenType == JsonToken.Date)
            {
#if !NET20
                if (reader.Value is DateTimeOffset)
                {
                    return XmlConvert.ToString((DateTimeOffset)reader.Value);
                }
#endif

                DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
#if !PORTABLE
                return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
#else
                return XmlConvert.ToString(d);
#endif
            }
            else if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else
            {
                throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
        }

19 View Source File : LgpReader.cs
License : MIT License
Project Creator : akpaevj

private EventLogItem ParseEventLogItemData(StringBuilder eventLogItemData, long endPosition,
            CancellationToken cancellationToken = default)
        {
            var parsedData = BracketsParser.ParseBlock(eventLogItemData);

            var eventLogItem = new EventLogItem
            {
                TransactionStatus = GetTransactionPresentation(parsedData[1]),
                FileName = LgpFileName,
                EndPosition = endPosition,
                LgfEndPosition = _lgfReader.GetPosition()
            };

            try
            {
                eventLogItem.DateTime = _timeZone.ToUtc(DateTime.ParseExact(parsedData[0], "yyyyMMddHHmmss",
                    CultureInfo.InvariantCulture));
            }
            catch
            {
                eventLogItem.DateTime = DateTime.MinValue;
            }

            var transactionData = parsedData[2];
            eventLogItem.TransactionNumber = Convert.ToInt64(transactionData[1], 16);

            var transactionDate = new DateTime().AddSeconds(Convert.ToInt64(transactionData[0], 16) / 10000);
            eventLogItem.TransactionDateTime = transactionDate == DateTime.MinValue
                ? transactionDate
                : _timeZone.ToUtc(transactionDate);

            var (value, uuid) = _lgfReader.GetReferencedObjectValue(ObjectType.Users, parsedData[3], cancellationToken);
            eventLogItem.UserUuid = uuid;
            eventLogItem.User = value;

            eventLogItem.Computer = _lgfReader.GetObjectValue(ObjectType.Computers, parsedData[4], cancellationToken);

            var application = _lgfReader.GetObjectValue(ObjectType.Applications, parsedData[5], cancellationToken);
            eventLogItem.Application = GetApplicationPresentation(application);

            eventLogItem.Connection = parsedData[6];

            var ev = _lgfReader.GetObjectValue(ObjectType.Events, parsedData[7], cancellationToken);
            eventLogItem.Event = GetEventPresentation(ev);

            var severity = (string) parsedData[8];
            eventLogItem.Severity = GetSeverityPresentation(severity);

            eventLogItem.Comment = parsedData[9];

            (value, uuid) = _lgfReader.GetReferencedObjectValue(ObjectType.Metadata, parsedData[10], cancellationToken);
            eventLogItem.MetadataUuid = uuid;
            eventLogItem.Metadata = value;

            eventLogItem.Data = GetData(parsedData[11]).Trim();
            eventLogItem.DataPresentation = parsedData[12];
            eventLogItem.Server = _lgfReader.GetObjectValue(ObjectType.Servers, parsedData[13], cancellationToken);

            var mainPort = _lgfReader.GetObjectValue(ObjectType.MainPorts, parsedData[14], cancellationToken);
            if (mainPort != "")
                eventLogItem.MainPort = int.Parse(mainPort);

            var addPort = _lgfReader.GetObjectValue(ObjectType.AddPorts, parsedData[15], cancellationToken);
            if (addPort != "")
                eventLogItem.AddPort = int.Parse(addPort);

            eventLogItem.Session = parsedData[16];

            return eventLogItem;
        }

19 View Source File : ExperimentController.cs
License : MIT License
Project Creator : AlexanderFroemmgen

[HttpGet("{id}/remainingTime")]
        public IActionResult GetRemainingTime(int id)
        {
            var sim = _context.Experiments
                .Include(s => s.ExperimentInstances)
                .SingleOrDefault(s => s.Id == id);

            if (sim == null)
            {
                return NotFound();
            }

            var workStarted = sim.ExperimentInstances
                .Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
                .Select(i => i.WorkStarted)
                .DefaultIfEmpty().Min();

            var avgTimeSpan = TimeSpan.FromTicks(Convert.ToInt64(sim.ExperimentInstances
                .Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
                .Select(i => (i.WorkFinished - i.WorkStarted).Ticks)
                .DefaultIfEmpty().Average()));

            var activeWorkers =
                _context.Workers.Count(w => w.LastRequestTime > DateTime.UtcNow.AddTicks(-2 * avgTimeSpan.Ticks));

            var remainingExperiments =
                sim.ExperimentInstances.Count(
                    i => i.Status == ExperimentStatus.Pending || i.Status == ExperimentStatus.Running);

            var estimatedRemainingTime = TimeSpan.FromMilliseconds(-1);

            if (activeWorkers > 0)
            {
                estimatedRemainingTime = TimeSpan.FromTicks(avgTimeSpan.Ticks * remainingExperiments / activeWorkers);
            }

            var result = new
            {
                WorkStarted = workStarted,
                ElapsedTime = DateTime.UtcNow - workStarted,
                AverageTimeToCompletion = avgTimeSpan,
                ActiveWorkerCount = activeWorkers,
                RemainingExperimentCount = remainingExperiments,
                EstimatedRemainingTime = estimatedRemainingTime,
                EstimatedTimeOfCompletion = DateTime.UtcNow.Add(estimatedRemainingTime)
            };

            return new ObjectResult(result);
        }

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

public static long Process(
      Stream data,
      ArchiveType archiveType, CompressionType compType,
      EncryptionProtocol encProtocol, EncryptionAlgorithm encAlgorithm)
    {
      string fileName = Path.GetTempFileName();
      FileInfo fileInfo = new FileInfo(fileName);
      long compSizeB = 0;

      ProgressStreamReportDelegate progressCallback =
        (_, args) => compSizeB += args.BytesMoved;

      using (Stream outFileStream = fileInfo.OpenWrite())
      {
        Action<Stream> streamWriter =
          (outStream) => CompressionHelper.Compress(
            "data.bin",
            data,
            outStream,
            archiveType,
            compType,
            progressCallback
          );

        switch (encProtocol)
        {
          case EncryptionProtocol.None:
            streamWriter(outFileStream);
            break;

          case EncryptionProtocol.AES:
            EncryptionHelper.EncryptStreamAES(streamWriter, outFileStream, encAlgorithm, Const.EncKey32);
            break;

          case EncryptionProtocol.PBE:
            EncryptionHelper.EncryptStreamPBE(streamWriter, outFileStream, encAlgorithm, Const.EncKey32);
            break;

          case EncryptionProtocol.PGP:
            using (Stream pgpPubKeyStream = new MemoryStream(Encoding.ASCII.GetBytes(Const.PGPPubKey)))
            EncryptionHelper.EncryptStreamPGP(
              streamWriter, outFileStream, encAlgorithm,
              pgpPubKeyStream, Convert.ToInt64(Const.PGPPubKeyID, 16));
            break;
        }
      }

      fileInfo.Delete();

      return compSizeB;
    }

19 View Source File : BinanceServerSpot.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<Trade> GetTickDataToSecurity(Security security, DateTime startTime, DateTime endTime, DateTime lastDate)
        {
            string markerDateTime = "";

            List<Trade> trades = new List<Trade>();

            DateTime startOver = startTime;
            long lastId = 0;

            while (true)
            {
                if (startOver >= endTime)
                {
                    break;
                }

                List<Trade> newTrades = new List<Trade>();

                if (lastId == 0)
                {
                    List<Trade> firstTrades = new List<Trade>();

                    do
                    {
                        firstTrades = _client.GetTickHistoryToSecurity(security.Name, startOver, startOver.AddSeconds(60), 0);
                        startOver.AddSeconds(60);
                        Thread.Sleep(60);
                    }
                    while (firstTrades == null || firstTrades.Count == 0);


                    Trade firstTrade = firstTrades.First();

                    lastId = Convert.ToInt64(firstTrade.Id);

                    newTrades.Add(firstTrade);
                }
                else
                {
                    newTrades = _client.GetTickHistoryToSecurity(security.Name, new DateTime(), new DateTime(), lastId + 1);

                    try
                    {
                        lastId = Convert.ToInt64(newTrades[newTrades.Count - 1].Id);
                    }
                    catch { } // Если дата по которую скачиваем свечки превышает сегодняшнюю: Ignore 
                }

                if (newTrades != null && newTrades.Count != 0)
                    trades.AddRange(newTrades);
                else
                    break;

                startOver = trades[trades.Count - 1].Time.AddMilliseconds(1);


                if (markerDateTime != startOver.ToShortDateString())
                {
                    markerDateTime = startOver.ToShortDateString();
                    SendLogMessage(security.Name + " Binance Spot start loading: " + markerDateTime, LogMessageType.System);
                }

                Thread.Sleep(10);
            }

            if (trades.Count == 0)
            {
                return null;
            }

            while (trades.Last().Time >= endTime)
                trades.Remove(trades.Last());


            return trades;
        }

19 View Source File : BitMaxProServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ClientMyOrderEvent(OrderState bitMaxOrder)
        {
            var data = bitMaxOrder.Data;

            OrderCoupler needCoupler = _couplers.Find(c => c.OrderNumberMarket == data.OrderId);

            if (needCoupler == null)
            {
                return;
            }

            Order order = new Order();
            order.NumberUser = needCoupler.OsOrderNumberUser;
            order.NumberMarket = data.OrderId;
            order.PortfolioNumber = data.S.Split('/')[1];
            order.Price = data.P.ToDecimal();
            order.Volume = data.Q.ToDecimal();
            order.Side = data.Sd == "Buy" ? Side.Buy : Side.Sell;
            order.SecurityNameCode = data.S;
            order.ServerType = ServerType;
            order.TimeCallBack = TimeManager.GetDateTimeFromTimeStamp(Convert.ToInt64(data.T));
            order.TypeOrder = OrderPriceType.Limit;

            if (data.St == "New")
            {
                order.State = OrderStateType.Activ;
            }
            else if (data.St == "Canceled")
            {
                order.State = OrderStateType.Cancel;
                _couplers.Remove(needCoupler);
            }
            else if (data.St == "PartiallyFilled")
            {
                order.State = OrderStateType.Patrial;
            }
            else if (data.St == "Filled")
            {
                order.State = OrderStateType.Done;
                _couplers.Remove(needCoupler);
            }
            else if (data.St == "Rejected")
            {
                order.State = OrderStateType.Fail;
            }

            if (bitMaxOrder.Data.St == "PartiallyFilled" || bitMaxOrder.Data.St == "Filled")
            {
                var replacedVolume = data.Cfq.ToDecimal();

                var tradeVolume = replacedVolume - needCoupler.CurrentVolume;
                needCoupler.CurrentVolume += tradeVolume;

                MyTrade myTrade = new MyTrade
                {
                    NumberOrderParent = data.OrderId,
                    Side = data.Sd == "Buy" ? Side.Buy : Side.Sell,
                    SecurityNameCode = data.S,
                    Price = data.Ap.ToDecimal(),
                    Volume = tradeVolume,
                    NumberTrade = data.Sn.ToString(),
                    Time = TimeManager.GetDateTimeFromTimeStamp(Convert.ToInt64(data.T)),
                };

                MyTradeEvent?.Invoke(myTrade);
            }

            MyOrderEvent?.Invoke(order);
        }

19 View Source File : BitMaxProServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<Candle> GetCandleHistory(string nameSec, TimeSpan tf)
        {
            string tfServer = GetNeedTimeFrameForServer((int)tf.TotalMinutes);

            int intervalTf;

            if (!int.TryParse(tfServer, out intervalTf))
            {
                intervalTf = 1440;
            }

            var interval = intervalTf * 1000;

            long start = TimeManager.GetUnixTimeStampMilliseconds() - Convert.ToInt64(TimeSpan.FromMinutes(interval).TotalMilliseconds);

            long end = TimeManager.GetUnixTimeStampMilliseconds();

            var bitMaxCandles = _client.GetCandles(nameSec, tfServer, start, end);

            List<Candle> newCandles = new List<Candle>();

            foreach (var bitMaxCandle in bitMaxCandles.Candles)
            {
                newCandles.Add(new Candle()
                {
                    Open = bitMaxCandle.Candle.O.ToDecimal(),
                    High = bitMaxCandle.Candle.H.ToDecimal(),
                    Low = bitMaxCandle.Candle.L.ToDecimal(),
                    Close = bitMaxCandle.Candle.C.ToDecimal(),
                    Volume = bitMaxCandle.Candle.V.ToDecimal(),
                    TimeStart = TimeManager.GetDateTimeFromTimeStamp(
                        Convert.ToInt64(bitMaxCandle.Candle.Ts.ToString().Replace(",",
                            CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator),
                        CultureInfo.InvariantCulture)),
                    State = CandleState.None,
                });
            }

            if (intervalTf == (int)tf.TotalMinutes)
            {
                return newCandles;
            }

            var newTfCandles = BuildCandles(newCandles, (int)tf.TotalMinutes, intervalTf);

            return newTfCandles;
        }

19 View Source File : LivecoinClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void CancelLimitOrder(OsEngine.Enreplacedy.Order order)
        {
            if (string.IsNullOrEmpty(order.NumberMarket))
            {
                return;
            }
            var cancelOrders = new protobuf.ws.CancelLimitOrderRequest
            {
                ExpireControl = new protobuf.ws.RequestExpired
                {
                    Now = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds,
                    Ttl = ttl
                },
                CurrencyPair = order.SecurityNameCode.Replace('_', '/'),
                Id = Convert.ToInt64(order.NumberMarket)
            };

            string token = "CancelOrder_" + order.NumberUser;

            SendAuthMessage(_secKey, token, protobuf.ws.WsRequestMetaData.WsRequestMsgType.CancelLimitOrder, cancelOrders);
        }

19 View Source File : BookSnapshotMessage.cs
License : Apache License 2.0
Project Creator : AlexWan

public static BookSnapshotMessage CreateFromString(string rawBookSnapshotMessage)
        {
            var bookSnapshotTokens = KrakenDataMessageHelper.EnsureRawMessage(rawBookSnapshotMessage);
            var detailTokens = (JObject)bookSnapshotTokens[1];
            return new BookSnapshotMessage
            {
                ChannelId = Convert.ToInt64(bookSnapshotTokens.First),
                Asks = ((JArray)detailTokens["as"]).OfType<JArray>().Select(level => PriceLevel.CreateFromJArray(level)).ToArray(),
                Bids = ((JArray)detailTokens["bs"]).OfType<JArray>().Select(level => PriceLevel.CreateFromJArray(level)).ToArray()
            };
        }

19 View Source File : BookUpdateMessage.cs
License : Apache License 2.0
Project Creator : AlexWan

public static BookUpdateMessage CreateFromString(string rawBookUpdateMessage)
        {
            var bookUpdateMessage = KrakenDataMessageHelper.EnsureRawMessage(rawBookUpdateMessage);

            var asks = bookUpdateMessage.Skip(1).OfType<JObject>().FirstOrDefault(x => x.ContainsKey("a"));
            var bids = bookUpdateMessage.Skip(1).OfType<JObject>().FirstOrDefault(x => x.ContainsKey("b"));

            return new BookUpdateMessage
            {
                ChannelId = Convert.ToInt64(bookUpdateMessage.First),
                Asks = asks!= null ? asks["a"].OfType<JArray>().Select(level => PriceLevel.CreateFromJArray(level)).ToArray() : null,
                Bids = bids != null ? bids["b"].OfType<JArray>().Select(level => PriceLevel.CreateFromJArray(level)).ToArray() : null,
            };
        }

19 View Source File : OhlcMessage.cs
License : Apache License 2.0
Project Creator : AlexWan

public static OhlcMessage CreateFromString(string rawOhlcMessage)
        {
            var ohlcMessage = KrakenDataMessageHelper.EnsureRawMessage(rawOhlcMessage);
            var dataArray = ohlcMessage[1] as JArray;
            return new OhlcMessage
            {
                ChannelId = Convert.ToInt64(ohlcMessage.First),
                Time = Convert.ToDecimal(dataArray[0]),
                EndTime = Convert.ToDecimal(dataArray[1]),
                Open = Convert.ToDecimal(dataArray[2]),
                High = Convert.ToDecimal(dataArray[3]),
                Low = Convert.ToDecimal(dataArray[4]),
                Close = Convert.ToDecimal(dataArray[5]),
                Vwap = Convert.ToDecimal(dataArray[6]),
                Volume = Convert.ToDecimal(dataArray[7]),
                Count = Convert.ToInt64(dataArray[8])
            };
        }

19 View Source File : SpreadMessage.cs
License : Apache License 2.0
Project Creator : AlexWan

public static SpreadMessage CreateFromString(string rawSpreadMessage)
        {
            var spreadMessage = KrakenDataMessageHelper.EnsureRawMessage(rawSpreadMessage);
            var spreadTokens = spreadMessage[1] as JArray;
            return new SpreadMessage
            {
                ChannelId = Convert.ToInt64(spreadMessage.First),
                Bid = Convert.ToDecimal(spreadTokens[0]),
                Ask = Convert.ToDecimal(spreadTokens[1]),
                Time = Convert.ToDecimal(spreadTokens[2]),
            };
        }

19 View Source File : TradesMessage.cs
License : Apache License 2.0
Project Creator : AlexWan

public static TradeMessage CreateFromString(string rawMessage)
        {
            var message = KrakenDataMessageHelper.EnsureRawMessage(rawMessage);
            return new TradeMessage()
            {
                ChannelId = Convert.ToInt64(message.First),
                Trades = ((JArray)message[1]).OfType<JArray>().Select(tradeJArray => TradeValues.CreateFromJArray(tradeJArray)).ToArray()
            };
        }

19 View Source File : OandaClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void CancelOrder(Order order)
        {
            if (string.IsNullOrWhiteSpace(order.NumberMarket))
            {
                return;
            }
            if (string.IsNullOrEmpty(order.NumberMarket))
            {
                return;
            }
            try
            {
                var openOrders = Rest20.GetPendingOrderListAsync(Credentials.GetDefaultCredentials().DefaultAccountId);

                while (!openOrders.IsCanceled &&
                        !openOrders.IsCompleted &&
                        !openOrders.IsFaulted) 
                {
                    Thread.Sleep(20);
                }
                

                for (int i = 0; i < openOrders.Result.Count; i++)
                {
                    if (openOrders.Result[i].id == Convert.ToInt64(order.NumberMarket))
                    {
                        Rest20.CancelOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, openOrders.Result[i].id);
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : ZbTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<Trade> Create(string data)
        {
            var trades = new List<Trade>();
            var jt = JToken.Parse(data);
            var tradesData = jt.SelectTokens(DataPath).Children();
            var security = jt[NamePath].ToString().Split('_')[0];

            foreach (var trade in tradesData)
            {
                var time = trade[TimePath].ToString();

                var newTrade = new Trade();

                newTrade.Time = TimeManager.GetDateTimeFromTimeStampSeconds(Convert.ToInt64(time));
                newTrade.SecurityNameCode = security;
                newTrade.Price = trade[PricePath].Value<decimal>();
                newTrade.Id = trade[IdPath].ToString();
                newTrade.Side = trade[DirectionPath].ToString() == "sell" ? Side.Sell : Side.Buy;
                newTrade.Volume = trade[VolumePath].Value<decimal>();

                trades.Add(newTrade);
            }

            return trades;
        }

19 View Source File : Snowflake.cs
License : MIT License
Project Creator : alonsoalon

public long NextId()
        {
            lock (locker)
            {
                var currentTimeStamp = TimeStamp();
                if (currentTimeStamp < lastTimestamp)
                {
                    throw new Exception("时间戳生成出现错误");
                }
                if (currentTimeStamp == lastTimestamp)
                {
                    if (lastIndex < 4095)//为了保证长度
                    {
                        lastIndex++;
                    }
                    else
                    {
                        throw new Exception("单位毫秒内生成的id超过所支持的数量");
                    }
                }
                else
                {
                    lastIndex = 0;
                    lastTimestamp = currentTimeStamp;
                }
                var timeStr = Convert.ToString(currentTimeStamp, 2);
                var dcStr = Convert.ToString(dataCenterId, 2).PadLeft(5, '0');
                var wStr = Convert.ToString(workId, 2).PadLeft(5, '0'); ;
                var indexStr = Convert.ToString(lastIndex, 2).PadLeft(12, '0');
                return Convert.ToInt64($"0{timeStr}{dcStr}{wStr}{indexStr}", 2);
            }

        }

19 View Source File : Variable.cs
License : MIT License
Project Creator : AMalininHere

[ExcludeFromCodeCoverage]
        public long AsLong()
        {
            EnsureIsOfType(VariableType.Long);
            return Convert.ToInt64(Value);
        }

19 View Source File : WebHelper.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites

public static DateTime? GetJwtExp(string token)
        {
            var jwt = new JwtSecurityTokenHandler();
            if (!jwt.CanReadToken(token))
            {
                throw new AccessTokenInvalidException(token);
            }
            var exp = jwt.ReadJwtToken(token).Claims.FirstOrDefault(a => a.Type == "exp")?.Value;
            if (string.IsNullOrWhiteSpace(exp))
            {
                throw new AccessTokenInvalidException(token);
            }
            return DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(exp)).DateTime;
        }

19 View Source File : XtraUCDirectoryListing.cs
License : MIT License
Project Creator : Analogy-LogViewer

private void treeList1_CustomDrawNodeCell(object sender, DevExpress.XtraTreeList.CustomDrawNodeCellEventArgs e)
        {
            if (e.Column == this.colSize)
            {
                if (e.Node.GetDisplayText("Type") == "File")
                {
                    e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Italic);
                    Int64 size = Convert.ToInt64(e.Node.GetValue("Size"));
                    if (size >= 1024)
                    {
                        e.CellText = string.Format("{0:### ### ###} KB", size / 1024);
                    }
                    else
                    {
                        e.CellText = string.Format("{0} Bytes", size);
                    }
                }
                else
                {
                    e.CellText = String.Format("<{0}>", e.Node.GetDisplayText("Type"));
                }
            }

            if (e.Column == this.colName)
            {
                if (e.Node.GetDisplayText("Type") == "File")
                {
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                }
            }
        }

See More Examples