Inheritance: Beverage, IHotBeverage
Beispiel #1
0
 //Must be inside a method
 static void structPractice()
 {
     Coffee coffeeStruct = new Coffee();
     coffeeStruct.Strength = 3;
     coffeeStruct.Bean = "Arabica";
     coffeeStruct.CountryofOrigin = "Kenya";
 }
Beispiel #2
0
    public static void Main()
    {
        // 処理行数を取得する
        var lines = int.Parse(System.Console.ReadLine());
        const int minLines = 1;
        const int maxLines = 10;
        if (lines < minLines || maxLines < lines) {
            throw new Exception("The num of lines must be " + minLines + "..." + maxLines + ".");
        }

        Coffee coffee = new Coffee();

        // 量の最大値・最小値を設定する
        const int minQuantity = 1;
        const int maxQuantity = 100;

        // カラムのタイプ
        const int columnTypeActType = 0;
        const int columnTypeQuantity = 1;
        const int columnSize = 2;

        // 行動のタイプ
        const int actTypeAddWater = 1;
        const int actTypeAddPowder = 2;
        const int actTypeTaste = 3;

        // コーヒーの処理を行う
        for (int idx = 0; idx < lines; idx++) {
            var actString = System.Console.ReadLine();
            var actArr = actString.Split(' ');
            if (actArr.Length != columnSize) {
                throw new Exception("Invalid format of action inputted.");
            }

            int actionType = int.Parse(actArr[columnTypeActType]);
            int quantity = int.Parse(actArr[columnTypeQuantity]);
            if (quantity < minQuantity || maxQuantity < quantity) {
                throw new Exception("The quantity must be " + minQuantity + "..." + maxQuantity + ".");
            }

            switch (actionType) {
                case actTypeAddWater:
                    coffee.AddWater(quantity);
                    break;
                case actTypeAddPowder:
                    coffee.AddPowder(quantity);
                    break;
                case actTypeTaste:
                    coffee.Taste(quantity);
                    break;
                default:
                    throw new Exception("Invalid action type detected. The action type must be 1(add water), 2(add powder), or 3(taste).");
            }
        }

        // 出力する
        System.Console.WriteLine((int)coffee.GetConsentration(true));
    }
Beispiel #3
0
        static void Main(string[] args)
        {

            Coffee coffee1 = new Coffee();
            coffee1.Strength = 3;
            coffee1.Bean = "Arabica";
            coffee1.CountryOfOrigin = "Kenya";
            //Coffee coffee1 = new Coffee(4, "Arabica", "Columbia");
            Console.WriteLine("\nStructures\nBean:{0}", coffee1.Bean);
        }
	static void Main()
	{
		Coffee normalCoffee = new Coffee(CoffeeSize.Normal);
		Coffee doubleCoffee = new Coffee(CoffeeSize.Double);

		Console.WriteLine("The {0} coffee is {1} ml.",
			  normalCoffee.Size, (int)normalCoffee.Size);
		Console.WriteLine("The {0} coffee is {1} ml.",
			  doubleCoffee.Size, (int)doubleCoffee.Size);
	}
        public void PrepareRecipe()
        {
            var coffee = new Coffee();

            coffee.PrepareRecipe();

            Assert.IsTrue(this.sw.ToString().Contains(BeverageMessages.BoilWater));
            Assert.IsTrue(this.sw.ToString().Contains(BeverageMessages.BrewCoffeeGrinds));
            Assert.IsTrue(this.sw.ToString().Contains(BeverageMessages.PourInCup));
            Assert.IsTrue(this.sw.ToString().Contains(BeverageMessages.AddSugarAndMilk));
        }
        static void Main(string[] args)
        {
            Coffee coffe1 = new Coffee();
            coffe1.Name = "Fourth Coffee Quencher";
            coffe1.CountryOfOrigin = "Indonesia";
            coffe1.Strenght = 3;
            coffe1.grind = "fine";
            Console.WriteLine("Name: {0}", coffe1.Name);
            Console.WriteLine("Country of origin: {0}", coffe1.CountryOfOrigin);
            Console.WriteLine("Strenght: {0}", coffe1.Strenght);
            Console.WriteLine("Grind: {0}", coffe1.grind);

            Console.ReadKey();


        }
