Esempio n. 1
0
        public void AsynchronousCancels()
        {
            var socket = new MockSessionSocket();
            var mockMarketUid = new Uid(317002);
            var mockContractUid = new Uid(608008);
            var mockOrder = new NewOrder {
                Type = OrderCreateType.Limit,
                Market = mockMarketUid,
                Contract = mockContractUid,
                Side = Side.Buy,
                Quantity = new Quantity(QuantityType.PayoffCurrency, 60000),
                Price = new Price(PriceType.PercentOdds, 5714)
            };

            socket.Expect(Payloads.Sequenced(Payloads.Login("mockuser", "mockpassword"), 1));
            socket.Next(Payloads.Sequenced(Payloads.LoginResponse("00000000-0000-0000-0000-000000658a8", 2), 1));
            socket.Expect(Payloads.Sequenced(Payloads.OrderCreate(mockOrder), 2));
            socket.Next(Payloads.Sequenced(Payloads.OrderAccepted(new Uid(82892989397900053), 2), 2));
            socket.Next(Payloads.Sequenced(Payloads.OrderCancelled(new Uid(82892989397900053)), 3));
            socket.Expect(Payloads.Sequenced(Payloads.Logout(), 3));
            socket.Next(Payloads.Sequenced(Payloads.LogoutConfirmation(), 4));

            var session = new SeqSession(socket, SessionSettings);
            IClientSettings mockSettings = new ClientSettings(SocketSettings, SessionSettings);

            using (var client = SmarketsClient.Create(mockSettings, session))
            {
                client.Login();
                var mockOrderResponse1 = client.CreateOrder(mockOrder);
                Assert.True(mockOrderResponse1.WaitOne(DataWait));
                Assert.NotNull(mockOrderResponse1.Data);
                client.Logout();
                Assert.Equal(mockOrderResponse1.Data.State.Status, OrderStatus.Cancelled);
            }
        }
Esempio n. 2
0
 internal Order(
     Price price, OrderState state, Uid market, Uid contract, Side side)
 {
     Price = price;
     State = state;
     Market = market;
     Contract = contract;
     Side = side;
 }
Esempio n. 3
0
 public static Payload AccountStateRequest(Uid? account)
 {
     var request = new AccountStateRequest();
     if (account != null)
         request.Account = account.Value.ToUuid128();
     return new Payload {
         Type = PayloadType.PAYLOADACCOUNTSTATEREQUEST,
         AccountStateRequest = request
     };
 }
Esempio n. 4
0
 private MarketQuotes(
     Uid uid,
     ContractQuotesMap contractQuotes,
     PriceType priceType,
     QuantityType quantityType)
 {
     _uid = uid;
     _contractQuotes = contractQuotes;
     _priceType = priceType;
     _quantityType = quantityType;
 }
Esempio n. 5
0
 public Order ToOrder(Uid orderUid)
 {
     return new Order(
         Price, new OrderState(
             orderUid,
             Type,
             OrderStatus.Live,
             Quantity,
             SetoMap.ToMicroseconds(DateTime.UtcNow),
             new Quantity(Quantity.Type, 0)),
         Market, Contract, Side);
 }
Esempio n. 6
0
 private ContractInfo(
     Uid uid,
     string type,
     string slug,
     string name,
     string shortname,
     IEnumerable<KeyValuePair<Uid, string>> entities)
 {
     _uid = uid;
     _type = type;
     _slug = slug;
     _name = name;
     _shortname = shortname;
     _entities = entities.ToList();
 }
Esempio n. 7
0
        public static Payload ContractQuotes(Uid contract,
                                             IEnumerable<Proto.Seto.Quote> bids,
                                             IEnumerable<Proto.Seto.Quote> offers)
        {
            var payload = new Payload {
                Type = PayloadType.PAYLOADCONTRACTQUOTES,
                ContractQuotes = new Proto.Seto.ContractQuotes {
                    Contract = contract.ToUuid128()
                }
            };

            payload.ContractQuotes.Bids.AddRange(bids);
            payload.ContractQuotes.Offers.AddRange(offers);

            return payload;
        }
Esempio n. 8
0
 private ContractQuotes(
     Uid uid,
     IEnumerable<Quote> bids,
     IEnumerable<Quote> offers,
     IEnumerable<Execution> executions,
     Execution? lastExecution,
     PriceType priceType,
     QuantityType quantityType)
 {
     _uid = uid;
     _bids = GetQuoteDict(bids, Price.BidOrder);
     _offers = GetQuoteDict(offers, Price.OfferOrder);
     _executions = new List<Execution>(executions);
     _lastExecution = lastExecution;
     _priceType = priceType;
     _quantityType = quantityType;
 }
Esempio n. 9
0
 private MarketInfo(
     Uid uid,
     string slug,
     string name,
     string shortname,
     DateTime? startDateTime,
     DateTime? endDateTime,
     IEnumerable<KeyValuePair<Uid, string>> entities,
     IEnumerable<Uid> contracts)
 {
     _uid = uid;
     _slug = slug;
     _name = name;
     _shortname = shortname;
     _startDateTime = startDateTime;
     _endDateTime = endDateTime;
     _entities = entities;
     _contracts = contracts;
 }
