private void initPublisher(String pub, int strength)
	    {
		    mgr = new DDSEntityManager("Ownership");
		    String partitionName = "Ownership example";

		    // create Domain Participant
		    mgr.createParticipant(partitionName);
    		
		    // create Type
		    StockTypeSupport stkTS = new StockTypeSupport();
		    mgr.registerType(stkTS);
    		
		    // create Topic
		    mgr.createTopic("OwnershipStockTracker");
    		
		    // create Publisher
		    mgr.createPublisher();
    		
		    // create DataWriter
		    mgr.createWriterWithStrength(strength);
		    dwriter= mgr.getWriter();
            OwnershipDataWriter = dwriter as StockDataWriter;
    		
		    msft = new Stock();
		    msft.ticker = "MSFT";
            msft.publisher = pub;
            msft.strength = strength;
            msftHandle = OwnershipDataWriter.RegisterInstance(msft);
	    }
Beispiel #2
0
        public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
        {
            string dir = String.Format(@"..\..\StockData\Maya");
            string filename = String.Format("{0}.csv", stockName);
            var fullPath = Path.Combine(dir, filename);

            var rates = new List<IStockEntry>();

            var parser = new TextFieldParser(fullPath) {TextFieldType = FieldType.Delimited};
            parser.SetDelimiters(",");

            //skips the first 3 lines
            parser.ReadFields();
            parser.ReadFields();
            parser.ReadFields();

            while (!parser.EndOfData)
            {
                var fields = parser.ReadFields();
                if (fields != null)
                {
                    StockEntry stockEntry = null;
                    rates.Add(stockEntry);
                }
            }

            rates.Reverse();

            var stock = new Stock(stockName, rates);

            return stock;
        }
Beispiel #3
0
        public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
        {
            string dir = String.Format(@"..\..\StockData\Yahoo");
            string filename = String.Format("{0}.stock", stockName);
            var fullPath = Path.Combine(dir, filename);

            List<IStockEntry> rates;
            if (!File.Exists(fullPath))
            {
                rates = GetStockFromRemote(stockName, startDate, endDate);
                Directory.CreateDirectory(dir);
                using (Stream stream = File.Open(fullPath, FileMode.Create))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bformatter.Serialize(stream, rates);
                }

            }
            else
            {
                using (Stream stream = File.Open(fullPath, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    rates = (List<IStockEntry>) bformatter.Deserialize(stream);
                }
            }
            var stock = new Stock(stockName, rates);
            return stock;
        }
 public void addTransaction(ApplicationDbContext db, ApplicationUser user, Stock stock, StockTransaction model)
 {
     model.StockTicker = stock.Identifier;
     model.UserId = user.Id;
     db.StockTransactions.Add(model);
     db.SaveChanges();
 }
Beispiel #5
0
 public void Init()
 {
     i1 = new StockItem ("BMAC56790", "Propelling Pencil", "Supply Master", "1.49", "10", "20");
     stock_list  = new Stock();
     stock_list.AddStockItem(i1.StockCode, i1);
     stock_control = new StockControl(stock_list);
 }
Beispiel #6
0
        public void RunExample()
        {
            decimal price = 23.50m;

            Stock stock = new Stock("MSFT", price);
            Console.WriteLine("Stock set to {0:C}.", stock.Price);

            Bidder bidderA = new Bidder("Bidder A", stock);
            Bidder bidderB = new Bidder("Bidder B", stock);
            Bidder bidderC = new Bidder("Bidder C", stock);

            stock.Attach(bidderA);
            stock.Attach(bidderB);
            stock.Attach(bidderC);

            price = 24.25m;
            Console.WriteLine("\nStock set to {0:C}.", price);
            stock.Price = price;

            stock.Detach(bidderB);
            Console.WriteLine("\n{0} detached.", bidderB.Name);

            price = 26.75m;
            Console.WriteLine("\nStock set to {0:C}.", price);
            stock.Price = price;
        }
        static void Main(string[] args)
        {
            Stock stock1 = new Stock("Technology", 160, 5, 15);
             Stock stock2 = new Stock("Retail", 30, 2, 6);
             Stock stock3 = new Stock("Banking", 90, 4, 10);
             Stock stock4 = new Stock("Commodity", 500, 20, 50);

             StockBroker b1 = new StockBroker("Broker 1");
             b1.AddStock(stock1);
             b1.AddStock(stock2);

             StockBroker b2 = new StockBroker("Broker 2");
             b2.AddStock(stock1);
             b2.AddStock(stock3);
             b2.AddStock(stock4);

             StockBroker b3 = new StockBroker("Broker 3");
             b3.AddStock(stock1);
             b3.AddStock(stock3);

             StockBroker b4 = new StockBroker("Broker 4");
             b4.AddStock(stock1);
             b4.AddStock(stock2);
             b4.AddStock(stock3);
             b4.AddStock(stock4);
        }
 protected void Button2_Click(object sender, EventArgs e)
 {
     int id = Convert.ToInt32(DropDownList.SelectedValue);
     int Quantity = Convert.ToInt32(QuantityBox.Text);
     Stock newStock = new Stock(id, Quantity);
     newStock.updateStock(id, Quantity);
 }
            public void ReturnsDateOfMostRecentEntry()
            {
                //// SETUP

                // Test Data
                var stock = new Stock { Ticker = "FLWS", CompanyName = "1-800 FLOWERS.COM" };
                var oldest = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/1/2000") };
                var middle = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/2/2000") };
                var newest = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/3/2000") };
                var testData = new List<HistoricPrice> { oldest, newest, middle };

                // Create a mock generic repository.
                var mockGenericRepository = new Mock<IReadOnlyRepository<HistoricPrice>>();
                mockGenericRepository.Setup(mock => mock.FilterBy(It.IsAny<Expression<Func<HistoricPrice, bool>>>())).Returns(testData.AsQueryable());

                // Setup target
                var target = new ReadOnlyPriceHistoryRepository(mockGenericRepository.Object);

                // EXECUTE
                var actual = target.GetMostRecentDateForTicker(stock.Ticker);

                // VERIFY
                Assert.AreEqual(newest.Date, actual);
                mockGenericRepository.Verify(mock => mock.FilterBy(It.IsAny<Expression<Func<HistoricPrice, bool>>>()), Times.Once());
            }
Beispiel #10
0
        public ReconcileStock(int _id)
        {
            InitializeComponent();
            id = _id;
            sl = new StockList(id);

            s = sl.ViewAStock(sl[0].StockID);
        }
 public StockTest()
 {
     _stock = new Stock("MSFT");
     _stock.CurrentPrice = 5.5m;
     _purchase1 = new StockTransaction(DateTime.Now, 4.0m, 7);
     _purchase2 = new StockTransaction(DateTime.Now.AddDays(-1), 7.5m, 2);
     _sale1 = new StockTransaction(DateTime.Now, 5.0m, -1);
 }
Beispiel #12
0
    static void Main()
    {
        Stock x = new Stock();
        x.SetPreviousPrice(5.3);
        Console.WriteLine(x.PreviousPrice); //=5.3

        Console.WriteLine(x.Words[1]); //=quick
    }
 public void ImportStock(Stock stock)
 {
     using (var context = ContainerHelper.Instance.Resolve<IRepositoryContext>())
     {
         //添加新的股票基础数据
         context.UnitOfWork.RegisterNew<Stock>(stock);
         context.UnitOfWork.Commit();
     }
 }
Beispiel #14
0
        public Stock GetFristCol(string data)
        {
            List<Price> prices = new List<Price>();
            List<DataItem> items = new List<DataItem>();
            string firstCol = string.Empty;
            List<string> lines = data.Split('\n').ToList<string>();
            for (int i = 2; i < lines.Count; i++)
            {
                string line = lines[i];
                List<string> numStrs = line.Split(' ').ToList<string>();
                if (numStrs.Count < 5)
                    continue;
                DataItem item = new DataItem();
                Price price = new Price();
                price.content = new string[4];
                for (int numI = 0; numI < numStrs.Count; numI++)
                {
                    if (numI == 0)
                        item.content = numStrs[numI];
                    if (numI > 0 && numI < 5)
                    {
                        price.content[numI-1] = numStrs[numI];
                        if (numI == 3)
                        {
                            price.content[numI-1] = numStrs[numI+1];
                        }
                        if (numI == 4)
                        {
                            price.content[numI - 1] = numStrs[numI-1];
                        }
                    }
                   // if (numI > 0 && numI < 4)

                        //price.content += ",";

                }
                items.Add(item);
                prices.Add(price);
            }
            Stock stock = new Stock();
            stock.price = new Price[prices.Count];
            for (int itemI = 0; itemI < items.Count; itemI++)
            {
                stock.data += items[itemI].content;
                if (itemI != items.Count - 1)
                    stock.data += ",";
            }
            for (int priceI = 0; priceI < prices.Count; priceI++)
            {
                stock.price[priceI] = prices[priceI];   // += "[" + prices[priceI].content + "]";
                //if (priceI != prices.Count - 2)
                //    stock.price += ";";
            }
               // stock.data = "[" + stock.data + "]";
               // stock.price = "[" + stock.price  + "]";
            return stock;
        }
Beispiel #15
0
        static void tstInheritance1()
        {
            Stock stock = new Stock { Name = "MSFT", SharesOwned = 1500 };
            House house = new House { Name = "SAS", Mortgage = 2300 };

            stock.Display();
            house.Display();

            //Upcasting
            Stock stock2 = new Stock();
            Asset asset = stock2;

            Console.WriteLine((asset == stock2 ? "asset == stock2!" : "asset != stock2!"));
            //asset.SharesOwned;     - yet Stock fields aren't accessible!!!

            //To access Stock fields DOWNCASTING is needed!!
            Stock stock3 = (Stock) asset;

            Console.WriteLine(stock3.SharesOwned);      // <No error>
            Console.WriteLine(stock3 == asset);         // True
            Console.WriteLine(stock3 == stock2);        // True

            //AS operator
            Asset a = new Asset();
            Stock s = a as Stock; // s is null; no exception thrown

            try {
                long shares1 = ((Stock)a).SharesOwned; // Approach #1
            }
            catch (InvalidCastException ice) {
                Console.WriteLine(ice.ToString());
            }

            if (s != null) {
                Console.WriteLine(s.SharesOwned);
                long shares2 = (a as Stock).SharesOwned; // Approach #2
            }

            /*  
             *  Another way of looking at it is that with the cast operator (Approach #1), you’re
                saying to the compiler: “I’m certain of a value’s type; if I’m
                wrong, there’s a bug in my code, so throw an exception!”
                Whereas with the as operator (Approach #2), you’re uncertain of its type and
                want to branch according to the outcome at runtime.
             * */

            //IS operator
            if (a is Stock)
                Console.WriteLine(((Stock)a).SharesOwned);

            /*
             *  The is operator tests whether a reference conversion would succeed; in other words,
                whether an object derives from a specified class (or implements an interface). It is
                often used to test before downcasting. 
             * */
        }
        public async Task<IActionResult> Buy(string symbol, int shares)
        {
            var stock = new Stock(symbol);
            stock = await stockInfo.GetQuoteAsync(stock);

            var model = new StockTransaction(DateTime.Now, stock.CurrentPrice.Value, shares);
            stockHistory.addTransaction(_applicationDbContext, await GetCurrentUserAsync(), stock, model);

            return Redirect("/Stocks/SearchStocks?symbol=" + symbol);
        }