Beispiel #7
0
 public static void AddCoffee(Coffee coffee)
 {
     string query = string.Format(
         @"INSERT INTO coffee VALUES ('{0}', '{1}', @prices, '{2}', '{3}','{4}', '{5}')",
         coffee.Name, coffee.Type, coffee.Roast, coffee.Country, coffee.Image, coffee.Review);
     command.CommandText = query;
     command.Parameters.Add(new SqlParameter("@prices", coffee.Price));
     try
     {
         conn.Open();
         command.ExecuteNonQuery();
     }
     finally
     {
         conn.Close();
         command.Parameters.Clear();
     }
 }
        public List <Coffee> GetAll()
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = /*"SELECT Id, Title, BeanVarietyId FROM Coffee;";*/

                                      "SELECT b.Name as BeanVarietyName, c.Id, c.Title, c.BeanVarietyId " +
                                      "FROM Coffee c " +
                                      "LEFT JOIN BeanVariety b on c.BeanVarietyId = b.Id;";

                    var reader  = cmd.ExecuteReader();
                    var coffees = new List <Coffee>();
                    while (reader.Read())
                    {
                        var coffee = new Coffee()
                        {
                            Id            = reader.GetInt32(reader.GetOrdinal("Id")),
                            Title         = reader.GetString(reader.GetOrdinal("Title")),
                            BeanVarietyId = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),

                            BeanVariety = new BeanVariety
                            {
                                Id   = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                                Name = reader.GetString(reader.GetOrdinal("BeanVarietyName"))
                            }
                        };


                        coffees.Add(coffee);
                    }

                    reader.Close();

                    return(coffees);
                }
            }
        }
        public ActionResult Edit([Bind(Include = "Journal,Author,Coffee")] CoffeeViewModel cvm, int PrivacyList)
        {
            if (ModelState.IsValid)
            {
                // Pull Journal from database, check authorization (same user), update, and save
                Journal journal = (from j in db.Journals
                                   where j.JournalID == cvm.Journal.JournalID
                                   select j).FirstOrDefault();
                if (journal.AuthorID == 1 || journal.AuthorID == 2)    // TODO: Update this if statement to check authorid against the current identity
                {
                    // TODO: send user to login page, or a "your kicked out" page
                    RedirectToAction("Index", "Home");
                }
                journal.Description = cvm.Journal.Description;
                journal.ImagePath   = cvm.Journal.ImagePath;
                journal.Location    = cvm.Journal.Location;
                journal.Rating      = cvm.Journal.Rating;
                journal.Title       = cvm.Journal.Title;
                journal.PrivacyType = PrivacyList;

                // Pull Coffee from database, update fields, and save
                Coffee coffee = (from c in db.Coffees
                                 where c.JournalID == journal.JournalID
                                 select c).FirstOrDefault();

                coffee.FoodPairing = cvm.Coffee.FoodPairing;
                coffee.Origin      = cvm.Coffee.Origin;
                coffee.RoastType   = cvm.Coffee.RoastType;


                // Set objects and save
                db.Entry(journal).State = EntityState.Modified;
                db.Entry(coffee).State  = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.PrivacyList = GetPrivacyList(PrivacyList);
            return(View(cvm));
        }
Beispiel #10
0
        public void TypeSafetyExampleOne()
        {
            // Type Safety Limitations for Non-Generic Collections
            var coffee1    = new Coffee();
            var coffee2    = new Coffee();
            var tea1       = new Tea();
            var arrayList1 = new ArrayList();

            arrayList1.Add(coffee1);
            arrayList1.Add(coffee2);
            arrayList1.Add(tea1);
            // The Sort method throws a runtime exception because the collection is not homogenous.
            try
            {
                arrayList1.Sort();
                // The cast throws a runtime exception because you cannot cast a Tea instance to a Coffee instance.
                Coffee coffee3 = (Coffee)arrayList1[2];
            }
            catch (Exception e) {
                Console.WriteLine("This code WILL produce an exception.  {0}", e.Message);
            }
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            BeveragesBase coffee   = new Coffee();
            BeveragesBase blackTea = new BlackTea();
            BeveragesBase greenTea = new GreenTea();

            Console.WriteLine("Standard beverages: ");
            ShowBeverageInfo(coffee);
            ShowBeverageInfo(blackTea);
            ShowBeverageInfo(greenTea);

            BeveragesBase cappuccino           = new MilkAdd(new SugarAdd(new Coffee()));
            BeveragesBase blackTeaWithSugar    = new SugarAdd(new BlackTea());
            BeveragesBase hotChocolateWithMilk = new ChocolateAdd(new SugarAdd(new MilkAdd(new Coffee())));

            Console.WriteLine("Custom beverages: ");
            ShowBeverageInfo(cappuccino);
            ShowBeverageInfo(blackTeaWithSugar);
            ShowBeverageInfo(hotChocolateWithMilk);

            Console.ReadLine();
        }
Beispiel #12
0
    static void Main()
    {
        Coffee coffee = new Coffee();

        // monitor.NotifyCoffeeReady()
        // A reference to a static method
        coffee.CoffeeReady += new Coffee.CoffeeEventHandler(MyCoffeeIsReady);
        // AddHandler coffee.CoffeeReady, AddressOf MyCoffeeIsReady
        CoffeeClanMember [] coffeeClanMember = new CoffeeClanMember[10 + 1];
        // Dim coffeeClanMember(10) As CoffeeClanMember
        int i;

        for (i = 0; i <= 10; i++)
        {
            coffeeClanMember[i] = new CoffeeClanMember();
            // A reference to an instance method.
            coffee.CoffeeReady += new Coffee.CoffeeEventHandler(coffeeClanMember[i].MyCoffeeIsReady);
        }

        // A single RaiseEvent will notify me and the entire coffee clan.
        coffee.NotifyCoffeeReady();
    }
Beispiel #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("\n--- Tea ---");
            var tea = new Tea();

            tea.PrepareRecipe();

            Console.WriteLine("\n--- Coffee ---");
            var coffee = new Coffee();

            coffee.PrepareRecipe();

            Console.WriteLine("\n--- Tea (with hook)---");
            var teaWithHook = new TeaWithHook();

            teaWithHook.PrepareRecipe();

            Console.WriteLine("\n--- Coffee (with hook) ---");
            var coffeeWithHook = new CoffeeWithHook();

            coffeeWithHook.PrepareRecipe();
        }
