Example #1
0
        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                var hashCode = 41;
                // Suitable nullity checks etc, of course :)
                if (Id != null)
                {
                    hashCode = hashCode * 59 + Id.GetHashCode();
                }

                hashCode = hashCode * 59 + Severity.GetHashCode();

                hashCode = hashCode * 59 + Passed.GetHashCode();

                hashCode = hashCode * 59 + Override.GetHashCode();
                if (ActualValue != null)
                {
                    hashCode = hashCode * 59 + ActualValue.GetHashCode();
                }
                if (ExpectedValue != null)
                {
                    hashCode = hashCode * 59 + ExpectedValue.GetHashCode();
                }

                hashCode = hashCode * 59 + Comparator.GetHashCode();
                if (Kpi != null)
                {
                    hashCode = hashCode * 59 + Kpi.GetHashCode();
                }
                return(hashCode);
            }
        }
Example #2
0
        public void SampleTest()
        {
            // Arrange
            const bool ExpectedValue = true;

            // Act // Assert
            ExpectedValue.Should().BeTrue();
        }
Example #3
0
 public TemplateToken ExpectValue(params String[] ExpectedValue)
 {
     if (!ExpectedValue.Contains(Current.Text))
     {
         throw (new Exception(String.Format("Expected tokens [{0}] but obtained '{1}'", ExpectedValue.Select(Item => "'" + Item + "'").Implode(","), Current.Text)));
     }
     return(Current);
 }
Example #4
0
        /// <summary>
        /// Compare a ulong value
        /// </summary>
        /// <param name="value">A ulong value</param>
        /// <param name="error">An error describing why it failed</param>
        /// <returns>true if pass, false if fail</returns>
        public bool Compare(ulong value, out string?error)
        {
            if (ExpectedValue is null)
            {
                error = "Null expected value";
                return(false);
            }
            error = "";
            if (Condition == RequirementCondition.OneOf)
            {
                if (ExpectedValue is null || ExpectedValue.Type != JTokenType.Array)
                {
                    error = $"long 'OneOf' comparison requires array token, but token was of type {ExpectedValue?.Type}";
                    return(false);
                }
                JArray?expectedArr = ExpectedValue.ToObject <JArray>();
                if (expectedArr is not null)
                {
                    foreach (JToken?arrayItem in expectedArr)
                    {
                        if (arrayItem.Type == JTokenType.Integer && arrayItem.ToObject <ulong>() == value)
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }

            if (ExpectedValue.Type != JTokenType.Integer)
            {
                error = $"Comparison requires Integer token, but token was of type {ExpectedValue.Type}";
                return(false);
            }
            ulong comparedValue = ExpectedValue.ToObject <ulong>();

            switch (Condition)
            {
            case RequirementCondition.Equals:
                return(value == comparedValue);

            case RequirementCondition.GreaterThan:
                return(value > comparedValue);

            case RequirementCondition.GreaterThanOrEqualTo:
                return(value >= comparedValue);

            case RequirementCondition.LessThan:
                return(value < comparedValue);

            case RequirementCondition.LessThanOrEqualTo:
                return(value <= comparedValue);

            default:
                error = "Bad comparison for ulong value: " + Condition;
                return(false);
            }
        }
Example #5
0
        public override bool Match(ITest test)
        {
            string assemblyName = string.Empty;

            //Assembly fullname is in the format "Assembly-name, meta data ...", so extract the name by looking for the comma
            if (test.TypeInfo != null && test.TypeInfo.Assembly != null && test.TypeInfo.FullName != null)
            {
                assemblyName = test.TypeInfo.Assembly.FullName.Substring(0, test.TypeInfo.Assembly.FullName.IndexOf(',')).TrimEnd(',');
            }
            return(ExpectedValue.Equals(assemblyName, StringComparison.OrdinalIgnoreCase));
        }
Example #6
0
 public bool CheckPolicy(ShoppingCart cart, Guid productGuid, int quantity, BaseUser user, IUnitOfWork unitOfWork)
 {
     foreach (PropertyInfo property in user.GetType().GetProperties())
     {
         if (property.Name == FieldName)
         {
             return(ExpectedValue.Equals(property.GetValue(user)) ? true : false);
         }
     }
     return(false);
 }
Example #7
0
 /// <summary>
 /// Test whether the constraint is matched by the actual value.
 /// This is a template method, which calls the IsMatch method
 /// of the derived class.
 /// </summary>
 /// <param name="actual"></param>
 /// <returns></returns>
 protected override bool Matches(string actual)
 {
     if (_caseInsensitive)
     {
         return(actual != null && actual.ToLower().EndsWith(ExpectedValue.ToLower()));
     }
     else
     {
         return(actual != null && actual.EndsWith(ExpectedValue));
     }
 }
Example #8
0
        /// <summary>
        /// Returns true if Metric instances are equal
        /// </summary>
        /// <param name="other">Instance of Metric to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(Metric other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Id == other.Id ||
                     Id != null &&
                     Id.Equals(other.Id)
                     ) &&
                 (
                     Severity == other.Severity ||

                     Severity.Equals(other.Severity)
                 ) &&
                 (
                     Passed == other.Passed ||

                     Passed.Equals(other.Passed)
                 ) &&
                 (
                     Override == other.Override ||

                     Override.Equals(other.Override)
                 ) &&
                 (
                     ActualValue == other.ActualValue ||
                     ActualValue != null &&
                     ActualValue.Equals(other.ActualValue)
                 ) &&
                 (
                     ExpectedValue == other.ExpectedValue ||
                     ExpectedValue != null &&
                     ExpectedValue.Equals(other.ExpectedValue)
                 ) &&
                 (
                     Comparator == other.Comparator ||

                     Comparator.Equals(other.Comparator)
                 ) &&
                 (
                     Kpi == other.Kpi ||
                     Kpi != null &&
                     Kpi.Equals(other.Kpi)
                 ));
        }
