Example #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            //main = Common.GetIntPtrByProcess("taskmgr");
            List <WindowInfo> windowInfos = new List <WindowInfo>();

            Common.GetWindows(Config.MainWindow, ref windowInfos);
            var ctrl = windowInfos.Where(p => (p.DlgCtrlID == ".00000000.0000E900.0000E901.00000000.00008016".ToUpper() && p.isVisible == 1)).ToArray();

            //if (ctrl.Length > 0)
            //    MessageBox.Show(ctrl.Length.ToString());
            StockService.SellStock("300446", (decimal)17.12, 100);
            StockService.BuyStock("300446", (decimal)17.12, 100);
            MessageBox.Show(Common.GetTitle(Common.GetWindowByCtrlID(StockService.windows, Config.BuyCtrlPrice)));
            //MessageBox.Show(StockService.GetMyAsset().availableMoney.ToString());
            //MessageBox.Show(StockService.GetMyAsset().moratoriumMoney.ToString());
            //MessageBox.Show(StockService.GetMyAsset().stockMoney.ToString());
            //MessageBox.Show(StockService.GetMyAsset().allAsset.ToString());
            //main = Common.GetIntPtrByProcess("xiadan");
            //IntPtr treePtr = Common.GetIntPtrByControlID(main, "00000000.0000E900.0000E900.00000081.000000C8.00000081");

            //SysTreeView32 tree = new SysTreeView32(treePtr);
            //SysTreeView32_Item i = tree.FirstItem;
            //while(i!=null)
            //{
            //    richTextBox1.AppendText(i.text + "\n");
            //    i = i.NextItem;
            //}
        }
Example #2
0
        static void Main(string[] args)
        {
            FileDatabaseService fileDatabaseService = new FileDatabaseService();
            StockService        stockService        = new StockService();
            MenuService         menuService         = new MenuService();
            OrdersService       ordersService       = new OrdersService();
            ConsoleUIService    consoleUIService    = new ConsoleUIService(fileDatabaseService, stockService, menuService, ordersService);

            string[] stockData = fileDatabaseService.ReadStock();
            if (stockData != null)
            {
                stockService.StockList = stockService.ParseStock(stockData);
            }

            string[] menuData = fileDatabaseService.ReadMenu();
            if (menuData != null)
            {
                menuService.MenuList = menuService.ParseMenu(menuData);
            }

            string[] ordersData = fileDatabaseService.ReadOrders();
            if (ordersData != null)
            {
                ordersService.OrdersList = ordersService.ParseOrders(ordersData);
            }

            while (true)
            {
                consoleUIService.PrintMessage(Constants.mainMenuMessage);
                int input = consoleUIService.GetInput();
                consoleUIService.ProcessInput(input);
            }
        }
Example #3
0
        public void Initialize()
        {
            //Initialize services as "composition" root
            AutoMapper.Mapper.CreateMap <StockDTO, Stock>();
            AutoMapper.Mapper.CreateMap <Stock, StockDTO>();

            _stockRepository = A.Fake <IStockRepository>();

            A.CallTo(() => _stockRepository.GetById(ValidStockId))
            .Returns(new DTO.StockDTO
            {
                Id = ValidStockId
            });
            A.CallTo(() => _stockRepository.GetById(InvalidStockId)).Throws <StockNotFoundException>();
            A.CallTo(() => _stockRepository.DeleteById(InvalidStockId)).Throws <StockNotFoundException>();
            A.CallTo(() => _stockRepository.GetAllStock()).Returns(new List <Stock>()
            {
                new Stock()
                {
                    Id = "1", CurrentPrice = 64.95m, IssuingCompany = "NASDAQ", LastRecordedPrice = 64.98m, StockCode = "MSFT", StockName = "Microsoft Corporation"
                },
                new Stock()
                {
                    Id = "2", CurrentPrice = 963.90m, IssuingCompany = "NSE", LastRecordedPrice = 963.90m, StockCode = "INFY", StockName = "Infosys Ltd"
                }
            });

            _stockService = new StockService(_stockRepository);
        }