Beispiel #14
0
        public async Task DemonstrateAsync()
        {
            Coffee cup = PourCoffee();

            Console.WriteLine("coffee is ready");

            // Start tasks and dring a coffee
            Task <Egg>   eggsTask  = FryEggsAsync();
            Task <Bacon> baconTask = FryBaconAsync();
            Task <Toast> toastTask = ToastBreadAsync();

            Console.WriteLine("All tasks have been started. Now go and drink coffee.");

            await Task.WhenAll(eggsTask, baconTask, toastTask);

            Console.WriteLine("Everything is ready just apply butter and jam on the toast");

            ApplyButter(toastTask.Result);
            ApplyJam(toastTask.Result);

            Console.WriteLine("Breakfast is ready!");
        }
Beispiel #15
0
        public void Load(string baseId)
        {
            CoffeeMachineState state = SaveLoadSystem.Load <CoffeeMachineState>(baseId, "CoffeeMachine");

            if (state == null)
            {
                state = new CoffeeMachineState();
            }

            currentCoffee        = state.currentCoffee;
            coffeeSetFromOutside = state.coffeeSetFromOutside;
            coffeeStrength       = state.coffeeStrength;
            coffeeSize           = state.coffeeSize;

            if (state.status == Status.Idle || state.status == Status.Busy)
            {
                TurnOn();
            }

            MyLog.TryLog(this, $"Loaded", debug);
            MyLog.TryLog(this, JsonConvert.SerializeObject(state), debug);
        }
        public void AddSteps_WhenCoffee_ShouldReturnCorrectData()
        {
            // Arrange

            var          testHotDrink  = new Coffee();
            const string expectedName  = "Coffee";
            const string expectedImage = "coffee.jpg";
            var          expectedSteps = new List <string>
            {
                "Boil some water",
                "Brew the coffee grounds",
                "Pour coffee in the cup",
                "Add sugar and milk"
            };

            // Assert

            testHotDrink.Steps.Should().BeEquivalentTo(expectedSteps);
            testHotDrink.Name.Should().Be(expectedName);
            testHotDrink.Image.Should().Be(expectedImage);
            testHotDrink.Id.Should().Be(DrinkType.Coffee);
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            Coffee cup = PourCoffee();

            Console.WriteLine("coffee is ready");
            Egg egg = FryEggs(2);

            Console.WriteLine("eggs are ready");
            Bacon bacon = FryBacon(3);

            Console.WriteLine("Bacon is ready");
            Toast toast = ToastBread(2);

            ApplyButter(toast);
            ApplyJan(toast);
            Console.WriteLine("toast is ready");
            Juice oj = PourOJ();

            Console.WriteLine("OJ is ready");
            Console.WriteLine("");
            Console.WriteLine("Breakfast is ready!".ToUpper());
        }
        public void Update(Coffee coffee)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        UPDATE Coffee 
                           SET Title = @Title, 
                               BeanVarietyId = @beanVarietyId, 
                              
                         WHERE Id = @id";
                    cmd.Parameters.AddWithValue("@id", coffee.Id);
                    cmd.Parameters.AddWithValue("@title", coffee.Title);
                    cmd.Parameters.AddWithValue("@beanVarietyId", coffee.BeanVarietyId);


                    cmd.ExecuteNonQuery();
                }
            }
        }
Beispiel #19
0
        //Marked with async to denote that this is an asynchronous method
        //Returns a task object -
        public static async Task BreakfastExample()
        {
            Coffee cup = PourCoffee();

            Console.WriteLine("coffee is ready");

            //Construct our tasks
            var eggsTask  = FryEggsAsync(2);
            var baconTask = FryBaconAsync(3);
            var toastTask = MakeToastWithButterAndJamAsync(2);

            var breakfastTasks = new List <Task> {
                eggsTask, baconTask, toastTask
            };

            while (breakfastTasks.Count > 0)
            {
                Task finishedTask = await Task.WhenAny(breakfastTasks);

                if (finishedTask == eggsTask)
                {
                    Console.WriteLine("eggs are ready");
                }
                else if (finishedTask == baconTask)
                {
                    Console.WriteLine("bacon is ready");
                }
                else if (finishedTask == toastTask)
                {
                    Console.WriteLine("toast is ready");
                }
                breakfastTasks.Remove(finishedTask);
            }

            Juice oj = PourOJ();

            Console.WriteLine("oj is ready");
            Console.WriteLine("Breakfast is ready!");
        }
        private void CoffeeListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedCoffee = e.AddedItems[0] as Coffee;

            if (selectedCoffee != null)
            {
                CoffeeIdLabel.Content          = selectedCoffee.CoffeeId;
                CoffeeNameLabel.Content        = selectedCoffee.CoffeeName;
                CoffeeDescriptionLabel.Content = selectedCoffee.Description;
                CoffeePriceLabel.Content       = selectedCoffee.Price;

                BitmapImage img  = new BitmapImage();
                var         path = Path.Combine(Environment.CurrentDirectory, "Images", "coffee" + selectedCoffee.CoffeeId + ".jpg");
                img.BeginInit();
                img.UriSource = new Uri("/KamilCoffeeStore.StockManagement.App;component/Images/coffee" + selectedCoffee.CoffeeId + ".jpg", UriKind.RelativeOrAbsolute);
                img.EndInit();

                CoffeeImage.Source = img;

                EditCofeeButton.Visibility = Visibility.Visible;
            }
        }
