コード例 #1
0
        protected void Button5_Click(object sender, EventArgs e)
        {
            ServiceReference1.ServiceClient sc1 = new ServiceReference1.ServiceClient();
            BookPurchaseInfo     info           = new BookPurchaseInfo();
            BookPurchaseResponse responce       = new BookPurchaseResponse();
            Boolean valid = true;

            try
            {
                float budget = float.Parse(TextBox9.Text);
                if (budget <= 0)
                {
                    TextBox13.Text = "budget must be positive";
                    return;
                }
                info.budget = budget;
                info.items  = new Dictionary <int, int>();
                //info.items.Add(int.Parse(TextBox10.Text), int.Parse(TextBox11.Text));
                for (int j = 0; j < count; j++)
                {
                    TextBox tb1 = (TextBox)Panel1.FindControl("book" + j);
                    TextBox tb2 = (TextBox)Panel1.FindControl("amount" + j);
                    try
                    {
                        int key   = int.Parse(tb1.Text);
                        int value = int.Parse(tb2.Text);
                        info.items.Add(key, value);
                    }
                    catch
                    {
                        TextBox13.Text = "Book number or amount is invalid";
                    }
                }

                responce.response = sc1.PurchaseBooks(info.budget, info.items, out responce.result);
                TextBox12.Text    = responce.response;
            }
            catch
            {
                TextBox13.Text = "budget is invalid";
            }
        }
コード例 #2
0
    public BookPurchaseResponse PurchaseBooks(BookPurchaseInfo info)
    {
        BookPurchaseResponse responce = new BookPurchaseResponse();
        List <Book>          books    = GetAllBooks();
        float budget = info.budget;
        Dictionary <int, int> items = info.items;
        float totalPrice            = 0.0f;

        foreach (var item in items)
        {
            int key   = item.Key;
            int value = item.Value;
            if (key > books.Count || key <= 0)
            {
                throw new Exception("Input is invalid");
            }
            if (value > books[key - 1].stock)
            {
                responce.result   = false;
                responce.response = "No enough stocks";
                return(responce);
            }
            totalPrice = totalPrice + value * books[key - 1].price;
        }

        if (totalPrice > info.budget)
        {
            responce.response = "No enough money";
            responce.result   = false;
            return(responce);
        }

        responce.response = Convert.ToString(info.budget - totalPrice);
        responce.result   = true;
        return(responce);
    }