Esempio n. 10
0
 public void HexTest()
 {
     var uid1 = new Uid(3408723498, 20347893249);
     const string uid1Hex = "0000cb2cfe2a00000004bcd43601acc1";
     var uid2 = new Uid(1);
     const string uid2Hex = "0000000000000000000000000001acc1";
     Assert.Equal(uid1.ToHex(UidTag.Account), uid1Hex);
     Assert.Equal(uid2.ToHex(UidTag.Account), uid2Hex);
     UidTag tag;
     var uid3 = Uid.ParseHex(uid1Hex, out tag);
     Assert.Equal(uid1, uid3);
     Assert.Equal(tag, UidTag.Account);
     var uid4 = Uid.ParseHex(uid2Hex, out tag);
     Assert.Equal(uid2, uid4);
     Assert.Equal(tag, UidTag.Account);
     Assert.Throws<ArgumentException>(() => Uid.ParseHex("ffacc2", out tag));
     Assert.Throws<ArgumentException>(() => Uid.ParseHex("ggacc1", out tag));
     Assert.Throws<ArgumentException>(() => Uid.ParseHex("", out tag));
     Assert.Throws<ArgumentNullException>(() => Uid.ParseHex(null, out tag));
 }
Esempio n. 11
0
 private EventInfo(
     Uid uid,
     string name,
     string type,
     string category,
     string slug,
     Uid? parentUid,
     DateTime? startDateTime,
     DateTime? endDateTime,
     string description,
     IEnumerable<KeyValuePair<Uid, String>> entities,
     IEnumerable<Uid> markets)
 {
     _uid = uid;
     _name = name;
     _type = type;
     _category = category;
     _slug = slug;
     _parentUid = parentUid;
     _startDateTime = startDateTime;
     _endDateTime = endDateTime;
     _description = description;
     _entities = entities;
     _markets = markets;
 }
Esempio n. 12
0
 public Uid RemoveAttributeValues(ObjectClass oclass, Uid uid, ICollection <ConnectorAttribute> valuesToRemove, OperationOptions options)
 {
     return(Update(UpdateType.DELETE, oclass, uid, valuesToRemove, options));
 }
Esempio n. 13
0
 public static Payload OrdersForMarketRequest(Uid market)
 {
     return new Payload {
         Type = PayloadType.PAYLOADORDERSFORMARKETREQUEST,
             OrdersForMarketRequest = new OrdersForMarketRequest {
             Market = market.ToUuid128()
         }
     };
 }
Esempio n. 14
0
 public static Payload OrderCancel(Uid order)
 {
     return new Payload {
         Type = PayloadType.PAYLOADORDERCANCEL,
             OrderCancel = new OrderCancel {
             Order = order.ToUuid128()
         }
     };
 }
Esempio n. 15
0
 public static Payload MarketUnsubscribe(Uid market)
 {
     return new Payload {
         Type = PayloadType.PAYLOADMARKETUNSUBSCRIBE,
         MarketUnsubscribe = new MarketUnsubscribe {
             Market = market.ToUuid128()
         }
     };
 }
Esempio n. 16
0
 public static Payload MarketQuotes(Uid market)
 {
     return new Payload {
         Type = PayloadType.PAYLOADMARKETQUOTES,
         MarketQuotes = new Proto.Seto.MarketQuotes {
             Market = market.ToUuid128(),
             PriceType = Proto.Seto.PriceType.PRICEPERCENTODDS,
             QuantityType = Proto.Seto.QuantityType.QUANTITYPAYOFFCURRENCY
         }
     };
 }
Esempio n. 17
0
 internal static ContractQuotes Empty(Uid uid, PriceType priceType, QuantityType quantityType)
 {
     return new ContractQuotes(
         uid,
         Enumerable.Empty<Quote>(),
         Enumerable.Empty<Quote>(),
         Enumerable.Empty<Execution>(),
         null,
         priceType,
         quantityType);
 }
Esempio n. 18
0
 internal ContractQuotes GetContract(Uid uid)
 {
     if (!_contractQuotes.ContainsKey(uid))
         _contractQuotes.Add(uid);
     return _contractQuotes[uid];
 }