Beispiel #21
0
        static async Task Main(string[] args)
        {
            Coffee cup = PourCoffee();

            Console.WriteLine("-- coffee is ready");

            var eggsTask  = FryEggsAsync(2);
            var baconTask = FryBaconAsync(3);
            var toastTask = MakeToastWithButterAndJamAsync(2);

            var breakfastTasks = new List <Task> {
                eggsTask, baconTask, toastTask
            };

            while (breakfastTasks.Count > 0)
            {
                Task finishedTask = await Task.WhenAny(breakfastTasks);

                if (finishedTask == eggsTask)
                {
                    Console.WriteLine("-- eggs are ready");
                }
                else if (finishedTask == baconTask)
                {
                    Console.WriteLine("-- bacon is ready");
                }
                else if (finishedTask == toastTask)
                {
                    Console.WriteLine("-- toast is ready");
                }
                breakfastTasks.Remove(finishedTask);
            }

            Juice oj = PourOJ();

            Console.WriteLine("-- oj is ready");
            Console.WriteLine("---- Breakfast is ready!");
            Console.ReadLine();
        }
Beispiel #22
0
        public static void TestTemplateMethod()
        {
            Console.WriteLine("----------Template method----------");
            Tea teaWithoutCondiments = new Tea(false);
            Tea teaWithCondiments    = new Tea(true);

            Coffee coffeeWithoutCondiments = new Coffee(false);
            Coffee coffeeWithCondiments    = new Coffee(true);

            Console.WriteLine("\nTea without condiments:");
            teaWithoutCondiments.PrepareBeverage();

            Console.WriteLine("\nTea with condiments:");
            teaWithCondiments.PrepareBeverage();

            Console.WriteLine("\nCoffee without condiments:");
            coffeeWithoutCondiments.PrepareBeverage();

            Console.WriteLine("\nCoffee with condiments:");
            coffeeWithCondiments.PrepareBeverage();
            Console.WriteLine("----------------------------------\n");
        }
        public ActionResult <Coffee> Post([FromBody] Coffee coffee)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"INSERT INTO Coffee (Title, BeanType)
                                        OUTPUT INSERTED.Id
                                        VALUES (@title, @beanType)";
                    cmd.Parameters.Add(new SqlParameter("@title", coffee.Title));
                    cmd.Parameters.Add(new SqlParameter("@beanType", coffee.BeanType));

                    int newId = (int)cmd.ExecuteScalar();
                    coffee.Id = newId;
                    return(CreatedAtRoute("GetCoffee", new { id = newId }, coffee));

                    // or return this get:
                    // return RedirectToAction();
                }
            }
        }
Beispiel #24
0
 public ActionResult Edit([Bind(Include = "Id,Name,Origin,CoffeeType,Rating,Strength,Description,Stock,Price")] CoffeeDTO newcoffee)
 {
     if (ModelState.IsValid)
     {
         Coffee coffee = new Coffee
         {
             Id          = newcoffee.Id,
             Name        = newcoffee.Name,
             Origin      = newcoffee.Origin,
             CoffeeType  = newcoffee.CoffeeType,
             Rating      = newcoffee.Rating,
             Strength    = newcoffee.Strength,
             Description = newcoffee.Description,
             Price       = newcoffee.Price,
             Stock       = newcoffee.Stock,
             Type        = newcoffee.Type
         };
         srv1.UpdateCoffee(coffee);
         return(RedirectToAction("Index"));
     }
     return(View(newcoffee));
 }
Beispiel #25
0
        public ActionResult <Coffee> Post([FromBody] Coffee coffee)
        {
            if (coffee.Name == null)
            {
                return(BadRequest("Product can't be added without a Name!"));
            }
            if (coffee.Category == null)
            {
                return(BadRequest("Product can't be added if not part of any Category!"));
            }
            if (coffee.Country == null)
            {
                return(BadRequest("Product must have an origin country!"));
            }
            if (coffee.Prise.Equals(null))
            {
                return(BadRequest("Product can't be Free!"));
            }

            _coffeeService.SaveCoffee(coffee);
            return(Ok($"Item with Name: {coffee.Name} was Added"));
        }
Beispiel #26
0
        public static void Main()
        {
            Coffee coffee = new Coffee();

            coffee.Bean            = "Strong";
            coffee.CountryOfOrigin = "Colombia";
            coffee.Strength        = 5;
            Coffee coffee2 = new Coffee
            {
                Bean = "Soft", CountryOfOrigin = "Ethiophya", Strength = 3
            };

            //Accediendo a la struct Menu
            Menu   menu        = new Menu("bev1", "bev2");
            string firstDrink  = menu.beverages[0];
            var    SecondDrink = menu[1];

            //Accediento al array usando el indexer
            firstDrink = menu[0];
            string secondDrink     = menu[1];
            int    numberOfChoices = menu.Length;
        }
Beispiel #27
0
        public void CoffeeExists()
        {
            DbContextOptions <CoffeeShopDbContext> options = new DbContextOptionsBuilder <CoffeeShopDbContext>().UseInMemoryDatabase("CanCreateCoffee").Options;

            using (CoffeeShopDbContext context = new CoffeeShopDbContext(options))
            {
                Coffee coffee = new Coffee();
                coffee.ID          = 1;
                coffee.Name        = "latte";
                coffee.Price       = 2;
                coffee.Description = "tasty";
                coffee.URL         = "www.coffee.com";

                CoffeeManager coffeeManager = new CoffeeManager(context);

                coffeeManager.CoffeeExists(1);

                var result = context.Coffee.Any(c => c.ID == 1);

                Assert.False(result);
            }
        }