Example #9
0
 public void AddValidation(ClientModelValidationContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     context.Attributes.Add("data-val", "true");
     context.Attributes.Add("data-val-togglerequiredfield", ErrorMessage);
     context.Attributes.Add("data-val-togglerequiredfield-expectedvalue", ExpectedValue?.ToString());
     context.Attributes.Add("data-val-togglerequiredfield-targetfieldname", TargetFieldName);
     context.Attributes.Add("data-val-togglerequiredfield-hiddenclass", HiddenClass);
 }
        private static void AssertValuation(HandlerResponse result)
        {
            // Load valuationItems for the current request Id
            List <ICoreItem> rawValuationItems =
                Engine.Cache.LoadItems <ValuationReport>(Expr.BoolAND(Expr.IsNull(ValueProp.Aggregation),
                                                                      Expr.IsEQU(RequestBase.Prop.RequestId, Guid.Parse(result.RequestId))));

            foreach (ICoreItem valuationItem in rawValuationItems)
            {
                // Extract the valuation report
                var valuation = (ValuationReport)valuationItem.Data;

                // Check that the valuation returned successfully
                var excpName = valuationItem.AppProps.GetValue <string>(WFPropName.ExcpName, null);
                if (excpName != null)
                {
                    // valuation failed - log details
                    var excpText = valuationItem.AppProps.GetValue <string>(WFPropName.ExcpText, null);
                    UTE.Logger.LogError(
                        "Valuation failed:" +
                        "{0}    UniqueId : {1}" +
                        "{0}    Exception: {2}: '{3}'",
                        Environment.NewLine,
                        valuationItem.Name, excpName, excpText);
                    Assert.Fail(excpName, $"Workflow error ({excpName})");
                }

                // check for errors
                var tradeSource = valuationItem.AppProps.GetValue <string>(TradeProp.TradeSource);
                var tradeId     = valuationItem.AppProps.GetValue <string>(TradeProp.TradeId);
                var marketName  = valuationItem.AppProps.GetValue <string>(CurveProp.Market);
                var key         = $"{tradeSource}_{tradeId}_{marketName}_{InstrumentMetrics.NPV}".ToLower();

                // Assert expected value has been supplied
                Assert.IsTrue(ExpectedValues.ContainsKey(key), $"ExpectedValue for key:({key}) is missing.");

                ExpectedValue expectedValue = ExpectedValues[key];

                Quotation quote = valuation.GetFirstQuotationForMetricName(InstrumentMetrics.NPV.ToString());
                Assert.IsNotNull(quote, $"CalculatedValue for key:({key}) is missing.");
                Assert.IsTrue(quote.valueSpecified, $"CalculatedValue for key:({key}) is missing.");

                decimal calculatedNPV = quote.value;
                decimal differenceNPV = expectedValue.OutputNPV - calculatedNPV;

                Assert.IsFalse(System.Math.Abs(differenceNPV) > ToleranceNPV,
                               $"ToleranceExceeded(|{differenceNPV:F0}| > {ToleranceNPV:F0})");
            }
        }
        public void GetActiveDirectorySizeLimit_Should_ReturnExpectedValue()
        {
            // Arrange
            const int ExpectedValue = 1;

            SizeLimitTextBox.Text = ExpectedValue.ToString();

            // Act
            var result = privateObject.Invoke(GetActiveDirectorySizeLimitMethodName) as int?;

            // Assert
            result.ShouldSatisfyAllConditions(
                () => result.ShouldNotBeNull(),
                () => result.Value.ShouldBe(ExpectedValue));
        }