Esempio n. 19
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Kpn.Length != 0)
            {
                hash ^= Kpn.GetHashCode();
            }
            if (Kpf.Length != 0)
            {
                hash ^= Kpf.GetHashCode();
            }
            if (SubBiz.Length != 0)
            {
                hash ^= SubBiz.GetHashCode();
            }
            if (Uid != 0L)
            {
                hash ^= Uid.GetHashCode();
            }
            if (Did.Length != 0)
            {
                hash ^= Did.GetHashCode();
            }
            if (ClientIp != 0L)
            {
                hash ^= ClientIp.GetHashCode();
            }
            if (AppVer.Length != 0)
            {
                hash ^= AppVer.GetHashCode();
            }
            if (Ver.Length != 0)
            {
                hash ^= Ver.GetHashCode();
            }
            if (Lat.Length != 0)
            {
                hash ^= Lat.GetHashCode();
            }
            if (Lon.Length != 0)
            {
                hash ^= Lon.GetHashCode();
            }
            if (Mod.Length != 0)
            {
                hash ^= Mod.GetHashCode();
            }
            if (Net.Length != 0)
            {
                hash ^= Net.GetHashCode();
            }
            if (Sys.Length != 0)
            {
                hash ^= Sys.GetHashCode();
            }
            if (C.Length != 0)
            {
                hash ^= C.GetHashCode();
            }
            if (Language.Length != 0)
            {
                hash ^= Language.GetHashCode();
            }
            if (CountryCode.Length != 0)
            {
                hash ^= CountryCode.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        internal Uid ValidateUserCredentials(string username, string password)
        {
            IntPtr tokenHandle = new IntPtr(0);

            try
            {
                const int LOGON32_PROVIDER_DEFAULT  = 0;
                const int LOGON32_LOGON_INTERACTIVE = 2;
                const int LOGON32_LOGON_NETWORK     = 3;

                tokenHandle = IntPtr.Zero;
                bool success = LogonUser(username, null, password, LOGON32_LOGON_NETWORK,
                                         LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
                if (!success)
                {
                    int lastWindowsError = Marshal.GetLastWin32Error();
                    if (lastWindowsError == ERROR_PASSWORD_MUST_CHANGE)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_PasswordMustChange",
                                                                                 "User password must be changed");

                        PasswordExpiredException pweException = new PasswordExpiredException(message);
                        pweException.Uid = GetUidFromSamAccountName(username);

                        throw pweException;
                    }
                    else if (lastWindowsError == ERROR_LOGON_FAILURE)
                    {
                        string message = _configuration.ConnectorMessages.Format(
                            "ex_InvalidCredentials", "Invalid credentials supplied for user {0}", username);

                        throw new InvalidCredentialException(message);
                    }
                    else if (lastWindowsError == ERROR_ACCOUNT_LOCKED_OUT)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_AccountLocked",
                                                                                 "User's account has been locked");
                        throw new InvalidCredentialException(message);
                    }
                    else if (lastWindowsError == ERROR_ACCOUNT_EXPIRED)
                    {
                        string message = _configuration.ConnectorMessages.Format("ex_AccountExpired",
                                                                                 "User account expired for user {0}", username);
                        throw new InvalidCredentialException(message);
                    }
                    else
                    {
                        // no idea what could have gone wrong, so log it and throw connector error
                        string errorMessage = string.Format(
                            "Windows returned error number {0} from LogonUser call", lastWindowsError);
                        Trace.TraceError(errorMessage);
                        //TODO: Add localization
                        throw new ConnectorException(errorMessage);
                    }
                }
                WindowsIdentity windowsId = new WindowsIdentity(tokenHandle);
                Uid             uid       = GetUidFromSid(windowsId.User);
                return(uid);
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                {
                    CloseHandle(tokenHandle);
                }
            }
        }
Esempio n. 21
0
 [DebuggerStepThrough] public CommandParameter(string key, Uid value)
 {
     Key = key; Value = Serialize(value.Value);
 }
Esempio n. 22
0
 [DebuggerStepThrough] public TsCommand Add(string key, Uid value) => Add(new CommandParameter(key, value));
Esempio n. 23
0
		public Address(Uid uid)
		{
			this.uid = uid;
		}
Esempio n. 24
0
		public Address()
		{
			uid = Uid.NewUid();
		}
 public static UserId ConvertAccountUidToFsUserId(Uid uid)
 {
     return(new UserId(uid.Id.High, uid.Id.Low));
 }
Esempio n. 26
0
 private void AddDataElementToXml(XmlTextWriter xml,
                                  DataElement element)
 {
     xml.WriteStartElement("DataElement");
     xml.WriteAttributeString("streamPosition", element.StreamPosition.ToString());
     xml.WriteElementString("Tag", element.Tag.ToString());
     xml.WriteElementString("VR", element.VR.ToString());
     xml.WriteElementString("VM",
                            element.Tag.GetDictionaryEntry().VM.ToString());
     xml.WriteElementString("Description",
                            element.Tag.GetDictionaryEntry().Description);
     xml.WriteElementString("ValueLength", element.ValueLength.ToString());
     if (element.Value.IsSequence)
     {
         xml.WriteStartElement("Sequence");
         xml.WriteAttributeString("elementCount",
                                  ((Sequence)element.Value[0]).Count.ToString());
         foreach (DataElement d in (Sequence)element.Value[0])
         {
             AddDataElementToXml(xml, d);
         }
     }
     else if (element.Value.IsNestedDataSet)
     {
         xml.WriteStartElement("NestedDataSet");
         xml.WriteAttributeString("elementCount",
                                  ((NestedDataSet)element.Value[0]).Count.ToString());
         foreach (DataElement d in (NestedDataSet)element.Value[0])
         {
             AddDataElementToXml(xml, d);
         }
     }
     else if (element.Value.IsMultiValue)
     {
         xml.WriteStartElement("MultiValue");
         xml.WriteAttributeString("count", element.Value.Count.ToString());
         object[] valueArray = element.Value.ToArray();
         for (int i = 0; i < valueArray.Length; i++)
         {
             xml.WriteStartElement("Value");
             xml.WriteAttributeString("order", i.ToString());
             AddValueToXml(xml, valueArray[i], element.Value.IsDate);
             xml.WriteEndElement();
         }
     }
     else if (element.Value.IsUid)
     {
         Uid uid = (Uid)element.Value[0];
         xml.WriteStartElement("Uid");
         xml.WriteStartElement("Value");
         AddValueToXml(xml, uid, element.Value.IsDate);
         xml.WriteEndElement();
         xml.WriteStartElement("Name");
         AddValueToXml(xml, uid.GetDictionaryEntry().Name,
                       element.Value.IsDate);
         xml.WriteEndElement();
         xml.WriteStartElement("Type");
         AddValueToXml(xml, UidType.GetName(typeof(UidType),
                                            uid.GetDictionaryEntry().Type), element.Value.IsDate);
         xml.WriteEndElement();
     }
     else
     {
         xml.WriteStartElement("Value");
         if (!element.Value.IsEmpty)
         {
             AddValueToXml(xml, element.Value[0], element.Value.IsDate);
         }
     }
     // Value
     xml.WriteEndElement();
     // DataElement
     xml.WriteEndElement();
 }