Beispiel #28
0
        public async void CanCreateCoffee()
        {
            DbContextOptions <CoffeeShopDbContext> options = new DbContextOptionsBuilder <CoffeeShopDbContext>().UseInMemoryDatabase("CanCreateCoffee").Options;

            using (CoffeeShopDbContext context = new CoffeeShopDbContext(options))
            {
                Coffee coffee = new Coffee();
                coffee.ID          = 1;
                coffee.Name        = "latte";
                coffee.Price       = 2;
                coffee.Description = "tasty";
                coffee.URL         = "www.coffee.com";

                CoffeeManager coffeeManager = new CoffeeManager(context);

                await coffeeManager.CreateCoffee(coffee);

                var result = context.Coffee.FirstOrDefault(c => c.ID == coffee.ID);

                Assert.Equal(coffee, result);
            }
        }
        public List <Coffee> GetAll()
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT c.Id, c.[Title], c.BeanVarietyId, b.Name, b.Id, b.Region
                        FROM Coffee c
                        JOIN BeanVariety b ON c.BeanVarietyId = b.Id;";

                    var reader  = cmd.ExecuteReader();
                    var coffees = new List <Coffee>();
                    while (reader.Read())
                    {
                        var coffee = new Coffee()
                        {
                            Id            = reader.GetInt32(reader.GetOrdinal("Id")),
                            Title         = reader.GetString(reader.GetOrdinal("Title")),
                            BeanVarietyId = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                            BeanVariety   = new BeanVariety()
                            {
                                Id     = reader.GetInt32(reader.GetOrdinal("Id")),
                                Name   = reader.GetString(reader.GetOrdinal("Name")),
                                Region = reader.GetString(reader.GetOrdinal("Region")),
                            }
                        };



                        coffees.Add(coffee);
                    }

                    reader.Close();

                    return(coffees);
                }
            }
        }
Beispiel #30
0
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] Coffee coffee)
        {
            try
            {
                using (SqlConnection conn = Connection)
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = @"UPDATE Coffee
                                            SET Title = @title,
                                                BeanType = @beanType
                                            WHERE Id = @id";
                        cmd.Parameters.Add(new SqlParameter("@title", coffee.Title));
                        cmd.Parameters.Add(new SqlParameter("@beanType", coffee.BeanType));
                        cmd.Parameters.Add(new SqlParameter("@id", id));

                        int rowsAffected = await cmd.ExecuteNonQueryAsync();

                        if (rowsAffected > 0)
                        {
                            return(new StatusCodeResult(StatusCodes.Status204NoContent));
                        }
                        throw new Exception("No rows affected");
                    }
                }
            }
            catch (Exception)
            {
                if (!CoffeeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #31
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string name    = txtName.Text;
                string type    = txtType.Text;
                double price   = Convert.ToDouble(txtPrice.Text);
                string roast   = txtRoast.Text;
                string country = txtCountry.Text;
                string image   = "../Images/Coffee/" + ddlImage.SelectedValue;
                string review  = txtReview.Text;

                Coffee coffee = new Coffee(name, type, price, roast, country, image, review);
                ConnectionClass.AddCoffee(coffee);
                lblResult.Text = "Upload succesful!";
                ClearTextFields();
            }
            catch (Exception)
            {
                lblResult.Text = "Upload failed!";
            }
        }
Beispiel #32
0
        // ASYNC

        static async Task Main(string[] args)
        {
            Coffee cup = PourCoffee();

            Console.WriteLine("coffee is ready");
            Egg eggs = await FryEggs(2);

            Console.WriteLine("eggs are ready");
            Bacon bacon = await FryBacon(3);

            Console.WriteLine("bacon is ready");
            Toast toast = await ToastBread(2);

            ApplyButter(toast);
            ApplyJam(toast);
            Console.WriteLine("toast is ready");
            Juice oj = PourOJ();

            Console.WriteLine("oj is ready");

            Console.WriteLine("Breakfast is ready!");
        }
Beispiel #33
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var coffee = new Coffee
                {
                    Id          = request.Id,
                    Name        = request.Name,
                    Description = request.Description,
                    Price       = request.Price,
                    Image       = request.Image,
                    Date        = request.Date
                };

                _context.Coffee.Add(coffee);
                var success = await _context.SaveChangesAsync() > 0;

                if (success)
                {
                    return(Unit.Value);
                }

                throw new Exception("Problem with saving");
            }
Beispiel #34
0
        public List <Coffee> GetAll()
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT c.Id AS cId, [Name], Title, BeanVarietyId, Region, Notes 
                                        FROM Coffee c
                                        JOIN BeanVariety bv ON bv.Id = c.BeanVarietyId;";
                    var reader    = cmd.ExecuteReader();
                    var varieties = new List <Coffee>();
                    while (reader.Read())
                    {
                        var coffee = new Coffee()
                        {
                            Id            = reader.GetInt32(reader.GetOrdinal("cId")),
                            Title         = reader.GetString(reader.GetOrdinal("Title")),
                            BeanVarietyId = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                            BeanVariety   = new BeanVariety()
                            {
                                Id     = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                                Name   = reader.GetString(reader.GetOrdinal("Name")),
                                Region = reader.GetString(reader.GetOrdinal("Region"))
                            }
                        };
                        if (!reader.IsDBNull(reader.GetOrdinal("Notes")))
                        {
                            coffee.BeanVariety.Notes = reader.GetString(reader.GetOrdinal("Notes"));
                        }
                        varieties.Add(coffee);
                    }

                    reader.Close();

                    return(varieties);
                }
            }
        }