Example #12
0
        /// <inheritdoc />
        public bool Match(JToken token)
        {
            try
            {
                if (!string.IsNullOrEmpty(Variable) && token.Type != JTokenType.Object)
                {
                    return(false);
                }

                var tmp = string.IsNullOrEmpty(Variable) ? token : ((JObject)token).SelectToken(Variable);
                if (tmp == null || tmp.Type != JTokenType.Boolean &&
                    tmp.Type != JTokenType.Date &&
                    tmp.Type != JTokenType.Integer &&
                    tmp.Type != JTokenType.Float &&
                    tmp.Type != JTokenType.String &&
                    tmp.Type != JTokenType.Guid &&
                    tmp.Type != JTokenType.Uri)
                {
                    return(false);
                }

                switch (_operator)
                {
                case Operator.Eq:
                    return(tmp.Value <T>()?.CompareTo(ExpectedValue) == 0);

                case Operator.Gt:
                    return(tmp.Value <T>()?.CompareTo(ExpectedValue) > 0);

                case Operator.Gte:
                    return(tmp.Value <T>()?.CompareTo(ExpectedValue) >= 0);

                case Operator.Lt:
                    return(tmp.Value <T>()?.CompareTo(ExpectedValue) < 0);

                case Operator.Lte:
                    return(tmp.Value <T>()?.CompareTo(ExpectedValue) <= 0);

                case Operator.Match:
                    return(IsMatch(tmp.Value <string>(), ExpectedValue.ToString()));
                }
            }
            catch (FormatException)
            {
            }

            return(false);
        }
Example #13
0
        public override bool Equals(object obj)
        {
            var otherType = typeof(object);

            if (obj != null)
            {
                if (obj.GetType().BaseType != null && obj.GetType().Namespace == "System.Data.Entity.DynamicProxies")
                {
                    otherType = obj.GetType().BaseType;
                }
                else
                {
                    otherType = obj.GetType();
                }
            }
            if (obj == null || typeof(Criteria) != otherType)
            {
                return(false);
            }
            var other = (Criteria)obj;

            if (!Name.Equals(other.Name))
            {
                return(false);
            }
            if (ExpectedValue == null)
            {
                if (other.ExpectedValue != null)
                {
                    return(false);
                }
            }
            else
            if (!ExpectedValue.Equals(other.ExpectedValue))
            {
                return(false);
            }
            if (Location != other.Location)
            {
                return(false);
            }
            if (!Selector.Equals(other.Selector))
            {
                return(false);
            }
            return(true);
        }
        public override void Run()
        {
            var s = Environment.GetEnvironmentVariable(Variable) ?? string.Empty;

            if (!CaseSensitive)
            {
                s             = s.ToUpper();
                ExpectedValue = ExpectedValue.ToUpper();
            }

            if (!s.Contains(ExpectedValue))
            {
                throw new AssertionException(
                          string.Format("Environment variable {0} did not contain expected text [{1}]", Variable,
                                        ExpectedValue));
            }
        }
Example #15
0
        public void VerifyExitingKeyInConfiguration()
        {
            var configuration = new Mock <IConfigurationContext>();

            const string Key                 = "Key1";
            const int    ExpectedValue       = 903;
            var          expectedValueString = ExpectedValue.ToInvariant();

            configuration
            .SetupGet(x => x.AppSettings)
            .Returns(new NameValueCollection {
                { Key, expectedValueString }
            });

            ConfigurationContext.Set(configuration.Object);

            ConfigurationContext.AppSettings.Get <int>(Key).Should().Be(ExpectedValue);
        }