Beispiel #17
0
 public void Init()
 {
     i1 = new StockItem ("BMAC56790", "Propelling Pencil", "Supply Master", "1.49", "10", "20");
     i3 = new StockItem ("BMAC56780", "Propelling Pencil", "Supply Master", "1.49", "10", "20");
     i4 = new StockItem ("BMAC56770", "Propelling Pencil", "Supply Master", "1.49", "10", "20");
     stock_list  = new Stock();
     stock_list.AddStockItem(i1.StockCode, i1);
     stock_list.AddStockItem(i3.StockCode, i3);
     stock_list.AddStockItem(i4.StockCode, i4);
 }
        public void CalculatePeRatioTest()
        {
            var stock = new Stock("TEA", StockType.Common, 10, 0, 100);
            var peRatio = StockCalculator.CalculatePeRatio(stock, 105);
            AssertDiff(10.5m, peRatio );

            var stockWithZeroDividend = new Stock("TEA", StockType.Common, 0, 0, 100);
            var peRatioWithZeroDividend = StockCalculator.CalculatePeRatio(stockWithZeroDividend, 105);
            AssertDiff(0m, peRatioWithZeroDividend);
        }
        public void addNewStock(Stock stock)
        {
            if (lbStocks.InvokeRequired)
            {
                this.BeginInvoke(new addNewStockDelegate(addNewStock), stock);
                return;
            }

            lbStocks.Items.Add(stock);
        }
        public List<double> historyData(Stock stock, DateTime start, DateTime end)
        {
            List<double> data = new List<double>();

            // MRO 접속



            return data;
        }
Beispiel #21
0
 public void Init()
 {
     i1 = new StockItem ("BMAC56790", "Propelling Pencil", "Supply Master", "1.49", "10", "20");
     stock_list  = new Stock();
     stock_list.AddStockItem(i1.StockCode, i1);
     order_history = new OrderHistory();
     DateTime timestamp = DateTime.Now;
     o1 = new Order (timestamp, i1.StockCode, i1.Supplier, 10, 10);
     order_history.AddOrder (o1);
 }
Beispiel #22
0
 public static IEnumerable<Stock> getNext()
 {
     for (int i = 0; i < samplePrices.Length; i++)
     {
         Stock s = new Stock();
         s.Code = sampleStocks[i];
         s.Price = samplePrices[i];
         yield return s;
     }
 }
        public void CalculateDividendTest()
        {
            var stockCommon = new Stock("TEA", StockType.Common, 10, 0, 100);
            var dividendCommon = StockCalculator.CalculateDividend(stockCommon, 100m);
            AssertDiff(0.1m, dividendCommon);

            var stockPreferred = new Stock("TEA", StockType.Preferred, 10, 5, 100);
            var dividendPreffered = StockCalculator.CalculateDividend(stockPreferred, 100);
            AssertDiff(5m, dividendPreffered);
        }
        public string StockSync()
        {
            StringBuilder returnStr = new StringBuilder();

            //获取股票Domain服务
            var stockservice = new ImportStockService();
            var dailypriceservice = new ImportDailyPriceDataService();

            //获取股票对象
            var stock = stockservice.GetStockBySymbol(m_StockCode);
            if (stock == null)
            {
                //创建股票对象
                stock = new Stock { Symbol = m_StockCode, Name = string.Empty };
                stockservice.ImportStock(stock);
            }

            //获取股票日线最新记录时间
            var starttime = dailypriceservice.GetLatestDailyPriceDataImportDateTime(m_StockCode);

            //创建雅虎财经实例,并获取数据库未记录的历史数据
            IEnumerable<DailyPriceDataItem> dayItemList;
            YahooFinance yahoo = new YahooFinance(stock);
            yahoo.Suffix = Suffix;
            if (starttime < new DateTime(1990, 12, 1))
            {
                dayItemList = yahoo.GetDayLineHistory();
            }
            else
            {
                dayItemList = yahoo.GetDayLineHistory(starttime.AddDays(1), DateTime.Now);
            }

            if (dayItemList == null)
            {
                returnStr.Append(string.Format("获取雅虎财经:{0}{1}失败,没有新数据或网络异常!\n", m_StockCode, Suffix));
                return returnStr.ToString();
            }

            //插入最新的日线数据
            if (dayItemList.Count() > 0)
            {
                dailypriceservice.ImportPriceData(dayItemList);
                returnStr.Append(string.Format("股票:{0}{1}插入{2}条日线数据。\n", m_StockCode, Suffix, dayItemList.Count()));
            }

            //如果今天是星期六,则获取股票基础面信息
            if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
            {
                Eastmoney eastMoney = new Eastmoney(Suffix, m_StockCode);
                eastMoney.RefreshStockBase();
            }

            return returnStr.ToString();
        }
        public void CalculateGbceAllShareIndexTest()
        {
            var stock = new Stock("TEA", StockType.Common, 0, 0, 100);
            
            var trades = new List<Trade>();
            trades.Add(new Trade(stock, DateTime.Now, 5, TradeAction.Buy, 10));
            trades.Add(new Trade(stock, DateTime.Now, 10, TradeAction.Buy, 100));

            var gbceAllShareIndex = StockCalculator.CalculateGbceAllShareIndex(trades);
            AssertDiff(31.62277660168379m, gbceAllShareIndex);
        }
        public void DecreaseStockCount_By_Five_Stock_Is_Too_Low()
        {
            // Arrange
            Drug drug = new Drug("Ibuprophen");
            Fakes.FakeStockProvider stockProvider = new Fakes.FakeStockProvider(4);

            Stock stock = new Stock(stockProvider);

            // Act
            stock.DecreaseStock(drug, 5);
        }
        public void DecreaseStockCount_By_One_Stock_Is_Empty()
        {
            // Arrange
            Drug drug = new Drug("Ibuprophen");
            Fakes.FakeStockProvider stockProvider = new Fakes.FakeStockProvider(0);

            Stock stock = new Stock(stockProvider);

            // Act
            stock.DecreaseStock(drug, 1);
        }
        public void when_not_on_a_market_day_do_thing2() {
            var clock = new FakeClock(
                Instant.FromUtc(2016, 5, 8, 0, 0));
            var stock = new Stock();
            var marketDay = new MarketDay(
                Instant.FromUtc(2016, 5, 8, 0, 0));

            var myClass = new MyClassNodaTime(stock, marketDay, clock);

            Assert.Equal("Thing2 done!", myClass.thingState);
        }
        public void CalculateStockPriceTest()
        {
            var stock = new Stock("TEA", StockType.Common, 0, 0, 100);

            var trades = new List<Trade>();
            trades.Add(new Trade(stock, DateTime.Now, 5, TradeAction.Buy, 50));
            trades.Add(new Trade(stock, DateTime.Now, 10, TradeAction.Buy, 100));
            trades.Add(new Trade(stock, DateTime.Now, 10, TradeAction.Sell, 100));

            var stockPrice = StockCalculator.CalculateStockPrice(stock, trades);
            AssertDiff(90, stockPrice);
        }
        public bool Update(EditStockVm editStockVm, Stock stock)
        {
            if (editStockVm.Id == stock.Id)
            {
                stock.Symbol = editStockVm.Symbol;
                stock.Title = editStockVm.Title;

                return StockRepository.UpdateStock(stock).OperationSuccessStatus;
            }

            return false;
        }
        public void MultipleParcelsPartiallySold()
        {
            var stock = new Stock(Guid.NewGuid());

            stock.List("ABC", "ABC Pty Ltd", new Date(1974, 01, 01), false, AssetCategory.AustralianStocks);

            var transaction = new Disposal()
            {
                Id                    = Guid.NewGuid(),
                Date                  = new Date(2020, 02, 01),
                Stock                 = stock,
                Comment               = "Test Disposal",
                Units                 = 180,
                AveragePrice          = 20.00m,
                TransactionCosts      = 19.95m,
                CgtMethod             = CgtCalculationMethod.FirstInFirstOut,
                CreateCashTransaction = true
            };

            var mockRepository = new MockRepository(MockBehavior.Strict);

            var parcel1Id = Guid.NewGuid();
            var parcel1   = mockRepository.Create <IParcel>();

            parcel1.Setup(x => x.Id).Returns(parcel1Id);
            parcel1.Setup(x => x.EffectivePeriod).Returns(new DateRange(new Date(2007, 01, 01), Date.MaxValue));
            parcel1.Setup(x => x.AquisitionDate).Returns(new Date(2007, 01, 01));
            parcel1.Setup(x => x.Properties[new Date(2020, 02, 01)]).Returns(new ParcelProperties(100, 1000.00m, 1500.00m));

            var parcel2Id = Guid.NewGuid();
            var parcel2   = mockRepository.Create <IParcel>();

            parcel2.Setup(x => x.Id).Returns(parcel2Id);
            parcel2.Setup(x => x.EffectivePeriod).Returns(new DateRange(new Date(2008, 01, 01), Date.MaxValue));
            parcel2.Setup(x => x.AquisitionDate).Returns(new Date(2008, 01, 01));
            parcel2.Setup(x => x.Properties[new Date(2020, 02, 01)]).Returns(new ParcelProperties(50, 200.00m, 300.00m));

            var parcel3Id = Guid.NewGuid();
            var parcel3   = mockRepository.Create <IParcel>();

            parcel3.Setup(x => x.Id).Returns(parcel3Id);
            parcel3.Setup(x => x.EffectivePeriod).Returns(new DateRange(new Date(2009, 01, 01), Date.MaxValue));
            parcel3.Setup(x => x.AquisitionDate).Returns(new Date(2009, 01, 01));
            parcel3.Setup(x => x.Properties[new Date(2020, 02, 01)]).Returns(new ParcelProperties(200, 1500.00m, 2000.00m));

            var holding = mockRepository.Create <IHolding>();

            holding.Setup(x => x.IsEffectiveAt(new Date(2020, 02, 01))).Returns(true);
            holding.Setup(x => x.Properties[new Date(2020, 02, 01)]).Returns(new HoldingProperties(350, 2700.00m, 3800.00m));
            holding.Setup(x => x.Parcels(new Date(2020, 02, 01))).Returns(new IParcel[] { parcel1.Object, parcel2.Object, parcel3.Object });
            holding.Setup(x => x.DisposeOfParcel(parcel1Id, new Date(2020, 02, 01), 100, 1988.92m, 488.92m, CgtMethod.Discount, transaction)).Verifiable();
            holding.Setup(x => x.DisposeOfParcel(parcel2Id, new Date(2020, 02, 01), 50, 994.46m, 694.46m, CgtMethod.Discount, transaction)).Verifiable();
            holding.Setup(x => x.DisposeOfParcel(parcel3Id, new Date(2020, 02, 01), 30, 596.67m, 296.67m, CgtMethod.Discount, transaction)).Verifiable();

            var cashAccount = mockRepository.Create <ICashAccount>();

            cashAccount.Setup(x => x.Transfer(new Date(2020, 02, 01), 3600.00m, "Sale of ABC")).Verifiable();
            cashAccount.Setup(x => x.FeeDeducted(new Date(2020, 02, 01), 19.95m, "Brokerage for sale of ABC")).Verifiable();

            var handler = new DisposalHandler();

            handler.Apply(transaction, holding.Object, cashAccount.Object);

            mockRepository.Verify();
        }
        public static Portfolio CreateEmptyPortfolio()
        {
            var arg = new Stock(Stock_ARG.Id);

            arg.List(Stock_ARG.AsxCode, Stock_ARG.Name, new Date(2000, 01, 01), false, AssetCategory.AustralianStocks);
            _StockCache.Add(arg);

            arg.CorporateActions.AddCapitalReturn(ARG_CapitalReturn, new Date(2001, 01, 01), "ARG Capital Return", new Date(2001, 01, 02), 10.00m);

            var argStockPrice = new StockPriceHistory(arg.Id);

            arg.SetPriceHistory(argStockPrice);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 01), 1.00m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 03), 1.01m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 04), 1.00m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 05), 1.03m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 06), 1.02m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 07), 1.01m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 10), 1.05m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 14), 1.07m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 17), 1.08m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 01, 31), 1.09m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 02, 29), 1.10m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 03, 31), 1.07m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 04, 28), 1.07m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 05, 25), 1.03m);
            argStockPrice.UpdateClosingPrice(new Date(2000, 12, 29), 1.04m);
            argStockPrice.UpdateClosingPrice(new Date(2001, 01, 01), 1.05m);
            argStockPrice.UpdateClosingPrice(new Date(2001, 12, 31), 1.01m);
            argStockPrice.UpdateClosingPrice(new Date(2002, 12, 31), 0.99m);
            argStockPrice.UpdateClosingPrice(new Date(2003, 12, 31), 1.29m);
            argStockPrice.UpdateClosingPrice(new Date(2003, 05, 23), 1.40m);
            argStockPrice.UpdateClosingPrice(new Date(2007, 01, 02), 0.90m);
            argStockPrice.UpdateClosingPrice(new Date(2009, 01, 02), 1.70m);
            argStockPrice.UpdateClosingPrice(new Date(2010, 01, 01), 2.00m);

            var wam = new Stock(Stock_WAM.Id);

            wam.List(Stock_WAM.AsxCode, Stock_WAM.Name, new Date(2000, 01, 01), false, AssetCategory.AustralianStocks);
            _StockCache.Add(wam);

            wam.CorporateActions.AddSplitConsolidation(WAM_Split, new Date(2002, 01, 01), "WAM Split", 1, 2);

            var wamStockPrice = new StockPriceHistory(wam.Id);

            wam.SetPriceHistory(wamStockPrice);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 01), 1.20m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 03), 1.21m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 04), 1.20m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 05), 1.23m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 06), 1.22m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 07), 1.21m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 10), 1.25m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 14), 1.24m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 17), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 01, 31), 1.28m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 02, 29), 1.29m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 03, 31), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 04, 28), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 05, 25), 1.23m);
            wamStockPrice.UpdateClosingPrice(new Date(2000, 12, 29), 1.14m);
            wamStockPrice.UpdateClosingPrice(new Date(2001, 01, 01), 1.15m);
            wamStockPrice.UpdateClosingPrice(new Date(2001, 12, 31), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2002, 12, 31), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2003, 12, 31), 1.27m);
            wamStockPrice.UpdateClosingPrice(new Date(2003, 05, 23), 1.40m);
            wamStockPrice.UpdateClosingPrice(new Date(2005, 01, 02), 1.10m);
            wamStockPrice.UpdateClosingPrice(new Date(2007, 01, 02), 0.90m);
            wamStockPrice.UpdateClosingPrice(new Date(2009, 01, 02), 1.30m);
            wamStockPrice.UpdateClosingPrice(new Date(2010, 01, 01), 1.50m);

            var portfolioFactory = new PortfolioFactory(StockResolver);
            var portfolio        = portfolioFactory.CreatePortfolio(Guid.NewGuid());

            portfolio.Create("Test", Guid.NewGuid());

            // Remove Events
            portfolio.FetchEvents();

            return(portfolio);
        }
Beispiel #33
0
 public FakeFigureProviderContext()
 {
     Stock = new Stock();
 }
Beispiel #34
0
        private void ExecuteSingleCommand(string[] commandParameters)
        {
            string commandType = string.Empty;

            try
            {
                Console.WriteLine();
                commandType = commandParameters[0];
            }
            catch
            {
                //this catch the IndexOutOfRange Exception and throws the error message of the Default of the Switch
            }
            int           employeeId;
            decimal       ratePerMinute;
            IEmployee     employee;
            ICounterparty supplier;
            ICounterparty client;
            IVehicle      vehicle;
            decimal       salary;
            //IOrderStock orderStock;
            IStock         stock;
            string         position;
            DepartmentType department;
            VehicleType    vehicleType;
            EngineType     engineType;
            IVehicle       newVehicle = null;
            string         assetName;
            string         stockUniqueNumber;
            string         bankAccountNumber;
            string         employeeFirstName;
            string         employeeLastName   = "";
            string         employeeDepartment = "";
            string         supplierUniqueNumber;
            string         supplierUniqueName;
            string         supplierAddress;
            string         clientUniquieNumber;
            string         clientUniqueName;
            string         clientAddress;
            string         vehicleMake;
            string         vehicleModel;
            string         vehicleRegistrationNumber;


            switch (commandType)
            {
            case "showEmployees":

                Validate.EmployeeCount(this.employees.Count);

                this.ShowEmployees();
                break;

            case "hireEmployee":

                Validate.ExactParameterLength(commandParameters, 7);

                employeeFirstName = commandParameters[1];
                employeeLastName  = commandParameters[2];
                position          = commandParameters[3];

                salary = Validate.DecimalFromString(commandParameters[4], "salary");

                ratePerMinute = Validate.DecimalFromString(commandParameters[5], "ratePerMinute");

                employeeDepartment = commandParameters[6];
                department         = Validate.DepartmentTypeFromString(employeeDepartment, "department");

                Validate.EmployeeAlreadyExistOnHire(this.employees, employeeFirstName, employeeLastName, employeeDepartment);

                this.AddEmployee(employeeFirstName, employeeLastName, position, salary, ratePerMinute, department);

                break;

            case "fireEmployee":

                Validate.ExactParameterLength(commandParameters, 2);

                Validate.EmployeeCount(this.employees.Count);

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                this.FireEmployee(employee);
                break;

            case "changeEmployeeRate":

                Validate.ExactParameterLength(commandParameters, 3);

                Validate.EmployeeCount(this.employees.Count);

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                ratePerMinute = Validate.DecimalFromString(commandParameters[2], "ratePerMinute");

                this.ChangeRateOfEmployee(employee, ratePerMinute);
                break;

            case "issueInvoices":
                Validate.ExactParameterLength(commandParameters, 1);

                this.IssueInvoices();

                break;

            case "showAllEmployeesAtDepartment":

                Validate.ExactParameterLength(commandParameters, 2);

                department = Validate.DepartmentTypeFromString(commandParameters[1], "department");

                this.ListEmployeesAtDepartment(department);
                break;

            case "changeEmployeePosition":

                Validate.ExactParameterLength(commandParameters, 3);

                Validate.EmployeeCount(this.employees.Count);

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                position = commandParameters[2];

                this.ChangePositionOfEmployee(employee, position);
                break;

            case "addEmployeeResponsibility":

                Validate.MinimumParameterLength(commandParameters, 3);

                Validate.EmployeeCount(this.employees.Count);

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                var responsibilitiesToAdd = commandParameters.Skip(2).ToArray();
                this.AddResponsibilitiesToEmployee(employee, responsibilitiesToAdd);

                break;

            case "removeEmpoloyeeResponsibility":

                Validate.MinimumParameterLength(commandParameters, 3);

                Validate.EmployeeCount(this.employees.Count);

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                var responsibilitiesToRemove = commandParameters.Skip(2).ToArray();

                this.RemoveResponsibilitiesToEmployee(employee, responsibilitiesToRemove);

                break;

            case "addVehicleToClient":
                //addVehicleToClient;Car;BMW;E39;CA1234AC;1999;Petrol;5;TelerikAcademy
                Validate.ExactParameterLength(commandParameters, 9);

                vehicleType  = Validate.VehicleTypeFromString(commandParameters[1], "vehicle type");
                vehicleMake  = commandParameters[2];
                vehicleModel = commandParameters[3];
                vehicleRegistrationNumber = commandParameters[4];
                string vehicleYear = commandParameters[5];
                engineType = Validate.EngineTypeFromString(commandParameters[6], "engine type");
                var additionalParams = Validate.IntFromString(commandParameters[7], "additional parameters");

                Validate.CounterpartyNotRegistered(this.clients, commandParameters[8], "client");

                clientUniqueName = commandParameters[8];

                client = this.clients.FirstOrDefault(x => x.Name == clientUniqueName);

                if (((IClient)client).Vehicles.Any(x => x.RegistrationNumber == vehicleRegistrationNumber))
                {
                    throw new ArgumentException(
                              $"This client already has a vehicle with this registration number: {vehicleRegistrationNumber}.");
                }
                newVehicle = CreateVehicle(vehicleType, vehicleMake, vehicleModel, vehicleRegistrationNumber,
                                           vehicleYear, engineType, additionalParams);

                ((IClient)client).Vehicles.Add((Vehicle)newVehicle);
                Console.WriteLine(newVehicle);

                Console.WriteLine($"Vehicle {vehicleMake} {vehicleModel} added to client {client.Name}");
                break;

            case "createBankAccount":

                Validate.ExactParameterLength(commandParameters, 4);

                if (this.employees.Count == 0)
                {
                    throw new InvalidOperationException(
                              "No employees currently in the service! You need to hire one then open the bank account :)");
                }

                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                assetName = commandParameters[2];

                Validate.ValidateBankAccount(commandParameters[3]);
                bankAccountNumber = commandParameters[3];

                DateTime currentAssetDate = this.lastAssetDate.AddDays(5);     //fixed date in order to check zero tests

                this.CreateBankAccount(employee, assetName, currentAssetDate, bankAccountNumber);
                break;

            case "depositCashInBank":

                Validate.ExactParameterLength(commandParameters, 3);

                Validate.BankAccountsCount(this.bankAccounts.Count);

                int bankAccountId = Validate.IntFromString(commandParameters[1], "bankAccountId");

                BankAccount bankAccount = Validate.BankAccountById(this.bankAccounts, bankAccountId);

                decimal depositAmount = Validate.DecimalFromString(commandParameters[2], "depositAmount");

                this.DepositCashInBankAccount(bankAccount, depositAmount);
                break;

            case "sellStockToClientVehicle":
                //sellStockToClientVehicle; Jo; 123456789; CA1234AC; RT20134HP; Manarino; Management
                Validate.EitherOrParameterLength(commandParameters, 5, 7);

                employeeFirstName         = commandParameters[1];
                clientUniqueName          = commandParameters[2];
                vehicleRegistrationNumber = commandParameters[3];
                stockUniqueNumber         = commandParameters[4];
                employeeLastName          = "";
                string employeeDepartmentName = "";

                if (commandParameters.Length == 7)
                {
                    employeeLastName       = commandParameters[5];
                    employeeDepartmentName = commandParameters[6];
                    employee = Validate.EmployeeUnique(this.employees, employeeFirstName, employeeLastName,
                                                       employeeDepartmentName);
                }
                else
                {
                    employee = Validate.EmployeeUnique(this.employees, employeeFirstName, null, null);
                }

                Validate.CounterpartyNotRegistered(this.clients, clientUniqueName, "client");

                client = this.clients.FirstOrDefault(x => x.Name == clientUniqueName);

                //stock we sell must be present in the warehouse :)
                bool stockExists = this.warehouse.ConfirmStockExists(stockUniqueNumber, employee);
                if (stockExists == false)
                {
                    throw new ArgumentException(
                              $"Trying to sell the stock with unique ID {stockUniqueNumber} that is not present in the Warehouse");
                }
                stock = this.warehouse.AvailableStocks.FirstOrDefault(x => x.UniqueNumber == stockUniqueNumber);

                //no need to check vehicle for null because we create a default vehicle with every client registration
                vehicle = ((IClient)client).Vehicles.FirstOrDefault(x =>
                                                                    x.RegistrationNumber == vehicleRegistrationNumber);

                this.SellStockToClient(stock, (IClient)client, vehicle);

                break;

            case "sellServiceToClientVehicle":
                //sellServiceToClientVehicle; Jo; 123456789; CA1234AC; Disk change; 240; Manarino; Management

                //we can sell services to client without vehicle, e.g. client brings old tire rim for repair
                Validate.EitherOrParameterLength(commandParameters, 6, 8);

                employeeFirstName         = commandParameters[1];
                clientUniqueName          = commandParameters[2];
                vehicleRegistrationNumber = commandParameters[3];
                var serviceName = commandParameters[4];

                int durationInMinutes = Validate.IntFromString(commandParameters[5], "duration in minutes");

                if (commandParameters.Length == 8)
                {
                    employeeLastName   = commandParameters[6];
                    employeeDepartment = commandParameters[7];
                    employee           = Validate.EmployeeUnique(this.employees, employeeFirstName, employeeLastName,
                                                                 employeeDepartment);
                }
                else
                {
                    employee = Validate.EmployeeUnique(this.employees, employeeFirstName, null, null);
                }

                Validate.CounterpartyNotRegistered(this.clients, clientUniqueName, "client");
                client = this.clients.FirstOrDefault(x => x.Name == clientUniqueName);

                vehicle = ((IClient)client).Vehicles.FirstOrDefault(x =>
                                                                    x.RegistrationNumber == vehicleRegistrationNumber);

                this.SellServiceToClient(employee, (IClient)client, vehicle, serviceName, durationInMinutes);

                break;


            case "orderStockToWarehouse":
                //orderStockToWarehouse;Jo;AXM-AUTO;Rotinger HighPerformance Brake Disks;RT20134HP;180;Manarino;Management

                Validate.EitherOrParameterLength(commandParameters, 6, 8);



                employeeFirstName = commandParameters[1];
                if (commandParameters.Length == 8)
                {
                    employee = Validate.EmployeeUnique(this.employees, employeeFirstName, commandParameters[6], commandParameters[7]);
                }
                else
                {
                    employee = Validate.EmployeeUnique(this.employees, employeeFirstName, null, null);
                }

                supplierUniqueName = commandParameters[2];

                Validate.CounterpartyNotRegistered(this.suppliers, supplierUniqueName, "supplier");
                supplier = this.suppliers.FirstOrDefault(x => x.Name == supplierUniqueName);

                var stockName = commandParameters[3];

                stockUniqueNumber = commandParameters[4];

                decimal purchasePrice = Validate.DecimalFromString(commandParameters[5], "purchasePrice");

                stock = new Stock(stockName, employee, stockUniqueNumber, purchasePrice, supplier);

                this.OrderStockFromSupplier(stock);
                break;

            case "registerSupplier":
                //registerSupplier;AXM - AUTO;54 Yerusalim Blvd Sofia Bulgaria;211311577
                Validate.ExactParameterLength(commandParameters, 4);

                supplierUniqueName   = commandParameters[1];
                supplierAddress      = commandParameters[2];
                supplierUniqueNumber = commandParameters[3];

                Validate.CounterpartyAlreadyRegistered(this.suppliers, supplierUniqueName, "supplier");

                this.AddSupplier(supplierUniqueName, supplierAddress, supplierUniqueNumber);
                Console.WriteLine("Supplier registered sucessfully");
                break;

            case "changeSupplierName":
                //changeSupplierName; VintchetaBolchetaGaiki; VintchetaBolchetaGaikiNew
                Validate.ExactParameterLength(commandParameters, 3);
                supplierUniqueName = commandParameters[1];
                var supplierNewUniqueName = commandParameters[2];
                Validate.CounterpartyNotRegistered(this.suppliers, supplierUniqueName, "supplier");

                this.ChangeCounterpartyName(supplierUniqueName, this.suppliers, supplierNewUniqueName);

                Console.WriteLine($"{supplierUniqueName} changed sucessfully to {supplierNewUniqueName}");
                break;

            case "removeSupplier":

                Validate.ExactParameterLength(commandParameters, 2);

                supplierUniqueName = commandParameters[1];

                Validate.CounterpartyNotRegistered(this.suppliers, supplierUniqueName, "supplier");
                this.RemoveCounterparty(supplierUniqueName, this.suppliers);
                break;

            case "registerClient":

                Validate.ExactParameterLength(commandParameters, 4);

                clientUniqueName    = commandParameters[1];
                clientAddress       = commandParameters[2];
                clientUniquieNumber = commandParameters[3];

                Validate.CounterpartyAlreadyRegistered(this.clients, clientUniqueName, "client");
                this.AddClient(clientUniqueName, clientAddress, clientUniquieNumber);

                //add default car to the client
                client     = this.clients.FirstOrDefault(x => x.UniqueNumber == clientUniquieNumber);
                newVehicle = CreateVehicle(VehicleType.Car, "Empty", "Empty", "123456", "2000", EngineType.Petrol,
                                           5);
                ((IClient)client).Vehicles.Add((Vehicle)newVehicle);
                Console.WriteLine(newVehicle);

                Console.WriteLine($"Default Vehicle added to client {client.Name}");

                break;

            case "changeClientName":
                //changeClientName; ClientSuperDuper; clientNewUniqueNameNew
                Validate.ExactParameterLength(commandParameters, 3);

                clientUniqueName = commandParameters[1];
                Validate.CounterpartyNotRegistered(this.clients, clientUniqueName, "client");

                var clientNewUniqueName = commandParameters[2];
                this.ChangeCounterpartyName(clientUniqueName, this.clients, clientNewUniqueName);
                Console.WriteLine($"{clientUniqueName} name changed sucessfully to {clientNewUniqueName}");
                break;

            case "removeClient":

                Validate.ExactParameterLength(commandParameters, 2);

                clientUniqueName = commandParameters[1];

                Validate.CounterpartyNotRegistered(this.clients, clientUniqueName, "client");
                this.RemoveCounterparty(clientUniqueName, this.clients);

                break;

            case "listWarehouseItems":
                this.ListWarehouseItems();
                break;

            case "addClientPayment":
                //addClientPayment;<clientName>;<bankAccountId>;<invoiceNum>;<amount>
                Validate.ExactParameterLength(commandParameters, 5);

                clientUniqueName = commandParameters[1];
                Validate.CounterpartyNotRegistered(this.clients, clientUniqueName, "client");
                client = this.clients.FirstOrDefault(f => f.Name == clientUniqueName);

                bankAccountId = Validate.IntFromString(commandParameters[2], "bankAccountId");
                Validate.BankAccountById(this.bankAccounts, bankAccountId);
                IInvoice invoiceFound  = Validate.InvoiceExists(this.clients, client, commandParameters[3]);
                decimal  paymentAmount = Validate.DecimalFromString(commandParameters[4], "decimal");

                this.AddClientPayment(invoiceFound, paymentAmount);

                break;

            case "listClients":
                this.ListClients();
                break;

            case "withdrawCashFromBank":
                //withdrawCashFromBank;<employeeId>;<bankAccountId>;<amount>

                Validate.ExactParameterLength(commandParameters, 4);

                Validate.BankAccountsCount(this.bankAccounts.Count);
                employeeId = Validate.IntFromString(commandParameters[1], "employeeId");

                employee = Validate.EmployeeById(this.employees, employeeId);

                bankAccountId = Validate.IntFromString(commandParameters[2], "bankAccountId");

                bankAccount = Validate.BankAccountById(this.bankAccounts, bankAccountId);

                decimal withdrawAmount = Validate.DecimalFromString(commandParameters[3], "depositAmount");

                this.WithdrawCashFromBank(bankAccount, withdrawAmount, employee);

                break;

            case "help":
                this.HelpThem();
                break;

            default:
                throw new NotSupportedException("Command not supported yet! Please call IT Support or raise a TT");
            }
        }
Beispiel #35
0
 public StockScreen(Stock stocks)
 {
     InitializeComponent();
     base.DataContext = stocks;
 }
 public void Add(Stock entity)
 {
     stockRepository.Add(entity);
 }
Beispiel #37
0
 public IActionResult UpdateEntry(Stock stock)
 {
     return(View(stock));
 }
Beispiel #38
0
        public async Task <IHttpActionResult> AddStockList([FromBody] List <StockIn> stockInList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            using (var connection = new SqlConnection(sqlConnectionString))
            {
                connection.Open();
                foreach (var stockIn in stockInList)
                {
                    List <int> BatchIds = new List <int>();
                    int        quantity = 0;
                    foreach (var item in stockIn.Batch)
                    {
                        var batchDetails = new Batch
                        {
                            BatchName         = item.BatchName,
                            Quantity          = item.Quantity,
                            WarehouseID       = item.WarehouseID,
                            MfgDate           = item.MfgDate,
                            ExpDate           = item.ExpDate,
                            ESL               = item.ESL,
                            AvailableQuantity = item.Quantity,
                            BatchCode         = item.BatchCode,
                            BatchNo           = item.BatchNo,
                            SectionID         = item.SectionID
                        };
                        quantity             = quantity + item.Quantity;
                        batchDetails.BatchId = connection.Query <int>(@"insert BatchMaster(BatchName,Quantity,WarehouseID,MFGDate,EXPDate,ESL,AvailableQuantity,BatchCode,BatchNo,SectionID) values (@BatchName,@Quantity,@WarehouseID,@MFGDate,@EXPDate,@ESL,@AvailableQuantity,@BatchCode,@BatchNo,@SectionID) select cast(scope_identity() as int)", batchDetails).First();
                        BatchIds.Add(batchDetails.BatchId);
                    }


                    var stockInDetails = new Stock
                    {
                        BatchIdFromMobile = String.Join(",", BatchIds),
                        RecievedOn        = stockIn.stock.RecievedOn,
                        CRVNo             = stockIn.stock.CRVNo,
                        Remarks           = stockIn.stock.Remarks,
                        RecievedFrom      = stockIn.stock.RecievedFrom,
                        PackingMaterial   = stockIn.stock.PackingMaterial,
                        OriginalManf      = stockIn.stock.OriginalManf,
                        GenericName       = stockIn.stock.GenericName,
                        Weight            = stockIn.stock.Weight,
                        AddedOn           = DateTime.Now,
                        SupplierId        = stockIn.stock.SupplierId,
                        //  IsActive = stockIn.stock.IsActive,
                        ProductId     = stockIn.stock.ProductId,
                        Quantity      = stockIn.stock.Quantity,
                        IsFromMobile  = stockIn.stock.IsFromMobile,
                        ATNo          = stockIn.stock.ATNo,
                        OtherSupplier = stockIn.stock.OtherSupplier,
                        //  TransferedBy = TransferedBy,
                        SampleSent = stockIn.stock.SampleSent,
                        SupplierNo = stockIn.stock.SupplierNo,
                        DepotId    = stockIn.stock.DepotId,
                        IsCP       = stockIn.stock.IsCP,
                        IsLP       = stockIn.stock.IsLP,
                        IsIDT      = stockIn.stock.IsIDT,
                        IsICT      = stockIn.stock.IsICT,
                    };

                    stockInDetails.StockInId = connection.Query <int>(@"insert StockMaster(BatchIdFromMobile,RecievedOn,CRVNo,Remarks,RecievedFrom,
                                         PackingMaterial,OriginalManf,GenericName,Weight,AddedOn,SupplierId,ProductId,Quantity,IsFromMobile,ATNo,OtherSupplier,TransferedBy,SampleSent,SupplierNo,DepotId,IsCP,IsLP,IsIDT,IsICT
) values (@BatchIdFromMobile,@RecievedOn,@CRVNo,@Remarks,@RecievedFrom,
                                         @PackingMaterial,@OriginalManf,@GenericName,@Weight,@AddedOn,@SupplierId,@ProductId,@Quantity,@IsFromMobile,@ATNo,@OtherSupplier,@TransferedBy,@SampleSent,@SupplierNo,@DepotId,@IsCP,@IsLP,@IsIDT,@IsICT) select cast(scope_identity() as int)", stockInDetails).First();
                }
                return(Json(new { Message = "Record Inserted Successfully" }));
            }
        }
 public void Delete(Stock entity)
 {
     entity.IsActive = false;
     stockRepository.Edit(entity);
 }
        public bool Handle(IRequestMessage msg)
        {
            try
            {
                Type msgType = msg.GetType();
                if (typeof(IRequestMessage).IsAssignableFrom(msgType))
                {
                    if (typeof(NewSingleOrder) == msgType)
                    {
                        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                        sw.Start();
                        Counters.IncrementCounter(CountersConstants.ClientsNewOrderReqs);

                        NewSingleOrder order = (NewSingleOrder)msg;

                        #region validate client key
                        if (order.ClientKey == Guid.Empty || order.ClientKey == null)
                        {
                            SystemLogger.LogEventAsync(string.Format("ClientKey [{0}] not valid! ", order.ClientKey.ToString()));
                            return(true);
                        }
                        string username = Sessions.GetUsername(order.ClientKey);
                        if (!Sessions.IsSubscribedToSendMsg(username))
                        {
                            SystemLogger.LogEventAsync(string.Format("ClientKey [{0}] not subscribed", order.ClientKey));
                            return(true);
                        }
                        #endregion validate client key

                        #region validate stock group
                        Stock stock = StocksDefinitions.GetStockByCode(order.SecurityID);
                        if (stock == null)
                        {
                            Sessions.Push(Sessions.GetUsername(order.ClientKey), new IResponseMessage[] { new Fix_OrderRefusedByService()
                                                                                                          {
                                                                                                              ClientKey = order.ClientKey, RefuseMessage = "Stock Not Found!", RequesterOrderID = order.RequesterOrderID
                                                                                                          } });
                        }
                        #endregion validate stock group

                        #region validate currency
                        CurrencyItem currency = Currencies.GetCurrencyByCode(stock.CurrencyCode);
                        #endregion validate currency

                        #region validate order details
                        string validation = ValidateOrder(username, order);
                        #endregion validate order details

                        #region not valid order

                        if (validation != "valid")
                        {
                            try
                            {
                                SystemLogger.LogEventAsync(string.Format("OrderRefusedByService RequesterOrderID: {0}, Reason: {1}", order.RequesterOrderID, validation));
                                Sessions.Push(Sessions.GetUsername(order.ClientKey), new IResponseMessage[] { new Fix_OrderRefusedByService()
                                                                                                              {
                                                                                                                  ClientKey = order.ClientKey, RefuseMessage = validation, RequesterOrderID = order.RequesterOrderID
                                                                                                              } });
                            }
                            catch (Exception ex)
                            {
                                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                                SystemLogger.LogEventAsync(string.Format("Error sending refused order to the client, ClientKey {0}, Error: {1}", order.ClientKey, ex.Message));
                            }
                            return(true);
                        }
                        #endregion not valid order

                        OrdersManager.HandleNewSingleOrder(username, order.ClientKey, order.RequesterOrderID, order.ClientID, order.CustodyID, order.SecurityID, order.OrderSide, Math.Round(order.Price, m_orderPriceDigitsRounding), order.Quantity, order.OrderType, DateTime.Now, order.TimeInForce, currency, order.ExchangeID, order.DateTime, stock.GroupID, stock.MarketID, order.HandleInst, order.ExpirationDateTime, order.OptionalParam);
                        sw.Stop();
                        SystemLogger.LogEventAsync(string.Format("new order handled in {0} ms ", sw.ElapsedMilliseconds));
                        sw = null;
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                SystemLogger.LogErrorAsync("NewSingleOrderHandler Error: " + ex.Message);
                return(true);
            }
        }
Beispiel #41
0
 public static TransactionItem CreateTransactionItem(this Transaction transaction, Stock stock, int quantity)
 {
     return(new TransactionItem {
         Stock = stock, Quantity = quantity, Transaction = transaction
     });
 }
Beispiel #42
0
 public static bool UpdateStockObjectWithIndicesData(StockQuote qoute, ref Stock stock)
 {
     //stock = qoute.openPrice;
     //stock.today_Close = qoute.closePrice
     return(false);
 }
Beispiel #43
0
 public StockPurchaseTransaction(Stock stock, int quantity, decimal price) : base(stock, quantity, price)
 {
 }
Beispiel #44
0
        public async Task <IHttpActionResult> AddStock([FromBody] StockIn stockIn)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                using (TransactionScope scope = new TransactionScope())

                    using (var connection = new SqlConnection(sqlConnectionString))
                    {
                        connection.Open();
                        Nullable <int> IdtMasterId = 0;
                        Nullable <int> CptMasterId = 0;
                        if (stockIn.stock.IsIDT || stockIn.stock.IsICT)
                        {
                            var IdtMaster = connection.Query <firstForm>("Select * from IdtIcTMaster where ReferenceNumber = @ReferenceNumber", new { ReferenceNumber = stockIn.stock.ReferenceNumber }).FirstOrDefault();
                            if (IdtMaster == null)
                            {
                                return(Json(new { Message = "Please select valid Idt Reference Number" }));
                            }
                            else
                            {
                                var IdtDetails = connection.Query <depotProductValueModel>("Select * from IdtIctDetails where IdtIctMasterId=@IdtIctMasterId", new { IdtIctMasterId = IdtMaster.Id }).ToList();
                                // IsProduct Exist
                                var isProduct = IdtDetails.Find(t => t.productId == stockIn.stock.ProductId);
                                var isDepot   = IdtDetails.Find(t => t.depotId == stockIn.stock.DepotId);
                                if (isProduct == null || isDepot == null)
                                {
                                    return(Json(new { Message = "Please select valid depot and product" }));
                                }
                                else
                                {
                                    // FindCurrentIdtDetails
                                    var currentIdtDetails = IdtDetails.Find(t => t.depotId == stockIn.stock.DepotId && t.productId == stockIn.stock.ProductId);
                                    if (stockIn.stock.Quantity > Convert.ToInt32(currentIdtDetails.AvailableQuantity))
                                    {
                                        return(Json(new { Message = "Quantity Not available" }));
                                    }

                                    var NewAvailableQuantity = Convert.ToInt32(currentIdtDetails.AvailableQuantity) - stockIn.stock.Quantity;
                                    var ModifiedOn           = DateTime.Now;
                                    var Id = currentIdtDetails.Id;
                                    IdtMasterId = IdtMaster.Id;
                                    string updateQuery = @"UPDATE IdtIctDetails SET AvailableQuantity=@NewAvailableQuantity,ModifiedOn=@ModifiedOn where  Id = @Id";
                                    var    Status      = "InProgress";
                                    //FInd available Quanity



                                    var result = connection.Execute(updateQuery, new
                                    {
                                        NewAvailableQuantity,
                                        ModifiedOn,
                                        Id
                                    });
                                    //var results2 = connection.Execute(updateMaster, new
                                    //{
                                    //    Status,
                                    //    Id

                                    //});
                                }
                            }
                        }
                        else
                        {
                            var CPMaster = connection.Query <CPLTMaster>("Select * from CPLTMaster where ReferenceNumber = @ReferenceNumber", new { ReferenceNumber = stockIn.stock.ReferenceNumber }).FirstOrDefault();
                            if (CPMaster == null)
                            {
                                return(Json(new { Message = "Please select valid CP Reference Number" }));
                            }
                            else
                            {
                                var CpDetails = connection.Query <CPLTDetails>("Select * from CPLTDetails where CPLTId = @CPLTId", new { CPLTId = CPMaster.Id }).ToList();
                                // IsProduct Exist
                                var isProduct = CpDetails.Find(t => t.ProdId == stockIn.stock.ProductId);
                                //  var isDepot = IdtDetails.Find(t => t.depotId == stockIn.stock.DepotId);
                                if (isProduct == null)
                                {
                                    return(Json(new { Message = "Please select valid depot and product" }));
                                }
                                else
                                {
                                    // FindCurrentCptDetails
                                    var currentCPTDetails = CpDetails.Find(t => t.ProdId == stockIn.stock.ProductId);
                                    if (stockIn.stock.Quantity > Convert.ToInt32(currentCPTDetails.AvailableQuantity))
                                    {
                                        return(Json(new { Message = "Quantity Not available" }));
                                    }

                                    var NewAvailableQuantity = Convert.ToInt32(currentCPTDetails.AvailableQuantity) - stockIn.stock.Quantity;
                                    var ModifiedOn           = DateTime.Now;
                                    var Id = currentCPTDetails.Id;
                                    CptMasterId = CPMaster.Id;
                                    string updateQuery = @"UPDATE CPLTDetails SET AvailableQuantity=@NewAvailableQuantity,ModifiedOn=@ModifiedOn where  Id = @Id";
                                    // string updateQuery = @"UPDATE IdtIcTMaster SET IdtIctType = @IdtIctType,ReferenceNumber=@ReferenceNumber,DateOfEntry=@DateOfEntry,Status=@Status WHERE Id = @Id";

                                    var result = connection.Execute(updateQuery, new
                                    {
                                        NewAvailableQuantity,
                                        ModifiedOn,
                                        Id
                                    });
                                }
                            }
                        }
                        var identity = (ClaimsIdentity)User.Identity;
                        var userId   = identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
                                       .Select(c => c.Value).SingleOrDefault();
                        List <int> BatchIds = new List <int>();
                        int        quantity = 0;
                        foreach (var item in stockIn.Batch)
                        {
                            var batchDetails = new Batch
                            {
                                BatchName   = item.BatchName,
                                Quantity    = item.Quantity,
                                WarehouseID = item.WarehouseID,

                                MfgDate           = item.MfgDate,
                                ExpDate           = item.ExpDate,
                                ESL               = item.ESL,
                                AvailableQuantity = item.Quantity,
                                BatchCode         = item.BatchCode,
                                BatchNo           = item.BatchNo,
                                AddedOn           = DateTime.Now,
                                SectionID         = item.SectionID,
                            };
                            quantity             = quantity + item.Quantity;
                            batchDetails.BatchId = connection.Query <int>(@"insert BatchMaster(BatchName,Quantity,WarehouseID,MFGDate,EXPDate,ESL,AvailableQuantity,BatchCode,BatchNo,AddedOn,SectionID) values (@BatchName,@Quantity,@WarehouseID,@MFGDate,@EXPDate,@ESL,@AvailableQuantity,@BatchCode,@BatchNo,@AddedOn,@SectionID) select cast(scope_identity() as int)", batchDetails).First();
                            BatchIds.Add(batchDetails.BatchId);
                        }
                        if (CptMasterId == 0)
                        {
                        }

                        var stockInDetails = new Stock
                        {
                            BatchIdFromMobile = String.Join(",", BatchIds),
                            RecievedOn        = stockIn.stock.RecievedOn,
                            CRVNo             = stockIn.stock.CRVNo,
                            Remarks           = stockIn.stock.Remarks,
                            RecievedFrom      = stockIn.stock.RecievedFrom,
                            PackingMaterial   = stockIn.stock.PackingMaterial,
                            OriginalManf      = stockIn.stock.OriginalManf,
                            GenericName       = stockIn.stock.GenericName,
                            Weight            = stockIn.stock.Weight,
                            AddedOn           = DateTime.Now,
                            SupplierId        = stockIn.stock.SupplierId,
                            //  IsActive = stockIn.stock.IsActive,
                            ProductId     = stockIn.stock.ProductId,
                            Quantity      = stockIn.stock.Quantity,
                            IsFromMobile  = stockIn.stock.IsFromMobile,
                            ATNo          = stockIn.stock.ATNo,
                            OtherSupplier = stockIn.stock.OtherSupplier,
                            //  TransferedBy = TransferedBy,
                            SampleSent  = stockIn.stock.SampleSent,
                            SupplierNo  = stockIn.stock.SupplierNo,
                            DepotId     = stockIn.stock.DepotId,
                            IsCP        = stockIn.stock.IsCP,
                            IsLP        = stockIn.stock.IsLP,
                            IsIDT       = stockIn.stock.IsIDT,
                            IsICT       = stockIn.stock.IsICT,
                            IdtMasterId = IdtMasterId == 0 ? null : IdtMasterId,
                            CptMasterId = CptMasterId == 0 ? null : CptMasterId
                        };


                        stockInDetails.StockInId = connection.Query <int>(@"insert StockMaster(BatchIdFromMobile,RecievedOn,CRVNo,Remarks,RecievedFrom,
                                         PackingMaterial,OriginalManf,GenericName,Weight,AddedOn,SupplierId,ProductId,Quantity,IsFromMobile,ATNo,OtherSupplier,TransferedBy,SampleSent,SupplierNo,DepotId,IsCP,IsLP,IsIDT,IsICT,IdtMasterId,CptMasterId
) values (@BatchIdFromMobile,@RecievedOn,@CRVNo,@Remarks,@RecievedFrom,
                                         @PackingMaterial,@OriginalManf,@GenericName,@Weight,@AddedOn,@SupplierId,@ProductId,@Quantity,@IsFromMobile,@ATNo,@OtherSupplier,@TransferedBy,@SampleSent,@SupplierNo,@DepotId,@IsCP,@IsLP,@IsIDT,@IsICT,@IdtMasterId,@CptMasterId) select cast(scope_identity() as int)", stockInDetails).First();

                        //Update IdtMaster

                        scope.Complete();
                        return(Json(new { Message = "Record Inserted Successfully" }));
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 /// <summary>
 /// used to Update the quntity of Stock of Product of Particular WarehouseID and warehouse AddressId
 /// </summary>
 /// <param name="stock">contains user entered information like Warehouseid,warehouse addreesid and Productid</param>
 public void UpdateStockQuantity(Stock stock)
 {
     stockDataAccesslogic.UpdateStockQuantity(stock);
 }
Beispiel #46
0
 public void Insert(Stock stock)
 {
     context.Stocks.InsertOnSubmit(stock);
     context.SubmitChanges();
 }
Beispiel #47
0
 public void Update(Stock stock)
 {
     Console.WriteLine("Notified {0} of {1}'s " + "change to {2:C}", _name, stock.Symbol, stock.Price);
 }
 public ProductEntity(ProductName name, Price price, Stock stock)
 {
     Name  = name;
     Price = price;
     Stock = stock;
 }
        public DataTable Search(Stock stock)
        {
            sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();

            if (stock.CategoryName == "")
            {
                commandString = @"select Items.ItemName,
            iv.CompanyName,
            iv.CategoryName,
            Items.ReOrderQuantity,
            ( case when ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) is null
            then 0 else  ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) end )as Quantity
             from itemsview iv
             inner join Items on Items.Id = iv.Id
             where CompanyName = '" + stock.CompanyName + "'";
            }
            else if (stock.CompanyName == "")
            {
                commandString = @"select Items.ItemName,
            iv.CompanyName,
            iv.CategoryName,
            Items.ReOrderQuantity,
            ( case when ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) is null
            then 0 else  ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) end )as Quantity
             from itemsview iv
             inner join Items on Items.Id = iv.Id
             where categoryname = '" + stock.CategoryName + "'";
            }
            else
            {
                commandString = @"select Items.ItemName,
            iv.CompanyName,
            iv.CategoryName,
            Items.ReOrderQuantity,
            ( case when ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) is null
            then 0 else  ((select sum(quantity) from Stocks where Itemid = items.id and stockStatus = 'StockIn')
            - case when (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') is not null
            then  (select sum(quantity) from Stocks where Itemid = items.id and stockStatus != 'StockIn') else 0 end ) end )as Quantity
             from itemsview iv
             inner join Items on Items.Id = iv.Id
             where categoryname = '" + stock.CategoryName + "' AND CompanyName = '" + stock.CompanyName + "' ";
            }
            sqlCommand = new SqlCommand(commandString, sqlConnection);
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
            DataTable dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            sqlConnection.Close();

            return dataTable;
        }
 public void SetStock(Stock stock)
 {
     Stock = stock;
 }
Beispiel #51
0
 public void Delete(Stock stock)
 {
     _databaseContext.Stocks.Remove(stock);
     _databaseContext.SaveChanges();
 }
Beispiel #52
0
        public static void DbInitialize(MasterDBContext context)
        {
            context.Database.EnsureCreated();

            // Look for any Entrys.
            if (context.Articles.Any())
            {
                return;   // DB has been seeded
            }
            // Article Types
            var articleTypes = new ArticleType[]
            {
                new ArticleType {
                    Name = "Assembly"
                },
                new ArticleType {
                    Name = "Material"
                },
                new ArticleType {
                    Name = "Consumable"
                }
            };

            foreach (ArticleType at in articleTypes)
            {
                context.ArticleTypes.Add(at);
            }
            context.SaveChanges();

            // Units
            var units = new Unit[]
            {
                new Unit {
                    Name = "Kilo"
                },
                new Unit {
                    Name = "Litre"
                },
                new Unit {
                    Name = "Pieces"
                }
            };

            foreach (Unit u in units)
            {
                context.Units.Add(u);
            }
            context.SaveChanges();

            var machines = new Machine[] {
                new Machine {
                    Capacity = 1, Name = "Säge", Count = 1, MachineGroup = new MachineGroup {
                        Name = "Zuschnitt"
                    }
                },
                new Machine {
                    Capacity = 1, Name = "Bohrer", Count = 1, MachineGroup = new MachineGroup {
                        Name = "Bohrwerk"
                    }
                },
                new Machine {
                    Capacity = 1, Name = "MontagePlatform", Count = 1, MachineGroup = new MachineGroup {
                        Name = "Montage"
                    }
                },
                new Machine {
                    Capacity = 1, Name = "MontagePlatform2", Count = 1,
                }
            };

            machines.Last().MachineGroup = machines.Single(n => n.Name == "MontagePlatform").MachineGroup;
            foreach (var m in machines)
            {
                context.Machines.Add(m);
            }
            context.SaveChanges();

            var machineTools = new MachineTool[]
            {
                new MachineTool {
                    MachineId = machines.Single(m => m.Name == "Säge").Id, SetupTime = 1, Name = "Sägeblatt 1mm Zahnabstant"
                },
                new MachineTool {
                    MachineId = machines.Single(m => m.Name == "Bohrer").Id, SetupTime = 1, Name = "M6 Bohrkopf"
                },
            };

            foreach (var mt in machineTools)
            {
                context.MachineTools.Add(mt);
            }
            context.SaveChanges();

            // Articles
            var articles = new Article[]
            {
                new Article {
                    Name = "Kipper", ArticleTypeId = articleTypes.Single(s => s.Name == "Assembly").Id, CreationDate = DateTime.Parse("2016-09-01"), DeliveryPeriod = 20, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 45.00
                },
                new Article {
                    Name = "Rahmengestell", ArticleTypeId = articleTypes.Single(s => s.Name == "Assembly").Id, DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 15.00
                },
                new Article {
                    Name = "Ladebehälter", ArticleTypeId = articleTypes.Single(s => s.Name == "Assembly").Id, CreationDate = DateTime.Parse("2016-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 15.00
                },
                new Article {
                    Name = "Chassis", ArticleTypeId = articleTypes.Single(s => s.Name == "Assembly").Id, CreationDate = DateTime.Parse("2016-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 15.00
                },

                new Article {
                    Name = "Rad", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 1.00
                },
                new Article {
                    Name = "Felge", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 2, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 1.00
                },
                new Article {
                    Name = "Bodenplatte", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 4.00
                },
                new Article {
                    Name = "Aufliegeplatte", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 3.00
                },

                new Article {
                    Name = "Seitenwand land", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 1.50
                },
                new Article {
                    Name = "Seitenwand kurz", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 2.00
                },
                new Article {
                    Name = "Bodenplatte Behälter", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 4.00
                },
                new Article {
                    Name = "Fahrerhaus", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 5.00
                },
                new Article {
                    Name = "Motorblock", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 3.00
                },
                new Article {
                    Name = "Achse", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 0.50
                },
                new Article {
                    Name = "Knopf", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 0.05
                },
                new Article {
                    Name = "Kippgelenk", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 1
                },
                new Article {
                    Name = "Holz 1,5m x 3,0m", ArticleTypeId = articleTypes.Single(s => s.Name == "Material").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 5, UnitId = units.Single(s => s.Name == "Pieces").Id, Price = 5
                },

                new Article {
                    Name = "Unterlegscheibe", ArticleTypeId = articleTypes.Single(s => s.Name == "Consumable").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 0.05
                },
                new Article {
                    Name = "Leim", ArticleTypeId = articleTypes.Single(s => s.Name == "Consumable").Id, CreationDate = DateTime.Parse("2002-09-01"), DeliveryPeriod = 10, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 5.00
                },
                new Article {
                    Name = "Dübel", ArticleTypeId = articleTypes.Single(s => s.Name == "Consumable").Id, CreationDate = DateTime.Parse("2005-09-01"), DeliveryPeriod = 3, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 3.00
                },
                new Article {
                    Name = "Verpackung", ArticleTypeId = articleTypes.Single(s => s.Name == "Consumable").Id, CreationDate = DateTime.Parse("2005-09-01"), DeliveryPeriod = 4, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 7.00
                },
                new Article {
                    Name = "Bedienungsanleitung", ArticleTypeId = articleTypes.Single(s => s.Name == "Consumable").Id, CreationDate = DateTime.Parse("2005-09-01"), DeliveryPeriod = 4, UnitId = units.Single(s => s.Name == "Kilo").Id, Price = 0.50
                },
            };

            foreach (Article a in articles)
            {
                context.Articles.Add(a);
            }
            context.SaveChanges();

            // get the name -> id mappings
            var DBArticles = context
                             .Articles
                             .ToDictionary(p => p.Name, p => p.Id);


            // create Stock Entrys for each Article
            foreach (var article in DBArticles)
            {
                var Stocks = new Stock[]
                {
                    new Stock
                    {
                        ArticleForeignKey = article.Value,
                        Name    = "Stock: " + article.Key,
                        Min     = (article.Key == "Kipper") ? 1 : 0,
                        Max     = 50,
                        Current = (article.Key == "Kipper") ? 1 : 0
                    }
                };
                foreach (Stock s in Stocks)
                {
                    context.Stocks.Add(s);
                }
                context.SaveChanges();
            }
            var workSchedule = new WorkSchedule[]
            {
                new WorkSchedule {
                    ArticleId = articles.Single(a => a.Name == "Kipper").Id, Name = "Kipper Hochzeit", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "MontagePlatform").MachineGroupId, HierarchyNumber = 10
                },
                new WorkSchedule {
                    ArticleId = articles.Single(a => a.Name == "Kipper").Id, Name = "Kipper Ladefläche Kleben", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "MontagePlatform").MachineGroupId, HierarchyNumber = 20
                },
                new WorkSchedule {
                    ArticleId         = articles.Single(a => a.Name == "Rahmengestell").Id, Name = "Rahmen zuschneiden", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "Säge").MachineGroupId
                    , HierarchyNumber = 10
                },
                new WorkSchedule {
                    ArticleId         = articles.Single(a => a.Name == "Rahmengestell").Id, Name = "Löcher für Achse in den Rahmen bohren", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "Bohrer").MachineGroupId
                    , HierarchyNumber = 20
                },

                new WorkSchedule {
                    ArticleId         = articles.Single(a => a.Name == "Bodenplatte").Id, Name = "Bodenplatte zuschneiden", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "Säge").MachineGroupId
                    , HierarchyNumber = 10
                },
                new WorkSchedule {
                    ArticleId = articles.Single(a => a.Name == "Rahmengestell").Id, Name = "Achse mit Rahmen Verschrauben", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "MontagePlatform").MachineGroupId, HierarchyNumber = 30
                },
                new WorkSchedule {
                    ArticleId = articles.Single(a => a.Name == "Rad").Id, Name = "Felge auf Rad Aufziehen", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "MontagePlatform").MachineGroupId, HierarchyNumber = 10
                },
                new WorkSchedule {
                    ArticleId = articles.Single(a => a.Name == "Rad").Id, Name = "Rad mit Achse verschrauben", Duration = 2, MachineGroupId = machines.Single(n => n.Name == "MontagePlatform").MachineGroupId, HierarchyNumber = 20
                },
            };

            foreach (var ws in workSchedule)
            {
                context.WorkSchedules.Add(ws);
            }
            context.SaveChanges();



            var articleBom = new List <ArticleBom>
            {
                new ArticleBom {
                    ArticleChildId = articles.Single(a => a.Name == "Kipper").Id, Name = "Kipper"
                },

                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Rahmengestell").Id, Name = "Rahmengestell", Quantity = 1,
                    ArticleParentId = articles.Single(a => a.Name == "Kipper").Id
                },
                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Chassis").Id, Name = "Chassis", Quantity = 1,
                    ArticleParentId = articles.Single(a => a.Name == "Kipper").Id
                },
                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Ladebehälter").Id, Name = "Ladebehälter", Quantity = 1,
                    ArticleParentId = articles.Single(a => a.Name == "Kipper").Id
                },

                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Bodenplatte").Id, Name = "Bodenplatte", Quantity = 1,
                    ArticleParentId = articles.Single(a => a.Name == "Rahmengestell").Id
                },
                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Achse").Id, Name = "Achse", Quantity = 2,
                    ArticleParentId = articles.Single(a => a.Name == "Rahmengestell").Id
                },
                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Rad").Id, Name = "Rad", Quantity = 4,
                    ArticleParentId = articles.Single(a => a.Name == "Rahmengestell").Id
                },

                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Felge").Id, Name = "Felge", Quantity = 1,
                    ArticleParentId = articles.Single(a => a.Name == "Rad").Id
                },
                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Dübel").Id, Name = "Dübel", Quantity = 2,
                    ArticleParentId = articles.Single(a => a.Name == "Rad").Id
                },

                new ArticleBom {
                    ArticleChildId  = articles.Single(a => a.Name == "Holz 1,5m x 3,0m").Id, Name = "Holz 1,5m x 3,0m", Quantity = 4,
                    ArticleParentId = articles.Single(a => a.Name == "Bodenplatte").Id
                },
            };


            foreach (var item in articleBom)
            {
                context.ArticleBoms.Add(item);
            }
            context.SaveChanges();


            //create Businesspartner
            var businessPartner = new BusinessPartner()
            {
                Debitor = true, Kreditor = false, Name = "Toys'R'us Spielwarenabteilung"
            };
            var businessPartner2 = new BusinessPartner()
            {
                Debitor = false, Kreditor = true, Name = "Material Großhandel"
            };

            context.BusinessPartners.Add(businessPartner);
            context.BusinessPartners.Add(businessPartner2);
            context.SaveChanges();

            var artToBusinessPartner = new ArticleToBusinessPartner[]
            {
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Dübel").Id, PackSize = 100, Price = 0.10, DueTime = 2
                },
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Chassis").Id, PackSize = 1, Price = 2, DueTime = 2
                },
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Ladebehälter").Id, PackSize = 1, Price = 3, DueTime = 2
                },
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Achse").Id, PackSize = 10, Price = 0.50, DueTime = 2
                },
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Holz 1,5m x 3,0m").Id, PackSize = 1, Price = 1, DueTime = 2
                },
                new ArticleToBusinessPartner {
                    BusinessPartnerId = businessPartner2.Id, ArticleId = articles.Single(x => x.Name == "Felge").Id, PackSize = 10, Price = 0.20, DueTime = 2
                },
            };

            foreach (var art in artToBusinessPartner)
            {
                context.ArticleToBusinessPartners.Add(art);
            }
            context.SaveChanges();

            //create order
            var orders = new List <Order>()
            {
                new Order {
                    BusinessPartnerId = businessPartner.Id, DueTime = 40, Name = "Erste Kipperbestellung"
                },
                new Order {
                    BusinessPartnerId = businessPartner.Id, DueTime = 70, Name = "Zweite Kipperbestellung"
                },
                new Order {
                    BusinessPartnerId = businessPartner.Id, DueTime = 100, Name = "Dritte Kipperbestellung"
                }
            };

            foreach (var order in orders)
            {
                context.Orders.Add(order);
            }
            context.SaveChanges();

            //create orderParts
            var orderParts = new List <OrderPart>()
            {
                new OrderPart()
                {
                    Quantity = 7, ArticleId = articles.Single(a => a.Name == "Kipper").Id, OrderId = 1, IsPlanned = false
                },
                new OrderPart()
                {
                    Quantity = 4, ArticleId = articles.Single(a => a.Name == "Kipper").Id, OrderId = 2, IsPlanned = false
                },
                new OrderPart()
                {
                    Quantity = 1, ArticleId = articles.Single(a => a.Name == "Kipper").Id, OrderId = 3, IsPlanned = false
                },
            };

            foreach (var orderPart in orderParts)
            {
                context.OrderParts.Add(orderPart);
            }
            context.SaveChanges();
        }