Beispiel #35
0
        public List <Coffee> GetAllCoffees()
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT c.Id, c.Title, c.BeanVarietyId, b.[Name], b.Region, b.Notes
                                       FROM Coffee c
                                       LEFT JOIN BeanVariety b
                                       ON c.BeanVarietyId = b.Id";
                    var           reader  = cmd.ExecuteReader();
                    List <Coffee> coffees = new List <Coffee>();
                    while (reader.Read())
                    {
                        Coffee coffee = new Coffee()
                        {
                            Id            = reader.GetInt32(reader.GetOrdinal("Id")),
                            Title         = reader.GetString(reader.GetOrdinal("Title")),
                            BeanVarietyId = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                            BeanVariety   = new BeanVariety()
                            {
                                Id     = reader.GetInt32(reader.GetOrdinal("BeanVarietyId")),
                                Name   = reader.GetString(reader.GetOrdinal("Name")),
                                Region = reader.GetString(reader.GetOrdinal("Region"))
                            }
                        };

                        if (!reader.IsDBNull(reader.GetOrdinal("Notes")))
                        {
                            coffee.BeanVariety.Notes = reader.GetString(reader.GetOrdinal("Notes"));
                        }
                        coffees.Add(coffee);
                    }
                    reader.Close();
                    return(coffees);
                }
            }
        }
        Get([FromRoute] int id)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                        SELECT
                            Id, Title, BeanType
                        FROM Coffee
                        WHERE Id = @id";
                    cmd.Parameters.Add(new SqlParameter("@id", id));
                    SqlDataReader reader = cmd.ExecuteReader();

                    Coffee coffee = null;

                    if (reader.Read())
                    {
                        coffee = new Coffee
                        {
                            Id       = reader.GetInt32(reader.GetOrdinal("Id")),
                            Title    = reader.GetString(reader.GetOrdinal("Title")),
                            BeanType = reader.GetString(reader.GetOrdinal("BeanType"))
                        };
                    }

                    if (coffee == null)
                    {
                        return(NotFound());
                    }


                    reader.Close();

                    return(Ok(coffee));
                }
            }
        }
        static async Task Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            Coffee cup = PourCoffee();

            Console.WriteLine("coffee is ready");

            Task <Egg>   eggsTask  = FryEggsAsync(2);
            Task <Bacon> baconTask = FryBaconAsync(3);
            Task <Toast> toastTask = ToastBreadAsync(2);

            Toast toast = await toastTask;

            ApplyButter(toast);
            ApplyJam(toast);
            Console.WriteLine("toast is ready");

            Juice oj = PourOJ();

            Console.WriteLine("oj is ready");


            Egg eggs = await eggsTask;

            Console.WriteLine("eggs are ready");

            Bacon bacon = await baconTask;

            Console.WriteLine("bacon is ready");

            Console.WriteLine("Breakfast is ready!");

            stopwatch.Stop();

            Console.WriteLine($"Total time : {stopwatch.Elapsed}");
        }
    static void Main()
    {
        Person anonimous = new Person();
        Console.WriteLine("Person 1: name: {0}, age: {1}",anonimous.Name??"[unnamed]",anonimous.Age);

        Person peter = new Person("Pet", 9999);
        Console.WriteLine("Person 2: name:{0}, age: {1}",peter.Name,peter.Age);
        Console.WriteLine();

        Point centerPoint = new Point();
        centerPoint.Name = "Center of the coordinate system";
        Console.WriteLine("First point:({0},{1}) has name:'{2}'",centerPoint.XCoord,centerPoint.YCoord,centerPoint.Name);

        Point point77 = new Point(7, 7);
        Console.WriteLine("Second point:({0},{1}) has name'{2}'",point77.XCoord,point77.YCoord,point77.Name);
        Console.WriteLine();

        // DEFINING PROPERTIES
        Rectangle firstRect = new Rectangle(5.0f, 3.0f);
        Console.WriteLine("Rectangle 1 is {0}x{1} and has area: {2}",firstRect.Height,firstRect.Width,firstRect.Area);

        Rectangle secondRect = new Rectangle(4.0f, 3.0f);
        Console.WriteLine("Rectangle 2 is {0}x{1} and has area: {2}",secondRect.Height,secondRect.Width,secondRect.Area);
        Console.WriteLine();

        UserProfile profile = new UserProfile(4344334, "Asen", "Pifov");
        Console.WriteLine(profile);
        Console.WriteLine();

        // METHODS
        Point p1 = new Point(2,3);
        Point p2 = new Point(3,4);
        Console.WriteLine(p1.CalculateDistance(p2));

        // DOGMEETING
        Console.Write("Enter first dog name: ");
        string dogName = Console.ReadLine();
        Console.Write("Enter first dog breed: ");
        string dogBreed = Console.ReadLine();

        Dog firstDog = new Dog(dogName, dogBreed);

        Dog secondDog = new Dog();
        Console.Write("Enter second dog name: ");
        secondDog.Name = Console.ReadLine();
        Console.Write("Enter second dog breed: ");
        secondDog.Breed = Console.ReadLine();

        Dog thirdDog = new Dog();
        Dog[] dogs = new Dog[] { firstDog, secondDog, thirdDog };
        foreach (Dog dog in dogs)
        {
            dog.saybau();
        }

        // DAYOFWEEK
        DaysOfWeek day = DaysOfWeek.wed;
        Console.WriteLine(day);

        day = DaysOfWeek.mon;
        Console.WriteLine(++day);

        Console.WriteLine((int)day);

        day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), "mon");
        Console.WriteLine(day);

        // COFFEESIZE
        Coffee normalCoffee = new Coffee(CoffeeSize.Normal);
        Coffee doubleCoffee = new Coffee(CoffeeSize.Double);

        Console.WriteLine("The {0} coffee is {1} ml.",normalCoffee.Size,(int)normalCoffee.Size);
        Console.WriteLine("The {0} coffee is {1} ml.",doubleCoffee.Size,(int)doubleCoffee.Size);

        // SAVEPERSONINFO
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        Console.Write("Enter your age: ");
        int age = int.Parse(Console.ReadLine());

        try
        {
            SavePerson person = new SavePerson(name, age);
            Console.WriteLine("Hello {0}!", person.Name);
            Console.WriteLine("Your age is {0}.", person.Age);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Can not create person object:"+ex);
        }
    }
 public static void CoffeePanel()
 {
     IDecorator blackCoffee = new BlackCoffee();
     ShowCoffee(blackCoffee);
     IDecorator coffee = new Coffee(blackCoffee);
     ShowCoffee(coffee);
     IDecorator chocolate = new ChoclateCoffee(coffee);
     ShowCoffee(chocolate);
     IDecorator cream = new CreamCoffee(coffee);
     ShowCoffee(cream);
     IDecorator creamAndChocolate = new CreamCoffee(chocolate);
     ShowCoffee(creamAndChocolate);
 }