Example #16
0
        public void CreateBody()
        {
            FunctionBody = FunctionHeader;

            FunctionBody += @"
{
            " + Type.Name + " obj= new " + Type.Name + "();" + @"
            " + MethodInfo.ReturnType.ToString() + " retVal = obj." + MethodInfo.Name + "(";
            foreach (object item in Parameters)
            {
                FunctionBody += item.ToString() + ",";
            }
            FunctionBody  = FunctionBody.Substring(0, FunctionBody.Length - 1);//remove trailing comma
            FunctionBody += ");" + @"
            if (retVal==" + ExpectedValue.ToString() + @")
            {
                Assert(true);
            }else{
                Assert(false);
            }
        
                
}";
        }
Example #17
0
        private string TestResultTypeToString()
        {
            switch (TestResultType)
            {
            case TestResultType.Pass:
                return("//  PASS  Value: " + ActualValue);

            case TestResultType.TypeMismatch:
                return($"//  FAIL  Expected: {ExpectedValue} ({ExpectedValue.GetType().Name}), " +
                       $"Actual: {ActualValue} ({ActualValue.GetType().Name})");

            case TestResultType.ValueMismatch:
                return($"//  FAIL  Expected: {ExpectedValue}, Actual: {ActualValue}");

            case TestResultType.Error:
                return($"//  COMPILE/RUNTIME ERROR  Expected: {ExpectedValue}");

            case TestResultType.Ignore:
                return("//  IGNORE  Can not check this type for correctness");

            default:
                return("// Error");
            }
        }
        public void ManualMockingScenarioTest()
        {
            ManualMockSession sess = new ManualMockSession();

            Sample.ICurrencyService cv = (Sample.ICurrencyService)sess.Mock(typeof(Sample.ICurrencyService), "cs")
                                         .ExpectAndReturn("ConvertAmount", 50m)
                                         .ExpectAndReturn("ConvertAmount", 80m).WithArguments(50m, ExpectedValue.OfType(typeof(Sample.CurrencyUnit)), ExpectedValue.OfType(typeof(Sample.CurrencyUnit)))
                                         .ExpectAndReturn("ConvertAmount", 30m).WithArguments(ExpectedValue.Any, ExpectedValue.OfType(typeof(Sample.CurrencyUnit)), Sample.CurrencyUnit.EUR).RepeatTimes(3)
                                         .Mock;
            Sample.CurrencyServiceFactory.NextInstance = cv;
            Sample.Account acc = new Sample.Account(Sample.CurrencyUnit.EUR);
            acc.Deposit(100m);
            Assert.AreEqual(100m, acc.Balance);
            acc.SwitchCurrency(Sample.CurrencyUnit.GBP);
            Assert.AreEqual(50m, acc.Balance);
            acc.SwitchCurrency(Sample.CurrencyUnit.USD);
            Assert.AreEqual(80m, acc.Balance);
            acc.SwitchCurrency(Sample.CurrencyUnit.EUR);
            Assert.AreEqual(30m, acc.Balance);
            acc.SwitchCurrency(Sample.CurrencyUnit.EUR);
            Assert.AreEqual(30m, acc.Balance);
            try
            {
                acc.SwitchCurrency(Sample.CurrencyUnit.NULL);
                Assert.Fail("Exception expected.");
            }
            catch (ReplayMockException) { }
            sess.ValidateSession();
        }
Example #19
0
 public ParseError(ExpectedValue expected, GotValue got, ILocation location, Tuple <TokenList, TokenList, AST> previous) : base(location)
 {
     Expected = expected;
     Got      = got;
     Previous = previous;
 }
Example #20
0
        public void ConstructorConvertsMetadataValuesToParameterTypes()
        {
            using (var transformation = new FakeTransformationWithIntParameter())
            {
                const int    ExpectedValue = 42;
                const string ParameterName = "IntParameter";
                transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName?ExpectedValue.ToString(CultureInfo.InvariantCulture) : null;

                using (new TransformationContext(transformation, transformation.GenerationEnvironment))
                {
                    Assert.AreEqual(ExpectedValue, transformation.Session[ParameterName]);
                }
            }
        }
Example #21
0
        public async Task <IActionResult> PostOrder([FromHeader] string Authorization, [FromBody] OrderPost orderPost)
        {
            try
            {
                long timestamp          = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                long markpricetimestamp = timestamp;// - DateTime.UtcNow.Second;

                if (Request.ContentType == "application/json")
                {
                    ;
                }
                else
                {
                    return(BadRequest("improper content type"));
                }

                if (orderPost.OrderType == "limit")
                {
                    if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && string.IsNullOrEmpty(orderPost.Price) && orderPost.OrderQuantity == null)
                    {
                        return(BadRequest("bad params"));
                    }
                }
                else if (orderPost.OrderType == "market")
                {
                    if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && orderPost.OrderQuantity == null)
                    {
                        return(BadRequest("bad params"));
                    }
                }
                else
                {
                    return(BadRequest("missing params"));
                }

                Console.WriteLine(orderPost.Contract + orderPost.OrderQuantity + orderPost.OrderType + orderPost.Side);
                if (string.IsNullOrEmpty(orderPost.Contract) || string.IsNullOrEmpty(orderPost.OrderType) || string.IsNullOrEmpty(orderPost.Side) || orderPost.OrderQuantity == null)
                {
                    return(BadRequest("missing variables"));
                }

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Table    SPXMarkTable  = Table.LoadTable(amazonDynamoDBClient, "SPXMarkPrice");
                Document searchdetails = new Document();

                orderPost.OrderType = orderPost.OrderType.ToLower();

                int    orderId;
                string socket;

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id)
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }

                    // verifiy valid account balance
                    Document userdetails = await UserTable.GetItemAsync(searchdetails["Email"].ToString());

                    Document markprice = new Document();
                    markpricetimestamp = markpricetimestamp - (markpricetimestamp % 5);
                    try { markprice = await SPXMarkTable.GetItemAsync(markpricetimestamp.ToString()); markprice["BTCPrice"].ToString(); }
                    catch { try { markpricetimestamp -= 5; markprice = await SPXMarkTable.GetItemAsync((markpricetimestamp).ToString()); markprice["BTCPrice"].ToString(); } catch { Console.WriteLine("bigbad"); } }

                    double availablebalance = searchdetails["AvailableBalance"].AsDouble();
                    if (orderPost.OrderQuantity > ((availablebalance * markprice["BTCPrice"].AsDouble()) * 100))
                    {
                        return(BadRequest("bad amount"));
                    }

                    // atomic id generate
                    Table    idgenerator = Table.LoadTable(amazonDynamoDBClient, "IdGenerator");
                    Document currentid   = await idgenerator.GetItemAsync("Main");

                    Document newid = new Document();
                    newid["Id"] = "Main";

                    double count = currentid["Count"].AsDouble();
                    count         += 1;
                    newid["Count"] = count.ToString();

                    UpdateItemOperationConfig updateItemOperationConfig = new UpdateItemOperationConfig();
                    ExpectedValue             expected = new ExpectedValue(ScanOperator.Equal);
                    updateItemOperationConfig.Expected = currentid;

                    try
                    {
                        Document test = await idgenerator.UpdateItemAsync(newid, updateItemOperationConfig);

                        orderId = (int)count;
                    }
                    catch
                    {
                        return(BadRequest("please try again"));
                    }

                    Table    orderreg = Table.LoadTable(amazonDynamoDBClient, "OrderRegistry");
                    Document addorder = new Document();
                    addorder["Id"]    = orderId.ToString();
                    addorder["Email"] = searchdetails["Email"].ToString();
                    addorder["Side"]  = orderPost.Side.ToString();
                    if (orderPost.OrderType == "limit")
                    {
                        addorder["Price"] = orderPost.Price.ToString();
                    }
                    addorder["OrderQuantity"] = orderPost.OrderQuantity.ToString();
                    addorder["Contract"]      = orderPost.Contract;
                    addorder["OrderType"]     = orderPost.OrderType;
                    addorder["Status"]        = "open";
                    addorder["Timestamp"]     = timestamp.ToString();
                    //addorder["Add"] = "true";
                    await orderreg.PutItemAsync(addorder);

                    // send tcp message to engine
                    try
                    {
                        TcpClient tcpclnt = new TcpClient();
                        Console.WriteLine("Connecting.....");

                        tcpclnt.Connect("52.213.34.99", port);
                        // use the ipaddress as in the server program

                        Console.WriteLine("Connected");
                        Console.Write("Enter the string to be transmitted : ");
                        var    enginepayload = new object();
                        double spymark       = markprice["SPXPrice"].AsDouble();
                        spymark  = Math.Round(spymark);
                        spymark *= 100;

                        if (orderPost.OrderType == "limit")
                        {
                            enginepayload = new
                            {
                                Method        = "Post",
                                Side          = orderPost.Side,
                                Id            = orderId.ToString(),
                                Price         = orderPost.Price,
                                OrderQuantity = orderPost.OrderQuantity.ToString(),
                                OrderType     = orderPost.OrderType,
                                Contract      = orderPost.Contract,
                                Secret        = "secret",
                                //Timestamp = timestamp.ToString(),
                                //User = searchdetails["Email"].ToString(),
                                //AvailableBalance = searchdetails["AvailableBalance"].ToString()
                            };
                        }
                        else if (orderPost.OrderType == "market")
                        {
                            enginepayload = new
                            {
                                Method        = "Post",
                                Side          = orderPost.Side,
                                Id            = orderId.ToString(),
                                OrderQuantity = orderPost.OrderQuantity.ToString(),
                                Slippage      = 99999.ToString(),
                                OrderType     = orderPost.OrderType,
                                Contract      = orderPost.Contract,
                                Secret        = "secret",
                                //Timestamp = timestamp.ToString(),
                                //User = searchdetails["Email"].ToString(),
                                //AvailableBalance = searchdetails["AvailableBalance"].ToString()
                            };
                        }
                        else
                        {
                            return(BadRequest("invalid order type"));
                        }

                        using (SslStream sslStream = new SslStream(tcpclnt.GetStream(), false,
                                                                   new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                        {
                            sslStream.AuthenticateAsClient("52.213.34.99");
                            // This is where you read and send data

                            String str = "enginekey" + JsonConvert.SerializeObject(enginepayload);
                            //Stream stm = tcpclnt.GetStream();

                            ASCIIEncoding asen = new ASCIIEncoding();
                            byte[]        ba   = asen.GetBytes(str);
                            Console.WriteLine("Transmitting.....");

                            sslStream.Write(ba, 0, ba.Length);
                            //sslStream.Close();

                            /*byte[] bb = new byte[1000];
                             * int k = await sslStream.ReadAsync(bb, 0, 1000);
                             *
                             * var socketresult = Encoding.UTF8.GetString(bb).TrimEnd('\0');
                             * Console.WriteLine(socketresult);
                             * socket = socketresult;*/
                        }
                        tcpclnt.Close();
                    }

                    catch (Exception e)
                    {
                        Console.WriteLine("Error..... " + e.StackTrace);
                        return(BadRequest("error with engine"));
                    }
                }
                catch
                {
                    return(BadRequest("failed processing"));
                }

                var    returnobj  = new { Id = orderId, Timestamp = markpricetimestamp.ToString(), Message = "transmitted", Result = "sucess" };
                string returnjson = JsonConvert.SerializeObject(returnobj);
                return(Content(returnjson, "application/json"));
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }
Example #22
0
 public override int GetHashCode()
 {
     return(Selector.GetHashCode() + ExpectedValue.GetHashCode());
 }