Esempio n. 27
0
        public async Task <KeyGrant> GetAsync(Uid id)
        {
            return(await db.KeyGrants.FindAsync(id));

            // TODO: throw if not found
        }
Esempio n. 28
0
        public void PollingOrderCancelTest()
        {
            var socket = new MockSessionSocket();
            var mockMarketUid = new Uid(1);
            var mockContractUid = new Uid(1);
            var mockOrderUid = new Uid(1);
            var mockNewOrder = new NewOrder {
                Type = OrderCreateType.Limit,
                Market = mockMarketUid,
                Contract = mockContractUid,
                Side = Side.Buy,
                Quantity = new Quantity(QuantityType.PayoffCurrency, 10M),
                Price = new Price(PriceType.PercentOdds, 2000)
            };
            var mockOrder = new Order(
                mockNewOrder.Price,
                new OrderState(
                    mockOrderUid,
                    OrderCreateType.Limit,
                    OrderStatus.Live,
                    mockNewOrder.Quantity,
                    1337694040417086,
                    new Quantity(QuantityType.PayoffCurrency, 0)),
                mockNewOrder.Market,
                mockNewOrder.Contract,
                mockNewOrder.Side);

            socket.Expect(Payloads.Sequenced(Payloads.Login("mockuser", "mockpassword"), 1));
            socket.Next(Payloads.Sequenced(Payloads.LoginResponse("00000000-0000-0000-0000-00000000000", 2), 1));
            socket.Expect(Payloads.Sequenced(Payloads.OrderCreate(mockNewOrder), 2));
            socket.Next(Payloads.Sequenced(Payloads.OrderAccepted(mockOrderUid, 2), 2));
            socket.Expect(Payloads.Sequenced(Payloads.OrdersForAccountRequest(), 3));
            socket.Next(Payloads.Sequenced(Payloads.OrdersForAccount(new List<Order> { mockOrder }), 3));
            socket.Expect(Payloads.Sequenced(Payloads.OrderCancel(mockOrderUid), 4));
            socket.Next(Payloads.Sequenced(Payloads.OrderCancelled(mockOrderUid), 4));
            socket.Expect(Payloads.Sequenced(Payloads.Logout(), 5));
            socket.Next(Payloads.Sequenced(Payloads.LogoutConfirmation(), 5));

            var session = new SeqSession(socket, SessionSettings);
            IClientSettings mockSettings = new ClientSettings(SocketSettings, SessionSettings);

            using (var client = SmarketsClient.Create(mockSettings, session))
            {
                client.Login();
                var mockOrderResponse1 = client.CreateOrder(mockNewOrder);
                Assert.True(mockOrderResponse1.WaitOne());
                var original = mockOrderResponse1.Data;
                Assert.NotNull(original);
                var orders = client.GetOrders();
                orders.WaitOne();
                var newOrder = orders.Data[original.Uid];
                client.CancelOrder(newOrder);
                var i = 0;
                // Wait up to 500 ms
                while (i++ < 10 && newOrder.State.Status == OrderStatus.Live)
                {
                    Thread.Sleep(50);
                }
                client.Logout();
                Assert.Equal(OrderStatus.Cancelled, original.State.Status);
                Assert.Equal(OrderStatus.Cancelled, newOrder.State.Status);
            }
        }
Esempio n. 29
0
 public async Task <IReadOnlyList <KeyGrant> > ListAsync(Uid keyId)
 {
     return(await db.KeyGrants.QueryAsync(Expression.Eq("keyId", keyId)));
 }
Esempio n. 30
0
 public static Payload MarketQuotesRequest(Uid market)
 {
     return new Payload {
         Type = PayloadType.PAYLOADMARKETQUOTESREQUEST,
         MarketQuotesRequest = new MarketQuotesRequest {
             Market = market.ToUuid128()
         }
     };
 }
Esempio n. 31
0
 public void Properties()
 {
     Uid uid = new Uid(new Publisher("Digg"), "jeremy");
     Assert.AreEqual(new Publisher("Digg"), uid.Publisher);
     Assert.AreEqual("jeremy", uid.Name);
 }