Beispiel #53
0
 public Stock Update(Stock stock)
 {
     _databaseContext.Stocks.Update(stock);
     _databaseContext.SaveChanges();
     return(stock);
 }
Beispiel #54
0
        static void Main(string[] args)
        {
            Console.Title = "Cecilia Silva. TP4 2D, probando probando";

            Console.WriteLine("-----------------------------------------------------------------------");
            Console.WriteLine("------------------------MARITIME SOLUTIONS LTD-------------------------");
            Console.WriteLine("-----------------------------------------------------------------------");



            #region instancias para funcionamiento
            SerializadoraXml <List <Publicacion> > serializacionPubs    = new SerializadoraXml <List <Publicacion> >();
            SerializadoraXml <List <Carta> >       serializacionCarta   = new SerializadoraXml <List <Carta> >();
            SerializadoraXml <List <Clientes> >    serializacionCliente = new SerializadoraXml <List <Clientes> >();

            List <Carta>       cartasConsola        = new List <Carta>();
            List <Clientes>    clientesConsola      = new List <Clientes>();
            List <Publicacion> publicacionesConsola = new List <Publicacion>();
            List <Barco>       barcosConsola        = new List <Barco>();

            Stock stocksito = new Stock();

            string rutaPub      = AppDomain.CurrentDomain.BaseDirectory + "listaPublicacionesStock";
            string rutaCartas   = AppDomain.CurrentDomain.BaseDirectory + "listaCartasStock";
            string rutaClientes = AppDomain.CurrentDomain.BaseDirectory + "listaClientes";

            Publicacion publicacion = new Publicacion(2, Publicacion.Formato.Hardbook, "Tanker Structures", 2021, "IMO", "AN2021", 1);


            /// Esta publicación ya está en la lista, no debería poder agregarse de nuevo
            Publicacion publicacionDuplicada = new Publicacion(2, Publicacion.Formato.Hardbook, "IMDG Code Supplement", 2008, "IMO", "KK210F", 1);


            #endregion

            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");

            Console.WriteLine("-----------------------------------------------------------------------");
            Console.WriteLine("------------------------AGREGAR PUBLICACIONES-------------------------");
            Console.WriteLine("-----------------------------------------------------------------------");


            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");


            if (stocksito + publicacion)
            {
                Console.WriteLine("Se agregó la publicación {0} con éxito", publicacion.Titulo);
                publicacionesConsola.Add(publicacion);
            }


            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");


            if (stocksito + publicacionDuplicada)
            {
                Console.WriteLine("Se agregó la publicación con éxito");
            }
            else
            {
                Console.WriteLine("No se pudo agregar la publicación {0}.", publicacionDuplicada.Titulo);
            }
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");

            Console.Write("-----------------PRESIONE UNA TECLA PARA CONTINUAR--------------------------");
            Console.ReadKey();
            Console.Clear();

            Console.WriteLine("-----------------------------------------------------------------------");
            Console.WriteLine("------------------------MARITIME SOLUTIONS LTD-------------------------");
            Console.WriteLine("-----------------------------------------------------------------------");

            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");

            Console.WriteLine("-----------------------------------------------------------------------");
            Console.WriteLine("-------------¿QUE BARCOS TIENEN LA PUBLICACIÓN DUPLICADA?--------------");
            Console.WriteLine("-----------------------------------------------------------------------");


            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");


            Console.WriteLine("La publicación duplicada es: {0} . \nNo se pudo agregar porque ya estaba en la lista. Su código es {1}.", publicacionDuplicada.Titulo, publicacionDuplicada.Codigo);

            Console.WriteLine("                                                   ");
            Console.WriteLine("                                                   ");

            Stock.RevisarIgualdadBarcoSeleccionado(publicacionDuplicada, barcosConsola);

            if (barcosConsola.Count > 0)
            {
                foreach (Barco barquito in barcosConsola)
                {
                    Console.WriteLine(barquito.NombreBarco);
                }
            }
            else
            {
                Console.WriteLine("Oops, ningún barco tiene esta publicación");
            }



            Console.ReadKey();
        }