Example #23
0
        }                                               // Has a public setter so that individual test cases can override. By default, it's set to the Utf8 character length of Text

        public sealed override string ToString()
        {
            //
            // Take good care of this method: it affects Xunit output and makes a lot of difference in how annoying test investigations are.
            //

            string formatString = (FormatSymbol == default) ?
                                  "default" :
                                  FormatSymbol.ToString();

            return($"[Parse{typeof(T).Name} '{Text}',{formatString} to {(ExpectedSuccess ? ExpectedValue.DisplayString() : "(should-not-parse)")})]");
        }
Example #24
0
 public bool Equals(Distinction other) =>
 other != null &&
 (ReferenceEquals(this, other) ||
  Name.Equals(other.Name) &&
  ActuallyValue.Equals(other.ActuallyValue) &&
  ExpectedValue.Equals(other.ExpectedValue));
        /// <summary>
        /// Load the expected values for the test trades
        /// </summary>
        /// <returns></returns>
        private static IDictionary <string, ExpectedValue> LoadExpectedValues()
        {
            // load expected values
            IDictionary <string, ExpectedValue> expectedValues = new Dictionary <string, ExpectedValue>();

            using (var csvFile = new StringReader(RegressionTestDataLoader.GetExpectedResults("ExpectedNPVs.csv")))
            {
                // CSV headers
                int colSystem          = -1;
                int colTradeId         = -1;
                int colMarketName      = -1;
                int colMetricSourceNpv = -1;
                int colMetricOutputNpv = -1;
                int colIRScenario      = -1;
                int colFXScenario      = -1;
                int colStressNPVDelta  = -1;

                // Line Id
                int lineNum = 0;

                // parse all lines
                // - 1st non-comment line is headings line
                string rawline;
                while ((rawline = csvFile.ReadLine()) != null)
                {
                    string line = rawline.Trim();
                    if ((line.Length == 0) || (line[0] == '#'))
                    {
                        // skip comment lines
                        continue;
                    }

                    if (lineNum == 0)
                    {
                        // process heading (line 0)
                        List <string> headings = line.Split(',').ToList();
                        colSystem          = GetColumn(headings, "System");
                        colTradeId         = GetColumn(headings, "TradeId");
                        colMarketName      = GetColumn(headings, "MarketName");
                        colMetricSourceNpv = GetColumn(headings, "SourceNPV");
                        colMetricOutputNpv = GetColumn(headings, "OutputNPV");
                        // optional stress scenarios and NPV variation
                        colIRScenario     = GetColumn(headings, "IRScenario");
                        colFXScenario     = GetColumn(headings, "FXScenario");
                        colStressNPVDelta = GetColumn(headings, "StressNPVDelta");
                    }
                    else
                    {
                        // process data
                        string key = "(undefined)";
                        try
                        {
                            string[] columns = line.Split(',');

                            // Generate the key
                            string tradeSource = columns[colSystem];
                            string tradeId     = columns[colTradeId];
                            string marketName  = columns[colMarketName];
                            key = String.Format("{0}_{1}_{2}_{3}", tradeSource, tradeId, marketName, InstrumentMetrics.NPV).ToLower();

                            // Add the expected values
                            decimal sourceValue = Convert.ToDecimal(columns[colMetricSourceNpv]);
                            decimal outputValue = Convert.ToDecimal(columns[colMetricOutputNpv]);
                            expectedValues[key] = new ExpectedValue
                            {
                                SourceNPV = sourceValue,
                                OutputNPV = outputValue
                            };
                        }
                        catch (Exception fe)
                        {
                            // may not be a problem
                            UTE.Logger.LogWarning("Failed to load expected value '{0}' (line[{1} = '{2}']) {3}: {4}",
                                                  key, lineNum, line, fe.GetType().Name, fe.Message);
                        }
                    }
                    lineNum++;
                } // while
            }
            return(expectedValues);
        }