Example #4
0
        private async Task LoadStocks()
        {
            var tickers = Ticker.Text.Split(',', ' ');

            var service = new StockService();

            var tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >();

            foreach (var ticker in tickers)
            {
                var loadTask = service.GetStockPricesFor(ticker, cancellationTokenSource.Token);

                tickerLoadingTasks.Add(loadTask);
            }
            var timeoutTask = Task.Delay(2000);

            var allStocksLoadingTask = Task.WhenAll(tickerLoadingTasks);

            var completedTask = await Task.WhenAny(timeoutTask, allStocksLoadingTask);

            if (completedTask == timeoutTask)
            {
                cancellationTokenSource.Cancel();
                cancellationTokenSource = null;
                throw new Exception("Timeout!");
            }

            Stocks.ItemsSource = allStocksLoadingTask.Result.SelectMany(stocks => stocks);
        }
Example #5
0
        private void FetchStockData(object sender, DoWorkEventArgs args)
        {
            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = $"Thread_{StockService.GetStockInfo.Tag}";
            }

            IsFetchStarted             = true;
            StockService.StockUpdated += UpdateStockData;

            Log.Info($"{ToString()} stock data fetching has been started.");

            try
            {
                while (IsFetchStarted)
                {
                    if (Worker.CancellationPending)
                    {
                        IsFetchStarted = false;
                        args.Cancel    = true;
                        break;
                    }

                    StockService.GetStockData();
                    Thread.Sleep(RefreshRate);
                }
            }
            finally
            {
                StockService.StockUpdated -= UpdateStockData;
                IsFetchStarted             = false;
            }
        }