Beispiel #55
0
 public Stock AddStock(Stock stock)
 {
     _databaseContext.Stocks.Add(stock);
     _databaseContext.SaveChanges();
     return(stock);
 }
Beispiel #56
0
        public static void UpdateStockReduce(String Pid, int qnt)
        {
            Stock s = us.Stocks.First <Stock>(x => x.ItemNumber == Pid);

            s.TotalInventoryBalance -= qnt;
        }
        public ActionResult OrderConfirm(Order obj, string CouponKey)
        {
            List <Cart> cartList = repoRakibCart.GetCartByUserId(obj.User_Id).ToList();

            if (cartList.Count == 0)
            {
                return(RedirectToAction("Index", "Home"));
            }
            float p = 0;

            if (CouponKey != "")
            {
                Coupon c = repoRakibCoupon.GetPercentage(CouponKey);
                obj.Coupon_Id = c.Id;
                p             = (float)c.Percentage;
            }

            repoRakibOrder.Insert(obj);
            repoRakibOrder.EContext.SaveChanges();

            var lastOrder = repoRakibOrder.GetLastEntryOfUser(obj.User_Id);

            //var cartList = repoRakibCart.GetCartByUserId(obj.User_Id);
            foreach (var item in cartList)
            {
                OrderData orderData = new OrderData();
                orderData.Book_Id         = item.Book_Id;
                orderData.Order_Id        = lastOrder.Id;
                orderData.QuantityOrdered = item.QuantityOrdered;
                orderData.Subtotal        = item.QuantityOrdered * item.Book.Price;

                if (CouponKey != "")
                {
                    orderData.ActualPrice = Math.Ceiling(orderData.Subtotal - ((orderData.Subtotal * p) / 100));
                }
                else
                {
                    orderData.ActualPrice = Math.Ceiling(orderData.Subtotal);
                }
                repoRakibOrderData.Insert(orderData);
                repoRakibOrderData.EContext.SaveChanges();

                Stock s = repoRakibStock.GetStockByBookId(item.Book_Id);
                s.OrderStock -= item.QuantityOrdered;
                repoRakibStock.EContext.Entry(s).State = EntityState.Modified;
                repoRakibStock.EContext.SaveChanges();
            }

            repoRakibCart.RemoveRange(cartList);
            repoRakibCart.EContext.SaveChanges();
            OrderLog o = new OrderLog();

            o.AddedDate  = DateTime.Now;
            o.LogDetails = "Pending for comfirmation";
            o.Order_Id   = lastOrder.Id;

            repoRakibOrderLog.Insert(o);
            repoRakibOrderLog.EContext.SaveChanges();

            return(RedirectToAction("OrderS"));
        }
        public void UpdateStockPrice(Stock stock, double newPrice)
        {
            Stock selected = GetStockByName(stock.Name);

            selected.Price = newPrice;
        }