Example #26
0
        public async Task <IActionResult> Gete([FromHeader] string key, [FromHeader] string payload)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;

                if (key != "enginekey")
                {
                    return(BadRequest("bad"));
                }
                Console.WriteLine(payload);
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                Table           table       = Table.LoadTable(client, "OrderRegistry");
                List <Document> docs        = new List <Document>();

                // begin parse payload
                int i = 0;
                if (payload[i] != '[')
                {
                    throw new Exception();
                }
                Document doc, docother = new Document();
                string   Id = new string(""); string Quantity = new string(""); string Price = new string(""); string Executed = new string(""); string OtherOrder = new string("");
                i += 1;
                while (true && i < payload.Length)
                {
                    if (payload[i] == ',')
                    {
                        i += 1; break;
                    }
                    Id += payload[i];
                    i  += 1;
                }
                while (true && i < payload.Length)
                {
                    if (payload[i] == ',')
                    {
                        i += 1; break;
                    }
                    Quantity += payload[i];
                    i        += 1;
                }
                while (true && i < payload.Length)
                {
                    if (payload[i] == ',')
                    {
                        i += 1; break;
                    }
                    Price += payload[i];
                    i     += 1;
                }
                while (true && i < payload.Length)
                {
                    if (payload[i] == ',')
                    {
                        i += 1; break;
                    }
                    Executed += payload[i];
                    i        += 1;
                }
                while (true && i < payload.Length)
                {
                    if (payload[i] == ']')
                    {
                        break;
                    }
                    OtherOrder += payload[i];
                    i          += 1;
                }
                double executed;
                try { executed = double.Parse(Executed); } catch { return(BadRequest("error parse")); }
                // end parse payload

                doc = await table.GetItemAsync(Id);

                docother = await table.GetItemAsync(OtherOrder);

                if (doc["Email"].ToString() == docother["Email"].ToString()) // self fill
                {
                    if (doc["OrderType"].ToString() == "limit")
                    {
                        double currentself = doc["OrderQuantity"].AsDouble();

                        currentself = currentself - executed;
                        Document currentselfdoc = new Document();
                        currentselfdoc["Id"]            = Id.ToString();
                        currentselfdoc["OrderQuantity"] = currentself.ToString();
                        await table.UpdateItemAsync(currentselfdoc);

                        return(Ok());
                    }
                    return(Ok());
                }

                doc["Price"] = Price;

                if (doc["OrderType"].ToString() == "market") // recent orders
                {
                    Document recentorder = new Document();
                    recentorder["Timestamp"] = timestamp.ToString();
                    recentorder["Price"]     = Price.ToString();
                    recentorder["Quantity"]  = Executed.ToString();
                    Table recentordertable = Table.LoadTable(client, "RecentOrdersSPXUSD");
                    await recentordertable.PutItemAsync(recentorder);
                }

                double price; double.TryParse(Price, out price);
                await table.UpdateItemAsync(doc);

                Table    postable = Table.LoadTable(client, "PositionRegistry");
                Document posdoc   = await postable.GetItemAsync(doc["Email"].ToString());

                Document posupdate = new Document();
                double   pos;
                try
                {
                    posdoc["POSSPXUSD"].ToString();
                    if (posdoc["POSSPXUSD"].ToString() == "0")
                    {
                        pos = 0;
                    }
                    pos = posdoc["POSSPXUSD"].AsDouble();
                }
                catch //never position or 0 position
                {
                    await postable.PutItemAsync(new Document()
                    {
                        ["Email"] = doc["Email"].ToString()
                    });

                    pos = 0;
                }


                if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "limit")
                {
                    pos = pos + executed;
                }
                else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "limit")
                {
                    pos       = pos - executed;
                    executed *= -1;
                }
                else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "market")
                {
                    pos       = pos - executed;
                    executed *= -1;
                }
                else if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "market")
                {
                    pos = pos + executed;
                }
                else
                {
                    return(BadRequest("error"));
                }

                posupdate["Email"]     = doc["Email"].ToString();
                posupdate["POSSPXUSD"] = pos.ToString();
                //await postable.UpdateItemAsync(posupdate);

                if (pos == 0)
                {
                    posupdate["POSSPXUSDEntry"] = "na";
                }                                                                                                          // closed out pos
                else if ((pos - executed) == 0 || (pos + executed) == 0 || (pos - executed) == 0 || (pos + executed) == 0) /*open pos from 0*/
                {
                    posupdate["POSSPXUSDEntry"] = Price;
                }
                else if ((pos - executed) > 0 || (pos + executed) < 0 || (pos - executed) < 0 || (pos + executed) > 0)                                                                                                                                                      /*pre-existing pos non zero*/
                {
                    if ((Math.Abs(posdoc["POSSPXUSD"].AsDouble()) > Math.Abs(executed) || (Math.Abs(posdoc["POSSPXUSD"].AsDouble()) < Math.Abs(executed) && ((posdoc["POSSPXUSD"].AsDouble() > 0 && executed > 0) || posdoc["POSSPXUSD"].AsDouble() < 0 && executed < 0)))) // reduce or add
                    {
                        if (pos > 0)
                        {
                            double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed);
                            if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/
                            {
                                posupdate["POSSPXUSDEntry"] = newentry.ToString();
                            }
                            else // profit/loss
                            {
                            }
                        }
                        else if (pos < 0)
                        {
                            double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed);
                            if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/
                            {
                                posupdate["POSSPXUSDEntry"] = newentry.ToString();
                            }
                            else // profit/loss
                            {
                            }
                        }
                        else
                        {
                            Console.WriteLine("error calc entry");
                        }
                    }
                    else // reduce and add
                    {
                        if (pos > 0)
                        {
                            //reduce
                            double posremain = (executed * -1) - posdoc["POSSPXUSD"].AsDouble();

                            //add
                            posupdate["POSSPXUSD"]      = (0 - posremain).ToString();
                            posupdate["POSSPXUSDEntry"] = Price;
                        }
                        else if (pos < 0)
                        {
                            //reduce
                            double posremain = executed - (posdoc["POSSPXUSD"].AsDouble() * -1);

                            //add
                            posupdate["POSSPXUSD"]      = (0 + posremain).ToString();
                            posupdate["POSSPXUSDEntry"] = Price;
                        }
                    }
                }

                // pull from database and calculate new position value.
                UpdateItemOperationConfig update   = new UpdateItemOperationConfig();
                ExpectedValue             expected = new ExpectedValue(ScanOperator.Equal);
                update.Expected = posdoc;
                try
                { Document test = await postable.UpdateItemAsync(posupdate, update); }
                catch
                {
                    Thread.Sleep(20);
                    Console.WriteLine("error");
                    posdoc = await postable.GetItemAsync(doc["Email"].ToString());

                    posupdate = new Document();

                    try
                    {
                        posdoc["POSSPXUSD"].ToString();
                        if (posdoc["POSSPXUSD"].ToString() == "0")
                        {
                            throw new Exception();
                        }
                        pos = posdoc["POSSPXUSD"].AsDouble();
                    }
                    catch //never position or 0 position
                    {
                        pos = 0;
                    }

                    try { executed = double.Parse(Executed); } catch { return(BadRequest("error parse")); }

                    if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "limit")
                    {
                        pos = pos + executed;
                    }
                    else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "limit")
                    {
                        pos       = pos - executed;
                        executed *= -1;
                    }
                    else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "market")
                    {
                        pos       = pos - executed;
                        executed *= -1;
                    }
                    else if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "market")
                    {
                        pos = pos + executed;
                    }
                    else
                    {
                        return(BadRequest("error"));
                    }

                    posupdate["Email"]     = doc["Email"].ToString();
                    posupdate["POSSPXUSD"] = pos.ToString();

                    if (pos == 0)
                    {
                        posupdate["POSSPXUSDEntry"] = "na";
                    }                                                                                                          // closed out pos
                    else if ((pos - executed) == 0 || (pos + executed) == 0 || (pos - executed) == 0 || (pos + executed) == 0) /*open pos from 0*/
                    {
                        posupdate["POSSPXUSDEntry"] = Price;
                    }
                    else if ((pos - executed) > 0 || (pos + executed) < 0 || (pos - executed) < 0 || (pos + executed) > 0)                                                                                                                                                      /*pre-existing pos non zero*/
                    {
                        if ((Math.Abs(posdoc["POSSPXUSD"].AsDouble()) > Math.Abs(executed) || (Math.Abs(posdoc["POSSPXUSD"].AsDouble()) < Math.Abs(executed) && ((posdoc["POSSPXUSD"].AsDouble() > 0 && executed > 0) || posdoc["POSSPXUSD"].AsDouble() < 0 && executed < 0)))) // reduce or add
                        {
                            if (pos > 0)
                            {
                                double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed);
                                if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/
                                {
                                    posupdate["POSSPXUSDEntry"] = newentry.ToString();
                                }
                                else // profit/loss
                                {
                                }
                            }
                            else if (pos < 0)
                            {
                                double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed);
                                if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/
                                {
                                    posupdate["POSSPXUSDEntry"] = newentry.ToString();
                                }
                                else // profit/loss
                                {
                                }
                            }
                            else
                            {
                                Console.WriteLine("error calc entry");
                            }
                        }
                        else // reduce and add
                        {
                            if (pos > 0)
                            {
                                //reduce
                                double posremain = (executed * -1) - posdoc["POSSPXUSD"].AsDouble();

                                //add
                                posupdate["POSSPXUSD"]      = (0 - posremain).ToString();
                                posupdate["POSSPXUSDEntry"] = Price;
                            }
                            else if (pos < 0)
                            {
                                //reduce
                                double posremain = executed - (posdoc["POSSPXUSD"].AsDouble() * -1);

                                //add
                                posupdate["POSSPXUSD"]      = (0 + posremain).ToString();
                                posupdate["POSSPXUSDEntry"] = Price;
                            }
                        }
                    }

                    await postable.UpdateItemAsync(posupdate);
                }

                return(Ok());
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }