public void validStockNameTest()
        {
            string stockName = "nono";
            Stock test = new Stock();

            if (!test.validStockName(stockName))
                Console.WriteLine("stock does not exist");
        }
 public void getDataTest()
 {
     string stockName = "nono";
     Stock test = new Stock();
     string price = test.getPriceFromYahoo(stockName);
     if(price==null)
         Console.WriteLine("is null");
 }
        public ServerMainThread()
        {
            Stocklist = new Stock();
            userList = new Users();

            thread = new Thread(new ThreadStart(serverthread));
            watchdog = new Thread(new ThreadStart(stockwatchdog));
            //serviceClient = new ClientServiceThread();

            stop = false;
        }
        public void getStockDataInFileTest()
        {
            Stock test = new Stock();
            test.getStockDataFromFile("test.txt");

            foreach(String key in test.stocksDictionary.Keys){
                Console.WriteLine("{0} {1} {2}", key, test.stocksDictionary[key].price, test.stocksDictionary[key].shares);
            }

            if (test.updateAllPrice())
            {
                test.writeAllStockData("test.txt");
            }
            else
            {
                Console.WriteLine("false");
            }
        }
        // Add a stock to the database
        public string AddStock(Stock stock)
        {
            SqlConnection conn = new SqlConnection(connString);
            string result = "";
            int rows = 0;
            try
            {
                conn.Open();
                string date = getSQLFormatDateNow();
                /* Create the insert query */
                string sqlcmd = "insert into StockTransaction (IDTransaction,IDClient,Email,Quantity,ShareType,ActionType,TransactionTime,Rate,Executed,Currency)";
                sqlcmd += "values (" + "'" + stock.id + "'" + "," + "'" + stock.client + "'" + "," + "'" + stock.email + "'" + "," + stock.quantity + ",";
                sqlcmd += "'" + stock.sType + "'" + "," + ((int)stock.type) + "," + "'" + date + "'" + "," + stock.price.ToString(CultureInfo.InvariantCulture) + ",";
                if (stock.executed)
                    sqlcmd += 1 + ",'" + stock.currency + "');";
                else
                    sqlcmd += 0 + ",'" + stock.currency + "');";

                if (Server.Program.Debug) Console.WriteLine("Query: " + sqlcmd);

                SqlCommand cmd = new SqlCommand(sqlcmd, conn);
                rows = cmd.ExecuteNonQuery();

                if (rows == 1)
                {
                    result = "200: The Stock has been added successfully!";
                    stock.price = convertCurrencyToUSD(stock.currency, stock.price);
                    stock.currency = "USD";
                    stockBroker.ReportNewStock(stock);
                }
            }
            catch (Exception e)
            {
                result = "500: " + e.Message;
            }
            finally
            {
                conn.Close();
            }

            if (Server.Program.Debug) Console.WriteLine(result);

            return result;
        }
 public Form1()
 {
     serverthread = new ServerMainThread();
     InitializeComponent();
     Stock obj = new Stock();
 }
 public void writeStockDataInFileTest()
 {
     Stock test = new Stock();
     test.writeNewStockData("test.txt", "FB");
 }
