Example #1
0
        public void Create_Product_With_No_ProductName_Should_Throw_Exception(string productName)
        {
            ProductKey productKey = new ProductKey("ABC123", "GENERICS");
            Action     action     = () => new Product(productKey, productName, 0, DateTime.MinValue, 0);

            action.Should().Throw <ArgumentException>().WithMessage($"{nameof(Product.ProductName)} can not be empty");
        }
Example #2
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.SerialCodeTextBox.Text) || this.ExpireDatePicker.SelectedDate.HasValue == false)
            {
                return;
            }

            var machineKey = new MachineKey(this.SerialCodeTextBox.Text);

            if (machineKey.IsValid == false)
            {
                MessageBox.Show("Serial code is invalid!", "Application", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }

            var version = new CP.NLayer.Common.License.Version((ApplicationEnum)this.ApplicationComboBox.SelectedValue,
                                                               (EditionEnum)this.EditionComboBox.SelectedValue,
                                                               (CountryEnum)this.CountryComboBox.SelectedValue);

            var productKey = ProductKey.Create(machineKey, this.ExpireDatePicker.SelectedDate.Value.Date, version, false);

            if (productKey != null && productKey.IsValid)
            {
                this.UnlockCodeTextBox.Text = productKey.Key;
            }
        }
Example #3
0
        private void SubscribeToInstrument(ProductKey productKey, string contract)
        {
            InstrumentLookupSubscription req = new InstrumentLookupSubscription(apiInstance.Session, Dispatcher.Current, productKey, contract);

            req.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(req_Update);
            req.Start();
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,NameId,Key,Status,OwnerId")] ProductKey productKey)
        {
            if (id != productKey.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(productKey);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductKeyExists(productKey.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["NameId"] = new SelectList(_context.ProductName, "Id", "Name", productKey.NameId);
            return(View(productKey));
        }
Example #5
0
        /// <summary>
        /// Verify whether the product key is valid. This method updates <see cref="IsValid" />, <see cref="KeyInvalidReason" />,
        /// and <see cref="LicenseType" />, which may be inspected for followup action.
        /// </summary>
        /// <param name="performWebServiceValidation">if set to <c>true</c> perform the validation using a web service.</param>
        public void Validate(bool performWebServiceValidation)
        {
            KeyInvalidReason = String.Empty;

            switch (ProductKey)
            {
            case Constants.ProductKeyGpl:
            case Constants.ProductKeyProfessional:
                if (!IsInTrialPeriod && AppSetting.Instance.ProviderDataStore == ProviderDataStore.SqlServer)
                {
                    KeyInvalidReason = "SQL Server detected. The product key you entered requires the use of SQL CE for the data store. You must switch to SQL CE or, if you wish to continue using SQL Server, purchase an Enterprise license. SQL Server offers faster performance and greater reliability. We highly recommend it.";
                    IsValid          = false;
                    LicenseType      = LicenseLevel.NotSet;
                }
                else
                {
                    IsValid     = true;
                    LicenseType = (ProductKey.Equals(Constants.ProductKeyProfessional) ? LicenseLevel.Professional : LicenseLevel.Gpl);
                }
                break;

            case Constants.ProductKeyEnterprise:
                IsValid     = true;
                LicenseType = LicenseLevel.Enterprise;
                break;

            default:
                KeyInvalidReason = "Product key is not valid";
                IsValid          = false;
                LicenseType      = LicenseLevel.NotSet;
                break;
            }
        }
Example #6
0
        /// <summary>
        /// Parse incoming keys from CSV file.
        /// </summary>
        public void ParseKeys()
        {
            using (var reader = new StreamReader(FilePath))
            {
                //SETUP
                List <ProductKey> keys = new List <ProductKey>();

                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split(Delimiter);

                    //TODO: Add handling of multiple entries on single line
                    //TODO: Add check for how many values in line

                    var validKey = new ProductKey
                    {
                        Key = values[1]
                    };

                    keys.Add(validKey);
                }

                //TODO Check DB for any keys already being

                Console.WriteLine($"Got {keys.Count} valid product keys");
            }
        }
Example #7
0
        public ProductKey GetProductKey(string siteId)
        {
            DataTable  dt = siteSetupData.GetProductKey(siteId);
            ProductKey pk = new ProductKey();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    pk.SiteId = dr.IsNull("site_id") ? 0 : int.Parse(dr["site_id"].ToString());

                    if (!dr.IsNull("SiteKey"))
                    {
                        var bytes_s = (byte[])dr["SiteKey"];
                        pk.SiteKey = Encoding.ASCII.GetString(bytes_s, 0, bytes_s.Length);
                    }
                    if (!dr.IsNull("LicenseKey"))
                    {
                        var bytes_l = (byte[])dr["LicenseKey"];
                        pk.LicenseKey = Encoding.ASCII.GetString(bytes_l, 0, bytes_l.Length);
                        pk.ExpireOn   = this.Decrypt(pk.LicenseKey, key).Split('|')[1];
                    }
                    break;
                }
            }
            return(pk);
        }
Example #8
0
        /// <summary>
        /// Event notification for status of authentication
        /// </summary>
        public void apiInstance_AuthenticationStatusUpdate(object sender, AuthenticationStatusUpdateEventArgs e)
        {
            if (e.Status.IsSuccess)
            {
                // lookup the leg instruments

                ProductKey prodKeyLeg = new ProductKey(MarketKey.Cbot, ProductType.Future, "ZN");

                // We will use a dictionary to hold all instrument requests and update it when each instrument is found.
                // Once all lookup requests for the legs are complete, we can continue with the creation of the spread.
                // tagValue will be used in the dictionary to identify each lookup request.

                int tagValue = 1000;

                m_req1     = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, prodKeyLeg, "Mar13");
                m_req1.Tag = tagValue;
                m_spreadLegKeys.Add(tagValue, null);
                m_req1.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(m_req_Update);
                m_req1.Start();

                tagValue++;

                m_req2     = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, prodKeyLeg, "Jun13");
                m_req2.Tag = tagValue;
                m_spreadLegKeys.Add(tagValue, null);
                m_req2.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(m_req_Update);
                m_req2.Start();
            }
            else
            {
                Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage);
                Dispose();
            }
        }
Example #9
0
        public void Create_Product_With_Invalid_Expiry_Should_Throw_Exception(int expiryInMonths)
        {
            ProductKey productKey  = new ProductKey("ABC123", "GENERICS");
            string     productName = "Demo Product";
            Action     action      = () => new Product(productKey, productName, expiryInMonths, DateTime.MinValue, 0);

            action.Should().Throw <ArgumentException>().WithMessage($"{nameof(Product.ExpiryInMonths)} should be greater than 0");
        }
 public TTInstrument(ProductKey productKey, string contract)
 {
     this.ProductKey       = productKey;
     this.Contract         = contract;
     m_instrument          = null;
     m_orderFeeds          = null;
     this.DefaultOrderFeed = null;
 }
Example #11
0
        public void PullNewProductKey(int id)
        {
            ProductOrderEntry entry = userRepository.GetProductOrderEntryByID(id);

            if (entry.Listing.Quantity == 0)
            {
                return;
            }

            ClaimedProductKey[] keys = entry.ClaimedProductKeys.ToArray();

            if (entry.Listing.ProductKeys.Count > 0)
            {
                ProductKey key = entry.Listing.ProductKeys.First();

                if (keys.Count() > 1)
                {
                    for (int i = 0; i < keys.Count(); i++)
                    {
                        userRepository.DeleteClaimedProductKey(keys[i].ClaimedProductKeyID);
                    }

                    entry.AddClaimedProductKey(new ClaimedProductKey(key, entry.Order.AppUser, DateTime.Now, "Admin pulled new key"));
                }
                else
                {
                    keys[0].Key    = key.ItemKey;
                    keys[0].IsGift = key.IsGift;
                }

                Listing listing = key.Listing;
                key.Listing.RemoveProductKeyAndUpdateQuantity(key);
                listingRepository.DeleteProductKey(key.ProductKeyID);
                listingRepository.UpdateListing(listing);
            }
            else if (entry.Listing.ChildListings.All(l => l.ProductKeys.Count > 0))
            {
                for (int i = 0; i < keys.Count(); i++)
                {
                    userRepository.DeleteClaimedProductKey(keys[i].ClaimedProductKeyID);
                }

                foreach (Listing childListing in entry.Listing.ChildListings)
                {
                    ProductKey key = childListing.ProductKeys.First();

                    userRepository.InsertClaimedProductKey(new ClaimedProductKey(key, entry.Order.AppUser, DateTime.Now, "Admin pulled new key"));

                    Listing listing = key.Listing;
                    key.Listing.RemoveProductKeyAndUpdateQuantity(key);
                    listingRepository.DeleteProductKey(key.ProductKeyID);
                    listingRepository.UpdateListing(listing);
                }
            }

            userRepository.UpdateProductOrderEntry(entry);
            unitOfWork.Save();
        }
Example #12
0
        public async Task CreateOrder(Order order, bool alreadyCharged, bool useDBKey = false)
        {
            // New orders should only have one product order entry
            ProductOrderEntry entry = order.ProductOrderEntries.FirstOrDefault();

            if (entry.ListingID != 0)
            {
                entry.Listing = listingRepository.GetListingByID(entry.ListingID);
            }

            DateTime date = DateTime.Now;

            order.SaleDate = date;

            String note = "Admin-created order";

            ClaimedProductKey newKey = new ClaimedProductKey();

            int priceToCharge = 0;

            if (order.ProductOrderEntries.Count() > 0)
            {
                priceToCharge = order.ProductOrderEntries.First().SalePrice;
            }

            if (useDBKey)
            {
                ProductKey key = GetProductKey(entry.ListingID);
                newKey = new ClaimedProductKey(key, order.AppUser, date, note);
                listingRepository.DeleteProductKey(key.ProductKeyID);
                unitOfWork.Save();

                priceToCharge = newKey.Listing.SaleOrDefaultPrice();

                entry.AddClaimedProductKey(newKey);//userRepository.InsertClaimedProductKey(newKey);
            }

            if (alreadyCharged == false)
            {
                BalanceEntry balanceEntry = new BalanceEntry();
                balanceEntry.Date           = date;
                balanceEntry.AppUser        = order.AppUser;
                balanceEntry.Notes          = note;
                balanceEntry.PointsAdjusted = priceToCharge;
                order.AppUser.Balance      -= priceToCharge;

                //userRepository.UpdateAppUser(order.AppUser);
                //userRepository.InsertBalanceEntry(balanceEntry);
                order.AppUser.AddBalanceEntry(balanceEntry);
            }

            entry.SalePrice = priceToCharge;
            order.AppUser.AddOrder(order);
            //userRepository.InsertOrder(order);
            await userRepository.UpdateAppUser(order.AppUser);

            unitOfWork.Save();
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,NameId,Key,Status,OwnerId")] ProductKey productKey)
        {
            ViewBag.keystatus = status;
            if (id != productKey.Id)
            {
                return(NotFound());
            }

            //Check if given key is a duplicate
            if (_context.ProductKey.Any(p => p.Key == productKey.Key && p.Id != id))
            {
                ModelState.AddModelError("Key", "Key already exists");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Edit the used key count
                    var products = _context.Product.AsQueryable();
                    var product  = products.Where(p => p.Id == productKey.NameId).FirstOrDefault();

                    // Get the key's old status
                    var    currentKey = _context.ProductKey.AsNoTracking().AsQueryable().Where(k => k.Id == id).FirstOrDefault();
                    string oldStatus  = currentKey.Status;

                    // Add or minus used key count by one if the status of edited key is changed
                    if (oldStatus == "New" && productKey.Status == "Used")
                    {
                        product.UsedKeyCount++;
                        _context.Entry(product).Property("UsedKeyCount").IsModified = true;
                    }
                    else if (oldStatus == "Used" && productKey.Status == "New")
                    {
                        product.UsedKeyCount--;
                        _context.Entry(product).Property("UsedKeyCount").IsModified = true;
                    }
                    await _context.SaveChangesAsync();

                    _context.Update(productKey);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductKeyExists(productKey.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["NameId"] = new SelectList(_context.Product, "Id", "Name", productKey.NameId);
            return(View(productKey));
        }
Example #14
0
        public void FindInstrument(ProductKey productKey, string contract)
        {
            Console.WriteLine(String.Format("TT API FindInstrument {0} {1}", productKey, contract));

            InstrumentLookupSubscription instrRequest = new InstrumentLookupSubscription(m_TTAPI.Session, Dispatcher.Current, productKey, contract);

            instrRequest.Update += instrRequest_Completed;
            instrRequest.Start();
        }
 /// <summary>
 /// Construct an InstrumentDescriptor object with the four strings that make up the
 /// necessary information
 /// </summary>
 /// <param name="market">Market for the requested instrument (i.e. "CME")</param>
 /// <param name="productType">Product type for the requested instrument (i.e. "FUTURE")</param>
 /// <param name="product">Product for the requested instrument (i.e. "CL")</param>
 /// <param name="contract">Contract for the requested instrument (i.e. "Nov12")</param>
 public InstrumentDescriptor(string market, string productType, string product, string contract) : this()
 {
     MarketName = market;
     ProductTypeName = productType;
     ProductName = product;
     ContractName = contract;
     
     ProductKey = new ProductKey(MarketName, ProductTypeName, ProductName);
 }
Example #16
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Title = string.Empty;
            var productKey = new ProductKey(this.UnlockCodeTextBox.Text);

            if (productKey.IsValid)
            {
                this.Title = productKey.MachineKey.Key;
            }
        }
Example #17
0
 public Product(ProductKey key)
 {
     Key         = key;
     ProductDet1 = new ProductDet {
         ProductKey = Key
     };
     ProductDet2 = new ProductDet {
         ProductKey = Key
     };
 }
 /// <summary>
 /// Create an InstrumentDescriptor using a single string containing all the required
 /// information (with the "|" char as the separator).
 /// </summary>
 /// <param name="descriptor"></param>
 /// <example>InstrumentDescriptor id = new InstrumentDescriptor("CME|FUTURE|HG|Dec12")</example>
 public InstrumentDescriptor(string descriptor) : this()
 {
     string[] items = descriptor.Split('|');
     MarketName = items[0].Trim();
     ProductTypeName = items[1].Trim();
     ProductName = items[2].Trim();
     ContractName = items[3].Trim();
     
     ProductKey = new ProductKey(MarketName, ProductTypeName, ProductName);
 }
Example #19
0
        internal static IResult <SetSampleOrderItemParameters> ToParsedParameters(this ISampleOrderItemParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            SampleOrderItemKey itemKey = null;

            if (!string.IsNullOrWhiteSpace(parameters.SampleOrderItemKey))
            {
                var itemKeyResult = KeyParserHelper.ParseResult <ISampleOrderItemKey>(parameters.SampleOrderItemKey);
                if (!itemKeyResult.Success)
                {
                    return(itemKeyResult.ConvertTo <SetSampleOrderItemParameters>());
                }

                itemKey = itemKeyResult.ResultingObject.ToSampleOrderItemKey();
            }

            ProductKey productKey = null;

            if (!string.IsNullOrWhiteSpace(parameters.ProductKey))
            {
                var chileProductKeyResult = KeyParserHelper.ParseResult <IProductKey>(parameters.ProductKey);
                if (!chileProductKeyResult.Success)
                {
                    return(chileProductKeyResult.ConvertTo <SetSampleOrderItemParameters>());
                }

                productKey = chileProductKeyResult.ResultingObject.ToProductKey();
            }

            LotKey lotKey = null;

            if (!string.IsNullOrWhiteSpace(parameters.LotKey))
            {
                var chileLotKeyResult = KeyParserHelper.ParseResult <ILotKey>(parameters.LotKey);
                if (!chileLotKeyResult.Success)
                {
                    return(chileLotKeyResult.ConvertTo <SetSampleOrderItemParameters>());
                }

                lotKey = chileLotKeyResult.ResultingObject.ToLotKey();
            }

            return(new SuccessResult <SetSampleOrderItemParameters>(new SetSampleOrderItemParameters
            {
                Parameters = parameters,

                SampleOrderItemKey = itemKey,
                ProductKey = productKey,
                LotKey = lotKey
            }));
        }
Example #20
0
        public void IsProductExpired_Should_Return_True_If_Product_Has_Passed_Expiry()
        {
            ProductKey productKey        = new ProductKey("ABC123", "GENERICS");
            string     productName       = "Demo Product";
            int        expiryInMonths    = 2;
            int        stockQuantity     = 10;
            DateTime   manufacturingDate = DateTime.Now.AddMonths(-3);
            var        product           = new Product(productKey, productName, expiryInMonths, manufacturingDate, stockQuantity);

            product.IsProductExpired(DateTime.Now).Should().Be(true);
        }
Example #21
0
        public void DeleteProductKey(int productKeyId)
        {
            ProductKey key     = listingRepository.GetProductKeyByID(productKeyId);
            Listing    listing = key.Listing;

            listingRepository.DeleteProductKey(productKeyId);
            //listing.UpdateQuantity();
            //listing.UpdateParentQuantities();
            listingRepository.UpdateListing(listing);
            unitOfWork.Save();
        }
Example #22
0
        public void UpdateProductKey(ProductKey productKey)
        {
            ProductKey targetProductKey = context.ProductKeys.Find(productKey.ProductKeyID);

            if (targetProductKey != null)
            {
                targetProductKey.ListingID = productKey.ListingID;
                targetProductKey.ItemKey   = productKey.ItemKey;
                targetProductKey.IsGift    = productKey.IsGift;
            }
        }
Example #23
0
        }     //TryGetInstrument()

        //
        // *****************************************************************
        // ****                 Try Get Product()                       ****
        // *****************************************************************
        /// <summary>
        /// This is a thread-safe way to query the Market whether it knows the Misty Product
        /// associated with a particular TT ProductKey.
        /// </summary>
        public bool TryLookupProduct(ProductKey ttProductKey, out Misty.Lib.Products.Product product)
        {
            bool isGood = false;

            lock (m_ProductMapLock)
            {
                if (m_ProductMapKey.TryGetValue(ttProductKey, out product))
                {
                    isGood = true;
                }
            } //lock
            return(isGood);
        }     //TryGetProduct()
Example #24
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            UpdateStatusBar("Connecting to Instrument...");

            // Create a product key from the given values
            ProductKey productKey = new ProductKey(this.txtExchange.Text,
                                                   (ProductType)this.cboProductType.SelectedItem,
                                                   this.txtProduct.Text);

            InstrumentKey key = new InstrumentKey(productKey, this.txtContract.Text);

            //m_ttapi.FindInstrument(key);
        }
        public async Task <IActionResult> Create([Bind("Id,NameId,Key,Status,OwnerId")] ProductKey productKey)
        {
            if (ModelState.IsValid)
            {
                // Increse current product key count by one

                _context.Add(productKey);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["NameId"] = new SelectList(_context.ProductName, "Id", "Name", productKey.NameId);
            return(View(productKey));
        }
Example #26
0
        public async Task <Product> GetByIdAsync(ProductKey id, CancellationToken cancellationToken = default)
        {
            var product = await _context
                          .Set <Product>()
                          .Include(p => p.Category)
                          .SingleOrDefaultAsync(cat => cat.Id == id, cancellationToken);

            if (product is null)
            {
                throw new KeyNotFoundException($"{nameof(Product)} with Id = {id} not found.");
            }

            return(product);
        }
        /// <summary>
        /// Click event which will initiate the price subscription
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            UpdateStatusBar("Connecting to Instrument...");

            // Create a product key from the given values
            ProductKey key = new ProductKey(this.txtExchange.Text,
                                            (ProductType)this.cboProductType.SelectedItem,
                                            this.txtProduct.Text);

            // Find out instrument based on the previously created key and the contract name
            InstrumentLookupSubscription instrRequest = new InstrumentLookupSubscription(this.m_TTAPI.Session, Dispatcher.Current, key, this.txtContract.Text);

            instrRequest.Update += instrRequest_Completed;
            instrRequest.Start();
        }