Example #6
0
        const int TIMERDURATION = 5000; // Set timer to 5 seconds (5000 milliseconds)
        static void Main(string[] args)
        {
            try
            {
                // Get the input stock symbol
                string inputSymbol =
                    getString("Enter a stock symbol, for example AAPL or GOOG or MSFT: ");

                // Get the current stock quote (using input symbol in upper case)
                // If found, display the current stock quote with indication to wait
                if (StockService.GetCurrentStockInfo(inputSymbol.ToUpper()))
                {
                    StockService.DisplayCurrentStockQuote("Wait for more information");

                    //  Set a timer to display more stock quotes
                    TimerService.setTimer(TIMERDURATION);

                    Console.ReadLine();
                    TimerService.stopTimer();
                    Console.WriteLine("Press <enter> to exit...");
                }
                else
                {
                    Console.WriteLine("No stock information was found for {0}",
                                      inputSymbol);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
                Console.ReadLine();
            }

            Console.ReadLine();
        }
Example #7
0
 public ProfileController(UserManager <IdentityUser> um)
 {
     _cs          = new CustomerService();
     _ss          = new StockService();
     _os          = new OrderService();
     _userManager = um;
 }
        public ActionResult UpdateStockQuantity(Stock model)
        {
            StockService stockService = new StockService();

            stockService.UpdateStock(model);
            return(Redirect(Request.UrlReferrer.ToString()));
        }
        public void Initialize()
        {
            _stockRepository = A.Fake <IStockRepository>();
            _stockService    = new StockService(_stockRepository);

            _ValidSymbols = new List <string>()
            {
                "AAPL", "GOOG"
            };

            A.CallTo(() => _stockRepository.GetBySymbol(ValidSymbol)).Returns(new Stock()
            {
                Symbol = ValidSymbol
            });

            A.CallTo(() => _stockRepository.GetBySymbol(InvalidSymbol)).Throws <StockNotFoundException>();

            A.CallTo(() => _stockRepository.GetStocks(_ValidSymbols)).Returns(new List <Stock>()
            {
                new Stock()
                {
                    Symbol = ValidSymbol
                }
            });
        }
Example #10
0
        public async Task <ActionResult <string> > PostBulkMutation([FromBody] string value)
        {
            UserData user = await GetUserData(Request.Headers["token"]);

            if (user == null)
            {
                return(Unauthorized("No valid session found for this token"));
            }
            if (user.storeId == null)
            {
                return(Unauthorized("No store found for this user"));
            }
            StockMutation[] mutations;
            try
            {
                mutations = Json.Deserialize <StockMutation[]>(value);
            }
            catch (Exception e)
            {
                return(BadRequest("Could not process inputted mutations"));
            }
            await StockService.AddMutationBulk((int)user.storeId, mutations);

            return(Ok("Mutations have been posted"));
        }
Example #11
0
        public async Task <ActionResult <string> > PostMutation([FromBody] string value)
        {
            UserData user = await GetUserData(Request.Headers["token"]);

            if (user == null)
            {
                return(Unauthorized("No valid session found for this token"));
            }
            if (user.storeId == null)
            {
                return(Unauthorized("No store found for this user"));
            }
            StockMutation mutation;

            try
            {
                mutation = Json.Deserialize <StockMutation>(value);
            } catch (Exception e)
            {
                return(BadRequest("Could not process inputted mutation\n" + e.Message + "\n " + e.StackTrace.ToString()));
            }
            await StockService.AddMutation((int)user.storeId, mutation);

            return(Ok("Mutation has been posted"));
        }
Example #12
0
        public Product stockDetails(InputData data)
        {
            var ss      = new StockService();
            var product = ss.GetProduct(data.Id);

            return(product);
        }
Example #13
0
        public ActionResult CatAddPost(string name, int pid)
        {
            if (!string.IsNullOrEmpty(name))
            {
                St_cat aCat = new St_cat();
                aCat.Name  = name;
                aCat.PId   = pid;
                aCat.Level = 0;
                int    lid     = DBService.AddEntity <St_cat>(aCat, true);
                string catpath = "";
                if (pid > 0)
                {
                    var pcat = DBService.GetEntity <St_cat>(pid);
                    if (pcat != null && pcat.Id > 0)
                    {
                        catpath = string.IsNullOrEmpty(pcat.Path) ? "," : pcat.Path + lid.ToString() + ",";
                    }
                }
                else
                {
                    catpath = "," + lid.ToString() + ",";
                }

                //aCat.Path = catpath;
                StockService.UpdateCatPath(lid, catpath);
            }
            return(RedirectToAction("Cat"));
        }
Example #14
0
        public ActionResult Stocks(int?p)
        {
            var vm = new MemberStockViewModel();

            vm.PageSize     = 40;
            vm.CurPageIndex = p.HasValue && p.Value > 1 ? p.Value : 1;
            var memberid = 0;
            var uid      = GetCurUserId();

            if (uid > 0)
            {
                var member = MemberService.GetMemberFromUser(uid);
                if (member != null && member.Id > 0)
                {
                    memberid = member.Id;
                }
            }
            vm.RecordCount = StockService.GetMemberTotalStockCount(memberid, "");
            vm.PageTotal   = (int)Math.Ceiling((double)vm.RecordCount / 40);
            if (vm.CurPageIndex > vm.PageTotal)
            {
                vm.CurPageIndex = vm.PageTotal;
            }
            if (vm.RecordCount > 0)
            {
                vm.CurPageStocks = StockService.GetMemberPagedStocks(memberid, (vm.CurPageIndex - 1) * vm.PageSize, vm.PageSize, "");
            }
            return(View(vm));
        }
Example #15
0
        public void SoldOutTest()
        {
            Transaction    transaction = new Transaction();
            StockService   stock       = new StockService();
            List <Product> products    = stock.Products;
            var            chiclet     = products.Find(p => p.Slot == "D3");

            //Insert $10 & buy a $0.75 Chiclet 6x
            //Should return SOLD OUT after the fifth purchase
            //Checking "SoldOut" Prop

            transaction.AcceptCash("10");
            //1
            transaction.SelectItem("D3", products);
            Assert.AreEqual(false, chiclet.SoldOut);
            //2
            transaction.SelectItem("D3", products);
            Assert.AreEqual(false, chiclet.SoldOut);
            //3
            transaction.SelectItem("D3", products);
            Assert.AreEqual(false, chiclet.SoldOut);
            //4
            transaction.SelectItem("D3", products);
            Assert.AreEqual(false, chiclet.SoldOut);
            //5.... SOLD OUT
            transaction.SelectItem("D3", products);
            Assert.AreEqual(true, chiclet.SoldOut);
        }
        public void Setup()
        {
            _stockMockRepo = new Mock <IStockRepository>();
            _stockService  = new StockService(_stockMockRepo.Object);

            products = new List <ProductsDataModel>();
            items    = new List <string>();
            products.Clear();
            products.Add(new ProductsDataModel()
            {
                Name  = "Biscuits",
                Price = 100,
            });
            products.Add(new ProductsDataModel()
            {
                Name  = "Milk",
                Price = 300,
            });
            items.Clear();
            items.Add("Bread");
            items.Add("Milk");
            items.Add("cheese");
            items.Add("Butter");
            items.Add("Biscuits");
        }
        public async Task <ActionResult> EnterQuantities(Inventory inventory, string sessionId)
        {
            //Contact Python API to get predicted re-order amount and level for item with code 'P021' and 'P030'
            List <Inventory> stock = await StockService.GetAllItemsOrdered();

            List <Inventory> selectedItems = new List <Inventory>();

            try
            {
                for (int i = 0; i < stock.Count; i++)
                {
                    if (inventory.CheckedItems[i] == true)
                    {
                        selectedItems.Add(stock[i]);
                    }
                }
            }
            catch (NullReferenceException)
            {
                return(RedirectToAction("All", new { sessionid = sessionId }));
            }

            ViewData["selectedItems"] = selectedItems;
            ViewData["sessionId"]     = sessionId;
            return(View());
        }
Example #18
0
 public FormAddStock()
 {
     InitializeComponent();
     _stockService    = new StockService();
     _employeeService = new EmployeeService();
     _logService      = new LogService();
 }
        //Get api/stock
        public IHttpActionResult GetAll()
        {
            StockService stockService = CreateStockService();
            var          stocks       = stockService.GetStocks();

            return(Ok(stocks));
        }
Example #20
0
        public async Task ThreadSave()
        {
            var service = new StockService();
            var stocks  = new ConcurrentBag <StockPrice>();

            string[] tickers            = new string[] { "MSFT" };
            var      tickerLoadingTasks = new List <Task <IEnumerable <StockPrice> > >();

            foreach (var ticker in tickers)
            {
                var loadTask = service.GetStockPricesFor(ticker, new CancellationTokenSource().Token)
                               .ContinueWith(t => {
                    foreach (var stock in t.Result.Take(5))
                    {
                        stocks.Add(stock);
                    }
                    return(t.Result);
                });

                tickerLoadingTasks.Add(loadTask);
            }

            var allStocksLoadingTask = Task.WhenAll(tickerLoadingTasks);

            await allStocksLoadingTask;
        }
Example #21
0
        public ActionResult Edit(StockInfo stockInfo)
        {
            stockInfo.MerchantSysNo = UserAuthHelper.GetCurrentUser().SellerSysNo;
            var success = StockService.Edit(stockInfo);

            return(Json(new { Success = success, Msg = success ? LanguageHelper.GetText("操作成功") : LanguageHelper.GetText("操作失败,请稍候再试") }));
        }
Example #22
0
 internal void SaveNewStock(AdminStocksModel adminStockModel)
 {
     StockService.CreateStock(new StockModel()
     {
         active = adminStockModel.active, description = "<p class=\"align-left\" style=\"text-align:justify\">" + adminStockModel.description + "</p>", market_id = adminStockModel.market_id, name = adminStockModel.name, symbol = adminStockModel.symbol, type_id = adminStockModel.type_id
     });
 }
Example #23
0
 internal void UpdateStock(AdminStocksModel adminStockModel)
 {
     StockService.UpdateStock(new StockModel()
     {
         Id = adminStockModel.Id, active = adminStockModel.active, description = adminStockModel.description, market_id = adminStockModel.market_id, name = adminStockModel.name, symbol = adminStockModel.symbol, type_id = adminStockModel.type_id
     });
 }
Example #24
0
        public JsonResult List(int?memberid, string q, PagingRequest pg)
        {
            var    res = new PagingReply();
            string qr  = q;

            if (!string.IsNullOrEmpty(pg.sSearch))
            {
                qr = pg.sSearch;
            }
            res.iTotalRecords = StockService.GetStockCount(memberid, qr);
            if (res.iTotalRecords > 0)
            {
                var cats = StockService.GetStockCats();

                var results        = StockService.GetStocks(memberid, pg.iDisplayStart, pg.iDisplayLength, qr);
                var stockmemberids = results.Where(s => s.MemberId > 0).Select(s => s.MemberId.HasValue ? s.MemberId.Value : 0).ToList();
                var members        = MemberService.GetMembersByIds(stockmemberids);
                res.aaData = results.Select(ct => new object[] { ct.Name,
                                                                 ct.CatId.HasValue && ct.CatId > 0 ? GetCatName(ct.CatId.Value, cats) : "无",
                                                                 !string.IsNullOrEmpty(ct.MainPic) && ct.MainPic.StartsWith("~") ? VirtualPathUtility.ToAbsolute(ct.MainPic) : ct.MainPic,
                                                                 "区域:" + ct.GoodsArea + " 类型:" + (ct.GoodsType == 1?"<b>求购</b>":"<b>出售</b>") + "<br>" + (ct.IsBrandGoods == true?"品牌:" + ct.BrandName + "<br>":"") + "价格:" + (ct.Price.HasValue ? ct.Price.Value.ToString() + " " : " ") + ct.PriceDetail + " 数量:" + (ct.Qty.HasValue ? ct.Qty.Value.ToString() + " " : " ") + ct.QtyDetail,
                                                                 ct.Status == 1 ? "已验证" : "未验证", ct.AddTime.ToString() + "<br>会员名:" + GetMemberName(ct.MemberId, members), ct.Id }).ToList();
            }
            res.iTotalDisplayRecords = res.iTotalRecords;
            res.sEcho = pg.sEcho.ToString();

            return(Json(res));
        }
Example #25
0
        public void Execute(IJobExecutionContext context)
        {
            LoggingExtensions.Logging.Log.InitializeWith <LoggingExtensions.log4net.Log4NetLog>();

            var cateService  = new StockCategoryService();
            var stockService = new StockService();



            var cycleType = this.CycleType;

            IList <stockcategory> cateList = cateService.FindAll();

            foreach (var category in cateList)
            {
                IList <stock> stockList = stockService.GetStockByCategory(category.code);

                foreach (var stock in stockList)
                {
                    IList <PriceInfo> priceList = stockService.GetPriceInfo(stock.code, cycleType);

                    this.Log().Error("开始计算股票技术指数:" + stock.name + ",Code:" + stock.code);
                    var tech = new TechCalculate(ObjectType.Stock, cycleType, stock.code, priceList);
                    tech.Run();
                    this.Log().Error("计算结束:" + stock.name);

                    Thread.Sleep(100);
                }
            }
        }
Example #26
0
        public ActionResult CatEditPost(int id, string name, int pid)
        {
            if (id > 0)
            {
                St_cat aCat = DBService.GetEntity <St_cat>(id);
                aCat.Name = name;
                string oldpath = aCat.Path;
                if (aCat.PId != pid && pid > 0)
                {
                    var pcat = DBService.GetEntity <St_cat>(pid);
                    if (pcat != null && pcat.Id > 0 && !pcat.Path.StartsWith(aCat.Path))
                    {
                        aCat.PId  = pid;
                        aCat.Path = string.IsNullOrEmpty(pcat.Path) ? "," : pcat.Path + id.ToString() + ",";
                        var pa = aCat.Path.Split(',');
                        if (pa.Length > 3)
                        {
                            aCat.Level = pa.Length - 3;
                        }
                        else
                        {
                            aCat.Level = 0;
                        }

                        StockService.UpdateSubCatPath(id, oldpath, aCat.Path);
                    }
                }
                DBService.UpdateEntity <St_cat>(aCat);
                StockService.UpdateCatPath(id, aCat.Path);
            }
            return(RedirectToAction("Cat"));
        }
        private StockService CreateStockService()
        {
            var userId       = Guid.Parse(User.Identity.GetUserId());
            var stockService = new StockService(userId);

            return(stockService);
        }
Example #28
0
        /// <summary>
        /// Constructor
        /// </summary>
        public StockPriceViewModel()
        {
            //initialize the start real time feed command
            StartRealTimeFeedCommand = new RelayCommand(GetStockPriceFromService, CanStartCommand);

            //initialize the stop real time feed command
            StopRealTimeFeedCommand = new RelayCommand(StopFeedFromService, CanStartCommand);

            ShowHistoricWindowCommand = new RelayCommand(ShowHistoricWindow, CanShowHistoricWindow);
            //get the url and fields info from the app.config
            _serviceUrl    = ConfigurationManager.AppSettings["ServiceUrl"];
            _fieldsToFetch = ConfigurationManager.AppSettings["FieldsToFetch"];

            //get the symbols from the config, this can be inclued to be taken from UI as well
            CsvStockSymbols = ConfigurationManager.AppSettings["CsvSymbols"];

            //instantiate the stock service
            _stockService = new StockService();

            //instantiate the observable collection
            StockPrices = new ObservableCollection <StockPrice>();

            //initilize the timer ticks from app.config, if no value then default to 50 sec
            int interval;

            int.TryParse(ConfigurationManager.AppSettings["TimerIntervalInSeconds"], out interval);
            _stockPriceTimer          = new DispatcherTimer();
            _stockPriceTimer.Tick    += _stockPriceTimer_Tick;
            _stockPriceTimer.Interval = new TimeSpan(0, 0, 0, interval == 0 ? 50 : interval);
        }
Example #29
0
        public void GetChangeTest()
        {
            Transaction    transaction  = new Transaction();
            StockService   productStock = new StockService();
            List <Product> products     = productStock.Products;

            //Put $5.00 w/ no purchase should return 5$
            transaction.AcceptCash("5.00");
            decimal customerChange = transaction.ReturnChange();

            Assert.AreEqual(5.00m, customerChange, "Input: inserted $5 w/ no purchase");


            //Inserted $2 with a $1.45 purchase
            transaction.AcceptCash("2.00");
            transaction.SelectItem("A2", products);
            customerChange = transaction.ReturnChange();
            Assert.AreEqual(0.55m, customerChange, "Input: inserted $2 w/ $1.45 purchase");

            //Inserted 10.00 with a $1.50 & $3.65 purchase
            transaction.AcceptCash("10.00");
            transaction.SelectItem("B2", products);
            transaction.SelectItem("A4", products);
            customerChange = transaction.ReturnChange();
            Assert.AreEqual(4.85m, customerChange, "Input: inserted $10 w/ $1.50 & $3.65 purchase");
        }
Example #30
0
        private static void UpdateRatings(IEnumerable <string> symbols)
        {
            var dateTimeStamp = DateTime.Now;

            IList <Stock> stocks = new List <Stock>();

            IStockService _stockService = new StockService();

            //var symbols = new List<string>() { "aame", "dis"};
            foreach (var symbol in symbols.Select((value, index) => new { index, value }))
            {
                //System.Console.Write("\r{0} Remaining", symbols.Count - symbol.index);
                decimal?rating = _yahooDataProvider.GetStockRating(symbol.value);

                if (rating != null)
                {
                    stocks.Add(new Stock {
                        ModifiedDate = dateTimeStamp, Symbol = symbol.value, Rating = rating.Value
                    });

                    //System.Console.WriteLine("{0}: {1}", symbol.value, rating.Value);
                }

                Thread.Sleep(1000);
            }

            _stockService.AddOrUpdateStocks(stocks);
            _stockService.Dispose();
        }
Example #31
0
    ///<summary>
    ///A simple example of a job that sends out an email message.
    ///</summary>
    public void Execute()
    {
        //  IF Day == Saturday | Sunday Then Scheduler should run exactly once.
        //  Currently Not running the scheduler on Friday.

        if ( (DateTime.Now.DayOfWeek != DayOfWeek.Saturday && DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
            && DateTime.Now.Hour == schedulerTimeInHours) //  This task has to run at 9:00 A.M. (EST)
        //  if ((DateTime.Now.Hour % 2) != 0) //  This task has to run at 12:00 A.M. (Midnight EST)
        {
            dbOps = new DBOperations();
            stockService = new StockService();

            yesterday = DateTime.Now.AddDays(-1).ToString(dateFormatString);
            today = DateTime.Now.ToString(dateFormatString);
            tomorrow = DateTime.Now.AddDays(+1).ToString(dateFormatString);

            //  Update the DB. This task has to run between 9:00 A.M. and 10:00 A.M. (Morning EST)
            UpdateDB();

            //  Log the time at which the Scheduler runs the Execute() Method
            //  And the DB was Updated using the UpdateDB() Method.
            log.Log("Run Execute(). DB Updated. Yay!");
        }
    }
Example #32
0
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = (DBOperations)Application["dbOps"];
        rssReader = (RssReader)Application["rssReader"];
        gui = (GUIVariables)Application["gui"];
        stockService = (StockService)Application["stockService"];
        links = (Links)Application["links"];
        general = (General)Application["general"];
        engine = (ProcessingEngine)Application["engine"];

        //  username = Convert.ToString(Session["username"]);
        //  username = "******";

        if (Request.Cookies["stoockerCookie"] != null)
        {
            HttpCookie stoockerCookie = Request.Cookies["stoockerCookie"];
            username = dbOps.Decrypt(stoockerCookie["username"].ToString().Trim());
        }

        if (string.IsNullOrEmpty(username))
        {
            Response.Redirect(links.SessionExpiredPageLink);
        }
        else
        {
            upPredict = (int)ProcessingEngine.Movement.Up;
            downPredict = (int)ProcessingEngine.Movement.Down;

            yesterday = DateTime.Now.AddDays(-1).ToString(dateFormatString);
            today = DateTime.Now.ToString(dateFormatString);
            tomorrow = DateTime.Now.AddDays(+1).ToString(dateFormatString);

            //  If Today=Friday Then Tomorrow=Monday. Why? Because Stock Markets are closed on Weekends.
            if (DateTime.Now.DayOfWeek == DayOfWeek.Friday || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Friday)
                    tomorrow = DateTime.Now.AddDays(+3).ToString(dateFormatString);
                if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                    tomorrow = DateTime.Now.AddDays(+2).ToString(dateFormatString);
                if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                    tomorrow = DateTime.Now.AddDays(+1).ToString(dateFormatString);
            }

            string welcomeMessage = gui.BoldFontStart + "Welcome to" + gui.StoocksFont + gui.BoldFontEnd;
            WelcomeLabel.Text = welcomeMessage;

            //  Trace.Write("Enter LoadCommonIndicesData");
            LoadCommonIndicesData();
            //  Trace.Write("Exit LoadCommonIndicesData");

            Trace.Write("Enter ShowAlreadySelectedStocks");
            interestedStocks = ShowAlreadySelectedStocks(username);
            Trace.Write("Exit ShowAlreadySelectedStocks");

            if (!string.IsNullOrEmpty(alreadySelectedStocks))
            {
                Trace.Write("Enter LoadYahooFinanceBadgeIFrame");
                LoadYahooFinanceBadgeIFrame(alreadySelectedStocks);
                Trace.Write("Exit LoadYahooFinanceBadgeIFrame");
            }

            //  if (!Page.IsPostBack)
            {
                Trace.Write("Enter LoadUserData");
                UserDetailsLabel.Text = LoadUserData(username);
                Trace.Write("Exit LoadUserData");

                if (isShowUserStockData)
                {
                    Trace.Write("Enter LoadCurrentData");
                    LoadCurrentData();
                    Trace.Write("Exit LoadCurrentData");
                }

                MessageLabel.Text = "";

                Trace.Write("Enter LoadNews");
                string newsFeeds = "";
                if (isGenericNews)      //  Show the same News for all Users, Do Cache, Update every 30 minutes.
                {
                    newsFeeds = rssReader.LoadPerStockNews(alreadySelectedStocks);
                }
                else
                {
                    newsFeeds = rssReader.LoadGenericNews("", false);
                }
                Trace.Write("Exit LoadNews");

                if (!string.IsNullOrEmpty(newsFeeds))
                {
                    NewsMessageLabel.Text = gui.BoldFontStart + "Latest News & Recommended Readings from " + gui.StoocksFont + gui.BoldFontEnd;
                    NewsLabel.Text = newsFeeds;
                }
            }
        }
    }