Esempio n. 32
0
 public static Payload OrderAccepted(Uid order, ulong sequence)
 {
     return new Payload {
         Type = PayloadType.PAYLOADORDERACCEPTED,
         OrderAccepted = new OrderAccepted {
             Seq = sequence,
             Order = order.ToUuid128()
         }
     };
 }
Esempio n. 33
0
 /// <summary>
 /// Implementation of UpdateOp.Update
 /// </summary>
 /// <param name="oclass">Object class</param>
 /// <param name="uid">Object UID</param>
 /// <param name="attributes">Object attributes</param>
 /// <param name="options">Operation options</param>
 /// <returns>Uid of the updated object</returns>
 public Uid Update(ObjectClass oclass, Uid uid, ICollection <ConnectorAttribute> attributes, OperationOptions options)
 {
     return(Update(UpdateType.REPLACE, oclass, uid, attributes, options));
 }
Esempio n. 34
0
 public static Payload OrderCancelled(Uid order)
 {
     return new Payload {
         Type = PayloadType.PAYLOADORDERCANCELLED,
         OrderCancelled = new OrderCancelled {
             Order = order.ToUuid128(),
             Reason = Proto.Seto.OrderCancelledReason.ORDERCANCELLEDMEMBERREQUESTED
         }
     };
 }
Esempio n. 35
0
 internal static Command GetCommand(PSExchangeConnector.CommandInfo cmdInfo, ICollection <ConnectorAttribute> attributes, Uid uidAttribute, ExchangeConfiguration config)
 {
     return(GetCommand(cmdInfo, attributes, uidAttribute, null, config));
 }
Esempio n. 36
0
 public override int GetHashCode()
 {
     return(Uid?.GetHashCode() ?? base.GetHashCode());
 }
Esempio n. 37
0
 /// <summary>
 /// Escreve os dados no xml.
 /// </summary>
 /// <param name="writer"></param>
 void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
 {
     writer.WriteElementString("FullName", FullName);
     writer.WriteElementString("Uid", Uid.ToString());
     writer.WriteElementString("IsActive", IsActive.ToString());
 }
Esempio n. 38
0
 public Uid AddAttributeValues(ObjectClass oclass, Uid uid, ICollection <ConnectorAttribute> valuesToAdd, OperationOptions options)
 {
     return(Update(UpdateType.ADD, oclass, uid, valuesToAdd, options));
 }
Esempio n. 39
0
        public void HandleQuotes()
        {
            var socket = new MockSessionSocket();
            var mockMarketUid = new Uid(317002);
            var mockContractUid = new Uid(608008);
            var mockOrder = new NewOrder {
                Type = OrderCreateType.Limit,
                Market = mockMarketUid,
                Contract = mockContractUid,
                Side = Side.Buy,
                Quantity = new Quantity(QuantityType.PayoffCurrency, 60000),
                Price = new Price(PriceType.PercentOdds, 5714)
            };
            var builder = new EventQueryBuilder();
            builder.SetCategory("sport");
            builder.SetSport("football");
            builder.SetDateTime(new DateTime(2012,2,21));

            socket.Expect(Payloads.Sequenced(Payloads.Login("mockuser", "mockpassword"), 1));
            socket.Next(Payloads.Sequenced(Payloads.LoginResponse("00000000-0000-0000-0000-000000658a8", 2), 1));
            socket.Expect(Payloads.Sequenced(Payloads.EventsRequest(builder.GetResult()), 2));
            socket.Next(Payloads.Sequenced(Payloads.HttpFound("http://mock/api/events/sport/football/20120221/2.pb", 2), 2));
            socket.Expect(Payloads.Sequenced(Payloads.MarketSubscribe(new Uid(317002)), 3));
            socket.Next(Payloads.Sequenced(Payloads.MarketQuotes(new Uid(317002)), 3));
            socket.Expect(Payloads.Sequenced(Payloads.OrderCreate(mockOrder), 4));
            socket.Next(
                Payloads.Sequenced(
                    Payloads.ContractQuotes(
                        new Uid(608008),
                        new List<Seto.Quote> { new Seto.Quote { Price = 5714, Quantity = 60000 } },
                        Enumerable.Empty<Seto.Quote>()), 4));
            socket.Next(Payloads.Sequenced(Payloads.OrderAccepted(new Uid(82892989397900053), 4), 5));
            socket.Expect(Payloads.Sequenced(Payloads.Logout(), 5));
            socket.Next(Payloads.Sequenced(Payloads.LogoutConfirmation(), 6));

            var session = new SeqSession(socket, SessionSettings);
            IClientSettings mockSettings = new ClientSettings(SocketSettings, SessionSettings);

            var mockHttpHandler = new MockHttpFoundHandler<Seto.Events>();
            mockHttpHandler.AddDocument(MockUrls.Football20120221);
            using (var client = SmarketsClient.Create(mockSettings, session, mockHttpHandler))
            {
                mockHttpHandler.SetClient(client);
                client.Login();
                var mockEventUid = new Uid(247001);
                var mockMapResponse = client.GetEvents(builder.GetResult());
                Assert.True(mockMapResponse.WaitOne(DataWait));
                var mockMap = mockMapResponse.Data;
                Assert.True(mockMap.ContainsKey(mockEventUid));
                var mockMarket = client.MarketMap[mockMarketUid];
                var mockContract = client.ContractMap[mockContractUid];
                mockMarket.SubscribeQuotes(client);
                var marketUpdatedEvent = new ManualResetEvent(false);
                var contractUpdatedEvent = new ManualResetEvent(false);
                MarketQuotes mockQuotes = null;
                mockMarket.MarketQuotesUpdated += (sender, args) => {
                    mockQuotes = args.Quotes;
                    marketUpdatedEvent.Set();
                };
                mockContract.ContractQuotesUpdated += (sender, args) => contractUpdatedEvent.Set();
                var createResponse = client.CreateOrder(mockOrder);
                Assert.True(createResponse.WaitOne(DataWait));
                Assert.NotNull(createResponse.Data);
                Assert.True(marketUpdatedEvent.WaitOne(1000));
                Assert.Equal(mockQuotes.QuantityType, QuantityType.PayoffCurrency);
                Assert.Equal(mockQuotes.PriceType, PriceType.PercentOdds);
                Assert.Equal(mockQuotes.Uid, mockMarketUid);
                Assert.True(contractUpdatedEvent.WaitOne(1000));
                Assert.True(mockQuotes.ContractQuotes.ContainsKey(mockContractUid));
                var mockContractQuotes = mockQuotes.ContractQuotes[mockContractUid];
                Assert.Equal(mockContractQuotes.Bids.Count(), 1);
                var mockBid = mockContractQuotes.Bids.First();
                Assert.Equal<uint>(mockBid.Price.Raw, 5714);
                Assert.Equal<uint>(mockBid.Quantity.Raw, 60000);
                Assert.Equal(mockContractQuotes.Offers.Count(), 0);
                Assert.Equal(mockContractQuotes.Executions.Count(), 0);
                Assert.Equal(mockContractQuotes.QuantityType, QuantityType.PayoffCurrency);
                Assert.Equal(mockContractQuotes.PriceType, PriceType.PercentOdds);
                Assert.Equal(mockContractQuotes.Uid, mockContractUid);
                client.Logout();
            }
        }
Esempio n. 40
0
 public void SlugTest()
 {
     var uid1 = new Uid(340, 2034);
     var uid2 = new Uid(3408723498, 20347893249);
     Assert.Equal(uid1.ToSlug(UidTag.Account), "a-1fn9i4uf0qcq7sjlq9");
     Assert.Equal(uid2.ToSlug(UidTag.Account), "a-8k9z998uxzp3343bc0ongh");
     UidTag tag;
     var uid3 = Uid.ParseSlug("1fn9i4uf0qcq7sjlq9", out tag);
     Assert.Equal(uid3, uid1);
     Assert.Equal(UidTag.Account, tag);
     var uid4 = Uid.ParseSlug("a-8k9z998uxzp3343bc0ongh", out tag);
     Assert.Equal(uid4, uid2);
     Assert.Equal(UidTag.Account, tag);
     Assert.Throws<ArgumentException>(() => Uid.ParseSlug("c-8k9z998uxzp3343bc0ongh", out tag));
     Assert.Throws<ArgumentException>(() => Uid.ParseSlug("a", out tag));
     Assert.Throws<ArgumentException>(() => Uid.ParseSlug("", out tag));
     Assert.Throws<ArgumentNullException>(() => Uid.ParseSlug(null, out tag));
 }
        public static Result EnsureApplicationSaveData(FileSystemClient fs, out long requiredSize, TitleId applicationId,
                                                       ref ApplicationControlProperty nacp, ref Uid uid)
        {
            requiredSize = default;
            long requiredSizeSum = 0;

            // Create local variable for use in closures
            TitleId saveDataOwnerId = nacp.SaveDataOwnerId;

            // Ensure the user account save exists
            if (uid != Uid.Zero && nacp.UserAccountSaveDataSize > 0)
            {
                // More local variables for use in closures
                Uid  uidLocal               = uid;
                long accountSaveDataSize    = nacp.UserAccountSaveDataSize;
                long accountSaveJournalSize = nacp.UserAccountSaveDataJournalSize;

                Result CreateAccountSaveFunc()
                {
                    UserId userId = ConvertAccountUidToFsUserId(uidLocal);

                    return(fs.CreateSaveData(applicationId, userId, saveDataOwnerId, accountSaveDataSize,
                                             accountSaveJournalSize, SaveDataFlags.None));
                }

                var filter = new SaveDataFilter();
                filter.SetProgramId(applicationId);
                filter.SetSaveDataType(SaveDataType.Account);
                filter.SetUserId(new UserId(uid.Id.High, uid.Id.Low));

                // The 0x4c000 includes the save meta and other stuff
                Result rc = EnsureAndExtendSaveData(fs, CreateAccountSaveFunc, ref requiredSizeSum, ref filter, 0x4c000,
                                                    accountSaveDataSize, accountSaveJournalSize);

                if (rc.IsFailure())
                {
                    return(rc);
                }
            }

            // Ensure the device save exists
            if (nacp.DeviceSaveDataSize > 0)
            {
                long deviceSaveDataSize    = nacp.DeviceSaveDataSize;
                long deviceSaveJournalSize = nacp.DeviceSaveDataJournalSize;

                Result CreateDeviceSaveFunc() => fs.CreateDeviceSaveData(applicationId, saveDataOwnerId,
                                                                         deviceSaveDataSize, deviceSaveJournalSize, 0);

                var filter = new SaveDataFilter();
                filter.SetProgramId(applicationId);
                filter.SetSaveDataType(SaveDataType.Device);

                Result rc = EnsureAndExtendSaveData(fs, CreateDeviceSaveFunc, ref requiredSizeSum, ref filter, 0x4000,
                                                    deviceSaveDataSize, deviceSaveJournalSize);

                if (rc.IsFailure())
                {
                    return(rc);
                }
            }

            Result bcatRc = EnsureApplicationBcatDeliveryCacheStorageImpl(fs,
                                                                          out long requiredSizeBcat, applicationId, ref nacp);

            if (bcatRc.IsFailure())
            {
                if (!ResultFs.InsufficientFreeSpace.Includes(bcatRc))
                {
                    return(bcatRc);
                }

                requiredSizeSum += requiredSizeBcat;
            }

            if (nacp.TemporaryStorageSize > 0)
            {
                if (requiredSizeSum > 0)
                {
                    // If there was already insufficient space to create the previous saves, check if the temp
                    // save already exists instead of trying to create a new one.
                    var filter = new SaveDataFilter();
                    filter.SetProgramId(applicationId);
                    filter.SetSaveDataType(SaveDataType.Temporary);

                    Result rc = fs.FindSaveDataWithFilter(out _, SaveDataSpaceId.Temporary, ref filter);

                    if (rc.IsFailure())
                    {
                        if (!ResultFs.TargetNotFound.Includes(rc))
                        {
                            return(rc);
                        }

                        Result queryRc = fs.QuerySaveDataTotalSize(out long tempSaveTotalSize,
                                                                   nacp.TemporaryStorageSize, 0);

                        if (queryRc.IsFailure())
                        {
                            return(queryRc);
                        }

                        requiredSizeSum += Util.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
                    }
                }
                else
                {
                    Result createRc = fs.CreateTemporaryStorage(applicationId, nacp.SaveDataOwnerId,
                                                                nacp.TemporaryStorageSize, 0);

                    if (createRc.IsFailure())
                    {
                        if (ResultFs.InsufficientFreeSpace.Includes(createRc))
                        {
                            Result queryRc = fs.QuerySaveDataTotalSize(out long tempSaveTotalSize,
                                                                       nacp.TemporaryStorageSize, 0);

                            if (queryRc.IsFailure())
                            {
                                return(queryRc);
                            }

                            requiredSizeSum += Util.AlignUp(tempSaveTotalSize, 0x4000) + 0x4000;
                        }
                        else if (ResultFs.PathAlreadyExists.Includes(createRc))
                        {
                            requiredSizeSum += 0;
                        }
                        else
                        {
                            return(createRc);
                        }
                    }
                }
            }

            requiredSize = requiredSizeSum;

            return(requiredSize == 0 ? Result.Success : ResultFs.InsufficientFreeSpace.Log());
        }
Esempio n. 42
0
 internal OrderState(
     Uid uid,
     OrderCreateType type,
     OrderStatus status,
     Quantity quantity,
     ulong created,
     Quantity quantityFilled)
 {
     _uid = uid;
     _type = type;
     _status = status;
     _quantity = quantity;
     _created = created;
     _quantityFilled = quantityFilled;
 }
Esempio n. 43
0
        public void Create(CreateOpContext context)
        {
            context.Attributes = DeduplicateEmailAddresses(context, context.Attributes);

            // get recipient type
            string rcptType = ExchangeUtility.GetAttValue(ExchangeConnectorAttributes.AttRecipientType, context.Attributes) as string;

            if (rcptType == null || rcptType.Equals(""))
            {
                rcptType = ExchangeConnectorAttributes.RcptTypeUser;
            }

            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            PSExchangeConnector.CommandInfo cmdInfoEnable = null;
            PSExchangeConnector.CommandInfo cmdInfoSet    = null;
            switch (rcptType)
            {
            case ExchangeConnectorAttributes.RcptTypeMailBox:
                cmdInfoEnable = PSExchangeConnector.CommandInfo.EnableMailbox;
                cmdInfoSet    = PSExchangeConnector.CommandInfo.SetMailbox;
                break;

            case ExchangeConnectorAttributes.RcptTypeMailUser:
                cmdInfoEnable = PSExchangeConnector.CommandInfo.EnableMailUser;
                cmdInfoSet    = PSExchangeConnector.CommandInfo.SetMailUser;
                break;

            case ExchangeConnectorAttributes.RcptTypeUser:
                break;

            default:
                throw new ArgumentException(
                          context.ConnectorConfiguration.ConnectorMessages.Format(
                              "ex_bad_rcpt", "Recipient type [{0}] is not supported", rcptType));
            }

            // first create the object in AD
            ICollection <ConnectorAttribute> adAttributes = ExchangeUtility.FilterOut(context.Attributes,
                                                                                      PSExchangeConnector.CommandInfo.EnableMailbox,
                                                                                      PSExchangeConnector.CommandInfo.SetMailbox,
                                                                                      PSExchangeConnector.CommandInfo.EnableMailUser,
                                                                                      PSExchangeConnector.CommandInfo.SetMailUser);
            Uid uid = adconn.Create(context.ObjectClass, adAttributes, context.Options);

            if (rcptType == ExchangeConnectorAttributes.RcptTypeUser)
            {
                // AD account only, we do nothing
                context.Uid = uid;
                return;
            }

            // add a empty "EmailAddresses" attribute if needed (address policy is disabled and no addresses are provided)
            ICollection <ConnectorAttribute> enhancedAttributes;
            ConnectorAttribute policyEnabledAttribute = ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttEmailAddressPolicyEnabled, context.Attributes);

            if (policyEnabledAttribute != null &&
                ConnectorAttributeUtil.GetBooleanValue(policyEnabledAttribute).HasValue&&
                ConnectorAttributeUtil.GetBooleanValue(policyEnabledAttribute).Value == false &&
                ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttPrimarySmtpAddress, context.Attributes) == null &&
                ConnectorAttributeUtil.Find(ExchangeConnectorAttributes.AttEmailAddresses, context.Attributes) == null)
            {
                enhancedAttributes = new HashSet <ConnectorAttribute>(context.Attributes);
                enhancedAttributes.Add(ConnectorAttributeBuilder.Build(ExchangeConnectorAttributes.AttEmailAddresses));
                LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Added empty EmailAddresses attribute because address policy use is disabled and no addresses were provided");
            }
            else
            {
                enhancedAttributes = context.Attributes;        // no change
            }

            // prepare the command
            Command cmdEnable = ExchangeUtility.GetCommand(cmdInfoEnable, enhancedAttributes, uid, (ExchangeConfiguration)context.ConnectorConfiguration);
            Command cmdSet    = ExchangeUtility.GetCommand(cmdInfoSet, enhancedAttributes, uid, (ExchangeConfiguration)context.ConnectorConfiguration);

            try {
                _helper.InvokePipeline(exconn, cmdEnable);
                _helper.InvokePipeline(exconn, cmdSet);
            }
            catch {
                LOGGER.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "Rolling back AD create for UID: " + uid.GetUidValue());

                // rollback AD create
                try {
                    adconn.Delete(context.ObjectClass, uid, context.Options);
                } catch {
                    LOGGER.TraceEvent(TraceEventType.Warning, CAT_DEFAULT, "Not able to rollback AD create for UID: " + uid.GetUidValue());
                    // note: this is not perfect, we hide the original exception
                    throw;
                }

                // rethrow original exception
                throw;
            }

            context.Uid = uid;
        }