Beispiel #59
0
    static public void Main(string[] args)
    {
        Stock stock;
        int   i;

        Storage db = StorageFactory.Instance.CreateStorage();

        db.Open("testts.dbs", pagePoolSize);
#if USE_GENERICS
        FieldIndex <string, Stock> stocks = (FieldIndex <string, Stock>)db.Root;
        if (stocks == null)
        {
            stocks       = db.CreateFieldIndex <string, Stock>("name", true);
            stock        = new Stock();
            stock.name   = "BORL";
            stock.quotes = db.CreateTimeSeries <Quote>(N_ELEMS_PER_BLOCK, N_ELEMS_PER_BLOCK * TICKS_PER_SECOND * 2);
            stocks.Put(stock);
            db.Root = stocks;
        }
        else
        {
            stock = stocks["BORL"];
        }
#else
        FieldIndex stocks = (FieldIndex)db.Root;
        if (stocks == null)
        {
            stocks       = db.CreateFieldIndex(typeof(Stock), "name", true);
            stock        = new Stock();
            stock.name   = "BORL";
            stock.quotes = db.CreateTimeSeries(typeof(QuoteBlock), QuoteBlock.N_ELEMS_PER_BLOCK * TICKS_PER_SECOND * 2);
            stocks.Put(stock);
            db.Root = stocks;
        }
        else
        {
            stock = (Stock)stocks["BORL"];
        }
#endif
        Random   rand  = new Random(2004);
        DateTime start = DateTime.Now;
        int      time  = getSeconds(start) - nElements;
        for (i = 0; i < nElements; i++)
        {
            Quote quote = new Quote();
            quote.timestamp = time + i;
            quote.open      = (float)rand.Next(10000) / 100;
            quote.close     = (float)rand.Next(10000) / 100;
            quote.high      = Math.Max(quote.open, quote.close);
            quote.low       = Math.Min(quote.open, quote.close);
            quote.volume    = rand.Next(1000);
            stock.quotes.Add(quote);
        }
        db.Commit();
        Console.WriteLine("Elapsed time for storing " + nElements + " quotes: "
                          + (DateTime.Now - start));

        rand  = new Random(2004);
        start = DateTime.Now;
        i     = 0;
        foreach (Quote quote in stock.quotes)
        {
            Debug.Assert(quote.timestamp == time + i);
            float open = (float)rand.Next(10000) / 100;
            Debug.Assert(quote.open == open);
            float close = (float)rand.Next(10000) / 100;
            Debug.Assert(quote.close == close);
            Debug.Assert(quote.high == Math.Max(quote.open, quote.close));
            Debug.Assert(quote.low == Math.Min(quote.open, quote.close));
            Debug.Assert(quote.volume == rand.Next(1000));
            i += 1;
        }
        Debug.Assert(i == nElements);
        Console.WriteLine("Elapsed time for extracting " + nElements + " quotes: "
                          + (DateTime.Now - start));

        Debug.Assert(stock.quotes.Count == nElements);


        long from  = getTicks(time + 1000);
        int  count = 1000;
        start = DateTime.Now;
        i     = 0;
        foreach (Quote quote in stock.quotes.Range(new DateTime(from), new DateTime(from + count * TICKS_PER_SECOND), IterationOrder.DescentOrder))
        {
            Debug.Assert(quote.timestamp == time + 1000 + count - i);
            i += 1;
        }
        Debug.Assert(i == count + 1);
        Console.WriteLine("Elapsed time for extracting " + i + " quotes: " + (DateTime.Now - start));

        start = DateTime.Now;
        long n = stock.quotes.Remove(stock.quotes.FirstTime, stock.quotes.LastTime);
        Debug.Assert(n == nElements);
        Console.WriteLine("Elapsed time for removing " + nElements + " quotes: "
                          + (DateTime.Now - start));

        Debug.Assert(stock.quotes.Count == 0);

        db.Close();
    }
Beispiel #60
0
 public virtual bool Attach(Stock input)
 {
     return(false);
 }