Beispiel #40
0
    public static Coffee GetCoffeeByID(int id)
    {
        string query = string.Format("SELECT * FROM coffee WHERE id =  '{0}'", id);
        Coffee coffee = null;

        try
        {
            conn.Open();
            command.CommandText = query;
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                string name = reader.GetString(1);
                string type = reader.GetString(2);
                double price = reader.GetDouble(3);
                string roast = reader.GetString(4);
                string country = reader.GetString(5);
                string image = reader.GetString(6);
                string review = reader.GetString(7);

                coffee = new Coffee(id, name, type, price, roast, country, image, review);
            }
        }
        finally
        {
            conn.Close();
        }

        return coffee;
    }
 public CoffeeDecorator(Coffee decoratedCoffee)
 {
     this.decoratedCoffee = decoratedCoffee;
 }
Beispiel #42
0
 // Use this for initialization
 void Start()
 {
     mainSelected = GameObject.Find ("QUAD").GetComponent<main> ();
     coffeeThings = GameObject.Find ("playerDot").GetComponent<Coffee> ();
     epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
 }
Beispiel #43
0
    public static ArrayList GetCoffeeByType(string coffeeType)
    {
        ArrayList list = new ArrayList();
        string query = string.Format("SELECT * FROM coffee WHERE type LIKE '{0}'", coffeeType);

        try
        {
            conn.Open();
            command.CommandText = query;
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                int id = reader.GetInt32(0);
                string name = reader.GetString(1);
                string type = reader.GetString(2);
                double price = reader.GetDouble(3);
                string roast = reader.GetString(4);
                string country = reader.GetString(5);
                string image = reader.GetString(6);
                string review = reader.GetString(7);

                Coffee coffee = new Coffee(id, name, type, price, roast, country, image, review);
                list.Add(coffee);
            }
        }
        finally
        {
            conn.Close();
        }

        return list;
    }
 public Milk(Coffee decoratedCoffee)
     : base(decoratedCoffee)
 {
 }
Beispiel #45
0
    // Use this for initialization
    IEnumerator Start()
    {
        // First, check if user has location service enabled
        mainVar = GameObject.Find ("QUAD").GetComponent<main> ();
        coffeeThings = GetComponent<Coffee> ();

        pastCoffeeLocations.Add (21);
        pastCoffeeLocations.Add (22);
        pastCoffeeLocations.Add (27);
        pastCoffeeLocations.Add (24);
        pastCoffeeLocations.Add (25);

        epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);

        if (!Input.location.isEnabledByUser)
            yield break;

        // Start service before querying location
        Input.location.Start();

        // Wait until service initializes
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            yield return new WaitForSeconds(1);
            maxWait--;
        }

        // Service didn't initialize in 20 seconds
        if (maxWait < 1)
        {
            //			print("Timed out");
            yield break;
        }

        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed)
        {
            //			print("Unable to determine device location");
            temp = false;
            yield break;
        }
        else
        {
            temp = true;
            // Access granted and location value could be retrieved
            //			latitude = Input.location.lastData.latitude;
            //			longtitude = Input.location.lastData.longitude;
            //			altitude = Input.location.lastData.altitude;
            //			horizontal = Input.location.lastData.horizontalAccuracy;
            //			timestamp = Input.location.lastData.timestamp;
            //			print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
        }

        // Stop service if there is no need to query location updates continuously
        //		Input.location.Stop();
    }
Beispiel #46
0
 // Use this for initialization
 void Start()
 {
     coffeeThings = GameObject.Find ("playerDot").GetComponent<Coffee> ();
 }