Esempio n. 44
0
 public override int GetHashCode()
 {
     return(Uid.GetHashCode());
 }
        private void AuthenticateExecute(IClosable _LoginWindow)
        {
            // Evaluate input mask command to generate Dummy Data;
            if (Uid == "$MAKE_DUMMY")
            {
                int Errors = DummyDataManager.Generate();
                if (Errors == 0)
                {
                    Message = "Executed. Dummy Data generated!";
                }
                else
                {
                    Message = $"Executed. At least {Errors} Columns weren't inserted!";
                }
                OnPropertyChanged("Message");
                return;
            }
            //else if (Uid == "$DELETE_DB")
            //{
            //    int Errors = DummyDataManager.DeleteAll();
            //    if (Errors == 0) Message = "Executed. Empties all Tables!";
            //    else Message = $"Executed. At least {Errors} Tables weren't emptied!";
            //    OnPropertyChanged("Message");
            //    return;
            //}

            // Get Name and LastName components from input string
            Regex RegexUid = new Regex(@"^(\S*)\.(\S*)\s*$");
            Match Identity = RegexUid.Match(Uid.ToLower());

            string Name     = Identity.Groups[1].ToString();
            string LastName = Identity.Groups[2].ToString();

            if (Identity.Groups.Count < 2)
            {
                Message = $"Illegal Uid! Must match '{RegexUid.ToString()}'";
                OnPropertyChanged("Message");
                return;
            }

            // Authenticate the Librarian / Customer
            dynamic User = Access.Auth(Name, LastName, Password);

            Librarian _Librarian = null;
            Customer  _Customer  = null;

            // Try casting to Librarian and Customer to check who has logged in
            try { _Librarian = User; } catch (Exception) { /* Ignore */ }
            try { _Customer = User; } catch (Exception) { /* Ignore */ }

            if (_Librarian != null)
            {
                LibrarianWindow _LibrarianWindow = new LibrarianWindow();
                _LibrarianWindow.DataContext = new LibrarianWindowViewModel()
                {
                    User = _Librarian, LibrarianWindow = _LibrarianWindow
                };
                _LibrarianWindow.Show();
                _LoginWindow.Close();
            }
            else if (_Customer != null)
            {
                CustomerWindow _CustomerWindow = new CustomerWindow();
                _CustomerWindow.DataContext = new CustomerWindowViewModel()
                {
                    User = _Customer
                };
                _CustomerWindow.Show();
                _LoginWindow.Close();
            }
            else
            {
                // Falltrough, invalid login data
                Message = "Uh Oh! Something went wrong.";
                OnPropertyChanged("Message");
            }
        }