Example #28
0
 public int UpdateProductKey(ProductKey pk)
 {
     try
     {
         SqlParameter[] sqlParameters = new SqlParameter[3];
         sqlParameters[0] = new SqlParameter("@SiteId", pk.SiteId);
         sqlParameters[1] = new SqlParameter("@SiteKey", Encoding.ASCII.GetBytes(pk.SiteKey));
         sqlParameters[2] = new SqlParameter("@LicenseKey", Encoding.ASCII.GetBytes(pk.LicenseKey));
         return(conn.executeUpdateQuery("sp_UpdateProductKey", sqlParameters));
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #29
0
        public int UpdateProductKey(ProductKey pk)
        {
            int result = -1;

            if (!string.IsNullOrWhiteSpace(pk.SiteKey) && !string.IsNullOrWhiteSpace(pk.LicenseKey))
            {
                var      license = Decrypt(pk.LicenseKey, key);
                var      array   = license.Split('|');
                DateTime date;
                if (DateTime.TryParse(array[1], out date))
                {
                    result = siteSetupData.UpdateProductKey(pk);
                }
            }
            return(result);
        }
Example #30
0
        public void Create_Product_With_Valid_Data_Should_Be_Successful()
        {
            ProductKey productKey        = new ProductKey("ABC123", "GENERICS");
            string     productName       = "Demo Product";
            int        expiryInMonths    = 6;
            int        stockQuantity     = 10;
            DateTime   manufacturingDate = DateTime.Now.AddMonths(-3);
            var        product           = new Product(productKey, productName, expiryInMonths, manufacturingDate, stockQuantity);

            product.Should().NotBeNull();
            product.ProductKey.Should().Be(productKey);
            product.ProductName.Should().Be(productName);
            product.ManufacturingDate.Should().Be(manufacturingDate);
            product.ExpiryInMonths.Should().Be(expiryInMonths);
            product.StockQuantity.Should().Be(stockQuantity);
        }
        public void startProductLookupSubscriptions(object sender, AuthenticationStatusUpdateEventArgs e)
        {
            PlsDictionaryCompleteQ = false;

            if (e.Status.IsSuccess)
            {

                // lookup an instrument
                foreach (string TickerHead in TickerHeadList)
                {
                    string exchange = ContractUtilities.ContractMetaInfo.GetExchange4Tickerhead(TickerHead);
                    if (exchange == "CME")
                        mkey = MarketKey.Cme;
                    else if (exchange == "ICE")
                        mkey = MarketKey.Ice;

                    Console.WriteLine(TA.TickerheadConverters.ConvertFromDB2TT(TickerHead));

                    ProductKey ProdKey = new ProductKey(mkey, ProductType.Future, TA.TickerheadConverters.ConvertFromDB2TT(TickerHead));
                    ProductLookupSubscription PLS = new ProductLookupSubscription(m_apiInstance.Session, Dispatcher.Current, ProdKey);
                    PlsDictionary.Add(ProdKey, PLS);
                    PLS.Update += new EventHandler<ProductLookupSubscriptionEventArgs>(PLSEventHandler);
                    PLS.Start();

                    ProdKey = new ProductKey(mkey, ProductType.Spread, TA.TickerheadConverters.ConvertFromDB2TT(TickerHead));
                    PLS = new ProductLookupSubscription(m_apiInstance.Session, Dispatcher.Current, ProdKey);

                    PlsDictionary.Add(ProdKey, PLS);
                    PLS.Update += new EventHandler<ProductLookupSubscriptionEventArgs>(PLSEventHandler);
                    PLS.Start();
                }
                PlsDictionaryCompleteQ = true;
            }

            else
            {
                Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage);
                Dispose();
            }
        }
        /// <summary>
        /// Event notification for status of authentication
        /// </summary>
        public void apiInstance_AuthenticationStatusUpdate(object sender, AuthenticationStatusUpdateEventArgs e)
        {
            if (e.Status.IsSuccess)
            {
                // lookup the leg instruments

                ProductKey prodKeyLeg = new ProductKey(MarketKey.Cbot, ProductType.Future, "ZN");

                // We will use a dictionary to hold all instrument requests and update it when each instrument is found.
                // Once all lookup requests for the legs are complete, we can continue with the creation of the spread.
                // tagValue will be used in the dictionary to identify each lookup request.

                int tagValue = 1000;

                m_req1 = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, prodKeyLeg, "Mar13");
                m_req1.Tag = tagValue;
                m_spreadLegKeys.Add(tagValue, null);
                m_req1.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(m_req_Update);
                m_req1.Start();

                tagValue++;

                m_req2 = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, prodKeyLeg, "Jun13");
                m_req2.Tag = tagValue;
                m_spreadLegKeys.Add(tagValue, null);
                m_req2.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(m_req_Update);
                m_req2.Start();
            }
            else
            {
                Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage);
                Dispose();
            }
        }
        /// <summary>
        /// Click event which will initiate the price subscription
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            UpdateStatusBar("Connecting to Instrument...");

            // Create a product key from the given values
            ProductKey key = new ProductKey(this.txtExchange.Text,
                                            (ProductType)this.cboProductType.SelectedItem,
                                            this.txtProduct.Text);

            // Find out instrument based on the previously created key and the contract name
            InstrumentLookupSubscription instrRequest = new InstrumentLookupSubscription(this.m_TTAPI.Session, Dispatcher.Current, key, this.txtContract.Text);
            instrRequest.Update += instrRequest_Completed;
            instrRequest.Start();
        }
        private void StartSpreadDetailsProcess()
        {
            // We will create a spread with 2 legs
            Console.WriteLine("Find instruments for the legs...");

            ProductKey prodKeyLeg = new ProductKey(MarketKey.Cbot, ProductType.Future, "ZN");

            // We will use a dictionary to hold all instrument requests and update it when each instrument is found.
            // Once all lookup requests for the legs are complete, we can continue with the creation of the spread.
            // tagValue will be used in the dictionary to identify each lookup request.

            int tagValue = 1000;

            req1 = new InstrumentLookupSubscription(apiInstance.Session, Dispatcher.Current,
                                                prodKeyLeg,
                                                "Sep12");
            req1.Tag = tagValue;
            spreadLegKeys.Add(tagValue, null);
            req1.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(legReq_Update);
            req1.Start();

            tagValue++;

            req2 = new InstrumentLookupSubscription(apiInstance.Session, Dispatcher.Current,
                                                prodKeyLeg,
                                                "Dec12");
            req2.Tag = tagValue;
            spreadLegKeys.Add(tagValue, null);
            req2.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(legReq_Update);
            req2.Start();
        }