Beispiel #8
0
        public static void Connection(Object stockC)
        {
            Stock_Crawler crawl = (Stock_Crawler)stockC;
            //---listen at the specified IP and port no.---
            IPAddress   localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);

            Console.WriteLine("Listening...");
            listener.Start();

            //Main form stuff
            string json;

            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            while (true)
            {
                try
                {
                    //---get the incoming data through a network stream---
                    NetworkStream nwStream = client.GetStream();
                    byte[]        buffer   = new byte[client.ReceiveBufferSize];

                    //---read incoming stream---
                    int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

                    //---convert the data received into a string---
                    string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received : " + dataReceived);

                    //Stock logic
                    using (var web = new WebClient())
                    {
                        var url = $"";
                        //If batch, special URL used
                        url = $"https://api.iextrading.com/1.0/stock/{dataReceived}/book/";

                        //Download the returned API call as a string
                        json = web.DownloadString(url);
                        Console.WriteLine(url);
                    }
                    json = json.Replace("//", "");
                    var   v         = JToken.Parse(json);
                    var   mainStuff = v.First.First;
                    Stock stockShow = crawl.FillStock(mainStuff);

                    //---write back the text to the client---
                    Console.WriteLine("End Received. Sending back : " + stockShow.ToString());
                    string toSend = stockShow.ToString();
                    switch (stockShow.Rating)
                    {
                    case float n when n >= 100:
                        toSend += "\nRating of: Watch Carefully";
                        break;

                    case float n when n < 100 && n >= 80:
                        toSend += "\nRating of: Optimistic Look";
                        break;

                    case float n when n < 80 && n >= 60:
                        toSend += "\nRating of: Solid Choice";
                        break;

                    case float n when n < 60 && n >= 40:
                        toSend += "\nRating of: Decent Choice";
                        break;

                    case float n when n < 40 && n >= 20:
                        toSend += "\nRating of: Stable, but Stalled";
                        break;

                    default:
                        toSend += "\nRating of: Wary, Sell or Keep Eye On";
                        break;
                    }

                    byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(toSend);
                    nwStream.Write(bytesToSend, 0, bytesToSend.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    break;
                }
            }
            client.Close();
            listener.Stop();
            Connection(crawl);
        }
        public void HandleMessage(ServerResponse sender, Event e)
        {
            Event.EventTypeEnum enumType = e.EventType;
            Account             acc      = new Account("NULL", "NULL");

            switch (enumType)
            {
            case Event.EventTypeEnum.CreateAccount:
                //Check list of all accounts and make sure the username isn't taken. If not, send new account
                LoginEventData createAccData = JsonConvert.DeserializeObject <LoginEventData>(e.EventData.ToString());
                bool           canCreate     = true;
                if (accountList == null)
                {
                    accountList = new List <Account>();
                }
                for (int i = 0; i < accountList.Count && canCreate; i++)
                {
                    string s = accountList.ElementAt(i).Username;
                    if (s == createAccData.Username)
                    {
                        canCreate = false;
                    }
                }
                if (canCreate)
                {
                    acc          = new Account(createAccData.Username, createAccData.Password);
                    acc.IsOnline = true;
                    accountList.Add(acc);
                    updateActivityList("New user created: " + createAccData.Username);
                    updateUserList(accountList);

                    //Send success response
                    //sender.SendResponseToClient(new Event(Event.EventTypeEnum.ServerResponseSuccess, null));

                    //Send account data
                    sender.SendResponseToClient(new Event(Event.EventTypeEnum.ServerSendAccount, new AccountData(acc)));
                }
                else
                {
                    updateActivityList("User attempted to create an account with the same username as one that exists.");
                    sender.SendResponseToClient(new Event(Event.EventTypeEnum.ServerResponseError, new ServerErrorData("Account already exists. Try again.")));
                }
                break;

            case Event.EventTypeEnum.LoginAttempt:
                //Find if the username exits. If so, make sure the password is correct. Send account data
                bool           found     = false;
                LoginEventData loginData = JsonConvert.DeserializeObject <LoginEventData>(e.EventData.ToString());
                for (int i = 0; i < accountList.Count && !found; i++)
                {
                    string u = accountList.ElementAt(i).Username;
                    if (u == loginData.Username)
                    {
                        found = true;
                        acc   = accountList.ElementAt(i);
                    }
                }
                if (loginData.Password == acc.Password)
                {
                    //Successful login attempt
                    updateActivityList("User " + loginData.Username + " has logged in");
                    acc.IsOnline = true;
                    updateUserList(accountList);

                    sender.SendResponseToClient(new Event(Event.EventTypeEnum.ServerSendAccount, new AccountData(acc)));
                }
                else
                {
                    //Unsuccessful login attempt
                    updateActivityList("User " + loginData.Username + " made bad login attempt");
                    sender.SendResponseToClient(new Event(Event.EventTypeEnum.ServerResponseError, new ServerErrorData("We couldn't find that username/password combo. Try again.")));
                }
                break;

            case Event.EventTypeEnum.UserLogOff:
                LoginEventData logOffData = JsonConvert.DeserializeObject <LoginEventData>(e.EventData.ToString());
                foreach (Account a in accountList)
                {
                    if (a.Username == logOffData.Username)
                    {
                        updateActivityList(a.Username + " has logged off");
                        a.IsOnline = false;
                        updateUserList(accountList);
                        break;
                    }
                }
                break;

            case Event.EventTypeEnum.ClientStockRequest:
                StockRequestData reqData        = JsonConvert.DeserializeObject <StockRequestData>(e.EventData.ToString());
                string           reqSymbol      = reqData.StockSymbol.ToUpper();
                bool             inStockList    = false;
                Stock            reqStockToSend = new Stock("NULL");
                for (int i = 0; i < stockList.Count; i++)
                {
                    string tStock = stockList.ElementAt(i).TickerSymbol;
                    if (tStock == reqSymbol)
                    {
                        inStockList = true;
                        stockList.ElementAt(i).UpdateStock();
                        reqStockToSend = stockList.ElementAt(i);
                        break;
                    }
                }
                if (!inStockList)
                {
                    Stock tStock = new Stock(reqSymbol);
                    reqStockToSend = tStock;
                    stockList.Add(tStock);
                }
                StockData sd             = new StockData(reqStockToSend);
                Event     reqEventToSend = new Event(Event.EventTypeEnum.ServerSendStock, sd);
                sender.SendResponseToClient(reqEventToSend);
                updateStockList(stockList);
                break;

            case Event.EventTypeEnum.NULLEVENTENUM:
                updateActivityList("Null event received in ServerHandler.HandleMessage()");
                break;
            }
        }