Example #33
0
    protected void FindStock()
    {
        FindStockMessageLabel.Text = "";
        string symbol = FindStockTB.Text.Trim();
        string errorMessage = "";

        if (!string.IsNullOrEmpty(symbol))
        {
            string companyName = "";
            StockService stockService = new StockService();

            //  If the User entered the Stock Symbol, then extract the Company Name.
            //  if (stockService.XIgniteIsQuoteExists(symbol, out companyName))
            if (stockService.YahooCSVIsQuoteExists(symbol, out companyName))
            {
                symbol = symbol.ToUpper();
                if (companyName == "")
                {
                    companyName = symbol;
                }

                string queryString = "INSERT IGNORE INTO stoocks.company VALUES ('" + companyName + "','" + symbol + "','');";
                int retVal = dbOps.ExecuteNonQuery(queryString);

                if (retVal != -1)
                {
                    if (!StocksCBL.Items.Contains(new ListItem(symbol, symbol)))
                    {
                        StocksCBL.Items.Add(new ListItem(symbol, symbol));
                        string message = gui.GreenFontStart + " Symbol found. Added to the list above." + gui.GreenFontEnd;
                        FindStockMessageLabel.Text = message;
                    }
                }
            }
            else
            {
                errorMessage = gui.RedFontStart + " * Symbol not found." + gui.RedFontEnd;
                FindStockMessageLabel.Text = errorMessage;
            }
        }
        else
        {
            errorMessage = gui.RedFontStart + " Please Enter a Valid Stock Symbol." + gui.RedFontEnd;
            FindStockMessageLabel.Text = errorMessage;
        }
    }
Example #34
0
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = (DBOperations)Application["dbOps"];
        rssReader = (RssReader)Application["rssReader"];
        gui = (GUIVariables)Application["gui"];
        stockService = (StockService)Application["stockService"];
        links = (Links)Application["links"];
        log = (Logger)Application["log"];

        NewsSearchLabel.Text = gui.GreenFontStart + "Enter a Stock Symbol: " + gui.GreenFontEnd;

        if (Request.Cookies["stoockerCookie"] != null)
        {
            HttpCookie stoockerCookie = Request.Cookies["stoockerCookie"];
            username = dbOps.Decrypt(stoockerCookie["username"].ToString().Trim());

            GoBackLink.Text = "Home Page";
            LogoutLink.Visible = true;
        }
        else
        {
            GoBackLink.Text = "Login";
            LogoutLink.Visible = false;
        }

        //  if (!Page.IsPostBack)
        {
            GetNews(newsFeedsTable);
            RenderNews();

            StockTable.Visible = false;
        }
    }
        public ActionResult GetStocks(int companyId, int warehouseId, int commodityId, int commodityTypeId, int brandId, int start, int length)
        {
            int currentUserId = Convert.ToInt32(Session["CurrentUserId"].ToString());
            var StockSvc = new StockService();
            int from = start;
            int to = from + length - 1;

            var data = StockSvc.GetStockByRange(companyId, warehouseId, commodityId, commodityTypeId, brandId, from, to, currentUserId);
            var allCount = StockSvc.GetStockCount(companyId, warehouseId, commodityId, commodityTypeId, brandId, currentUserId);
            var result = new Dictionary<string, object>
                             {
                                 {"aaData", data},
                                 {"iTotalRecords", data.Count},
                                 {"iTotalDisplayRecords", allCount}
                             };

            return Json(result);
        }