Beispiel #47
0
        static void Main(string[] args)
        {
            #region using a struct

            Coffee coffee1 = new Coffee();
            coffee1.Name = "Fourth Coffee Quencher";
            coffee1.CountyOfOrigin = "Indonesia";
            coffee1.Strength = 3;
            coffee1.grind = "fine";
            Console.WriteLine("Name: {0}", coffee1.Name);
            Console.WriteLine("Country of Origin: {0}", coffee1.CountyOfOrigin);
            Console.WriteLine("Strength: {0}", coffee1.Strength);
            Console.WriteLine("The grind is: {0}", coffee1.grind);

            #endregion

            #region enum

            //int x = (int)Days.Sunday;
            //int y = (int)Days.Friday;
            //Console.WriteLine("Sun = {0}", x);
            //Console.WriteLine("Fri = {0}", y);

            #endregion

            #region Variables, Operators & Expressions

            //int condition1;
            //int condition2;
            //int switchCondition;
            #endregion

            #region Decision Statements

            ////if sample
            //condition1 = 1;
            //if (condition1 == 1)
            //{
            //    Console.WriteLine("comparison evaluated to true.");
            //}

            //Console.WriteLine("This executes after the if, regardles of what has taken place.");

            //if-else sample
            //condition1 = 3;
            //if (condition1 == 1)
            //{
            //    Console.WriteLine("comparison evaluated to true");
            //}
            //else
            //{
            //    Console.WriteLine("comparison evaluate to false.");
            //}

            //if-else-if sample
            //condition1 = 1;
            //condition2 = 2;
            //if (condition1 == 3)
            //{
            //    Console.WriteLine("condition1 is true.");
            //}
            //else if (condition2 == 1)
            //{
            //    Console.WriteLine("condition2 is true.");
            //}
            //else
            //{
            //    Console.WriteLine("Neither condition is true.");
            //}

            //switch sample
            //switchCondition = 2;

            //switch (switchCondition)
            //{
            //    case 1:
            //        Console.WriteLine("value is 1.");
            //        break;

            //    case 2:
            //        Console.WriteLine("value is 2");
            //        break;

            //    case 3:
            //        Console.WriteLine("value is 3");
            //        break;

            //    default:
            //        Console.WriteLine("value is " + switchCondition);
            //        break;
            //}
            #endregion

            #region Repetion Statements

            //int whileCounter = 0;
            //int doCounter = 0;

            //for loop sample
            //Console.WriteLine("for loop");
            //Console.WriteLine();

            //for (int forCounter = 0; forCounter < 10; forCounter++)
            //{
            //    Console.WriteLine("forCounter is at" + forCounter);
            //}

            //while loop sample
            //Console.WriteLine();
            //Console.WriteLine("while loop");
            //Console.WriteLine();

            //while(whileCounter < 5)
            //{
            //    Console.WriteLine("whileCounter is at " + whileCounter);
            //    whileCounter++;
            //}

            //do-while sample
            //Console.WriteLine();
            //Console.WriteLine("do-while loop");
            //Console.WriteLine();

            //do
            //{
            //    Console.WriteLine("doCounter is at " + doCounter);
            //    doCounter++;
            //} while (doCounter < 5);

            //recursion sample
            //Console.WriteLine();
            //Console.WriteLine("recursion");
            //Console.WriteLine();

            //long value = Factorial(10);
            //Console.WriteLine(value);
            #endregion

            #region methods

            //Demostrating methods
            //First method returns nothing and accepts nothing parameters
            //PrintSomething();

            //Create some variables for use in a method call
            //int first = 10;
            //int second = 2;
            //string sValue;

            //This method call will expect a single value returned
            //So the return value must be assigned to something
            //We also pass in two arguments to the method
            //int result = Sum(first, second);
            //Console.WriteLine("The sum of {0} and {1} is: {2}", first, second, result);

            //C# methods typically only return a single value
            //You can use out or ref as a way of returning multiple items from a method
            //Using out
            //ReturnMultiOut(out first, out sValue);
            //Console.WriteLine("{0}, {1}", first.ToString(), sValue);

            //Using ref requires that the variables be initialized first
            //sValue = "";
            //ReturnMultiRef(ref first, ref sValue);
            //Console.WriteLine("{0}, {1}", first.ToString(), sValue);

            //Using named parameters
            //Area(length: 30, width: 50);

            //Using optional parameters
            //OptionalParams(10, 20);

            #endregion

            #region Exception Handling

            //double a = 98, b = 0;
            //double result = 0;

            //try
            //{
            //    result = SafeDivision(a, b);
            //    Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
            //}
            //catch (DivideByZeroException e)
            //{
            //    Console.WriteLine("Attempted divide by zero.");
            //}
            #endregion

            #region Arrays
            ////Integer array of size 10
            //int[] intArray = new int[10];

            ////integer array of size 5 by initializing
            //int[] newArray = { 1, 2, 3, 4, 5 };

            //for(int counter = 0; counter < newArray.Length; counter++)
            //{
            //    Console.WriteLine(newArray[counter]);
            //}

            //create 2 dimensional array and iterate over it.
            //int[,] twoDArray = { { 3, 2 }, { 4, 5 }, { 5, 6 } };

            //for (int x = 0; x < twoDArray.GetLength(0); x++)
            //{
            //    for (int y = 0; y < twoDArray.GetLength(1); y++)
            //    {
            //        int value = twoDArray[x, y];
            //        Console.WriteLine(value.ToString());
            //    }
            //}
            #endregion
        }
 public Sugar(Coffee decoratedCoffee)
     : base(decoratedCoffee)
 {
 }