public void GetParent_success()
        {
            Warehouse hop = new Warehouse()
            {
                Code        = "AUTA05",
                Description = "This WH is awesome",
                HopType     = "Warehouse",
                NextHops    = new List <WarehouseNextHops>()
                {
                    new WarehouseNextHops()
                    {
                        HopACode = "AUTA05",
                        HopBCode = "BNDA04",
                        HopB     = new Warehouse()
                        {
                            Code = "BNDA04"
                        }
                    }
                }
            };
            Warehouse HopB = new Warehouse()
            {
                Code = "BNDA04"
            };
            string code   = _dal.Create(hop);
            Hop    parent = _dal.GetParent(HopB);

            Assert.IsNotNull(parent);
        }
Example #2
0
        public Hop GetByCoordinates(double Y, double X)
        {
            NetTopologySuite.Geometries.Point tmpPoint = new NetTopologySuite.Geometries.Point(X, Y)
            {
                SRID = 4326
            };
            Hop hop = context.Hops.OfType <Truck>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));

            if (hop == null)
            {
                hop = context.Hops.OfType <Transferwarehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                if (hop == null)
                {
                    hop = context.Hops.OfType <Warehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                }
            }
            if (hop == null)
            {
                tmpPoint = new NetTopologySuite.Geometries.Point(Y, X);
                hop      = context.Hops.OfType <Truck>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                if (hop == null)
                {
                    hop = context.Hops.OfType <Transferwarehouse>().FirstOrDefault(c => c.RegionGeoJson.Contains(tmpPoint));
                }
            }
            return(hop);
        }
 public Warehouse GetWarehouseRoot()
 {
     try
     {
         Hop child  = _dbContext.Warehouses.FirstOrDefault();
         Hop parent = null;
         do
         {
             parent = GetParent(child);
             if (parent == null)
             {
                 break;
             }
             child = parent;
         } while (parent != null);
         var root = child;
         return(_dbContext.Warehouses
                .Include(x => x.NextHops)
                .ThenInclude(x => x.HopB)
                .AsEnumerable()  //crazy shit
                .Where(x => x.Code == root.Code)
                .ToList()
                .FirstOrDefault());
     }
     catch (SqlException exc)
     {
         throw new DALException($"{exc.GetType()} Exception in {System.Reflection.MethodBase.GetCurrentMethod().Name}", exc);
     }
     catch (Exception exc)
     {
         throw new DALException($"{exc.GetType()} Exception in {System.Reflection.MethodBase.GetCurrentMethod().Name}", exc);
     }
 }
Example #4
0
        public async Task <IActionResult> Edit(Guid id, [Bind("Id,Name,Version,Alpha,Amount,Minutes,Notes,Beta")] Hop hop)
        {
            if (id != hop.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(hop);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!HopExists(hop.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(hop));
        }
        /// <summary>
        /// Will parse hops from any pagecontent with a BeerCalc recipe.
        /// </summary>
        /// <param name="content">pagecontent for a BeerCalc recipe</param>
        /// <returns></returns>
        public List <Hop> Parse(string content)
        {
            List <Hop> results = new List <Hop>();

            string        acidContent = content.Substring("acids", ");");
            List <string> acidValues  = acidContent.Substrings("\"", "\"");

            List <string> hopSelectItems = content.Substring("do_drop('hop',0", "</select>").Substrings("<option ", "</option>");

            foreach (string hopItem in hopSelectItems)
            {
                string name  = hopItem.Substring(">");
                int    value = int.Parse(hopItem.Substring("value=\"", "\""));
                if (value > 0 && !string.IsNullOrEmpty(name))
                {
                    Hop hop = new Hop();
                    hop.HopIndexValue = value;
                    hop.HopName       = name;
                    string acidValue = acidValues[value];
                    if (!string.IsNullOrEmpty(acidValue))
                    {
                        hop.Acid = double.Parse(acidValue);
                    }

                    results.Add(hop);
                }
            }

            return(results);
        }
Example #6
0
        public async Task <IActionResult> PutHop(int id, Hop hop)
        {
            if (id != hop.IngredientId)
            {
                return(BadRequest());
            }

            _context.Entry(hop).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!HopExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #7
0
        public async Task <Hop> SaveHop([FromBody] Hop postedHop)
        {
            //if (!HttpContext.User.Identity.IsAuthenticated)
            //    throw new ApiException("You have to be logged in to modify data", 401);

            if (!ModelState.IsValid)
            {
                throw new ApiException("Model binding failed.", 500);
            }

            if (!_hopRepo.Validate(postedHop))
            {
                throw new ApiException(_hopRepo.ErrorMessage, 500, _hopRepo.ValidationErrors);
            }

            // this doesn't work for updating the child entities properly
            //if(!await AlbumRepo.SaveAsync(postedAlbum))
            //    throw new ApiException(AlbumRepo.ErrorMessage, 500);

            var hop = await _hopRepo.SaveHop(postedHop);

            if (hop == null)
            {
                throw new ApiException(_hopRepo.ErrorMessage, 500);
            }

            return(hop);
        }
Example #8
0
        public async Task <Hop> SaveHop(Hop hop, string userEmail)
        {
            var db = _mongoClient.GetDatabase("BeerDb");
            var mongoCollection = db.GetCollection <HopsCollection>("Hops");
            var query           = Builders <HopsCollection> .Filter.Eq(f => f.UserEmail, userEmail);

            var hopsCollections = await mongoCollection.Find(query).ToListAsync();

            HopsCollection usersCollection = null;

            if (hopsCollections == null || hopsCollections.Count == 0)
            {
                usersCollection = CreateNewHopsCollection(userEmail, mongoCollection);
            }
            else
            {
                //should only be one collection per user
                usersCollection = hopsCollections[0];
            }
            var hopToUpdate = usersCollection.Hops.SingleOrDefault(f => f.Id == hop.Id);

            if (hopToUpdate == null)
            {
                hop.Id = Guid.NewGuid();
            }
            else
            {
                usersCollection.Hops.Remove(hopToUpdate);
            }
            usersCollection.Hops.Add(hop);
            var filter = Builders <HopsCollection> .Filter.Eq(f => f.Id, usersCollection.Id);

            mongoCollection.ReplaceOne(filter, usersCollection);
            return(hop);
        }
Example #9
0
        public void DeserializeHop_CorrectUse_WithUnderscore()
        {
            HopUse use = HopUse.Dry_Hop;

            string xml = $@"
                <HOP>
                    <NAME>Goldings, East Kent</NAME>
                    <VERSION>1</VERSION>
                    <ALPHA>5.0</ALPHA>
                    <AMOUNT>0.0638</AMOUNT>
                    <USE>{EnumUtilities.ConvertEnumToString(use)}</USE>
                    <TIME>60.0</TIME>
                    <NOTES>Great all purpose UK hop for ales, stouts, porters</NOTES>
                </HOP>";

            Mock <IStreamFactory> streamFactory = new Mock <IStreamFactory>();

            using (MemoryStream ms = CommonUtilities.GetTestXmlStream(xml))
            {
                streamFactory.Setup(f => f.GetFileStream(It.IsAny <string>(), It.IsAny <FileMode>())).Returns(ms);

                IBeerXMLSerializer s = new XDocumentBeerXMLSerializer()
                {
                    StreamFactory = streamFactory.Object
                };

                Hop hop = (Hop)s.Deserialize(It.IsAny <string>());

                Assert.AreEqual(use, hop.Use);
            }
        }
Example #10
0
        public IHttpActionResult PutHop(int id, Hop hop)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != hop.Id)
            {
                return(BadRequest());
            }

            db.Entry(hop).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!HopExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Example #11
0
    // Hop from one space to another space (probably right next to it)
    // start the hopping at the first one. will continue until hopsQueue is empty
    private void NextHop()
    {
        // Pop first hop off the queue
        if (hopsQueue.First != null)
        {
            // Get next hop out of queue
            Hop nextHop = hopsQueue.First.Value;
            hopsQueue.RemoveFirst(); // pop

            // Update UI to match one space moved
            GameManager.instance.currentTurnStats.MovementLeft -= 1;
            GameManager.instance.TextSpeedLeft.text             = GameManager.instance.currentTurnStats.MovementLeft + " Spaces";

            // Set up global variables for next hop. (Requried to be global to use InvokeRepeating to loop through the animation.)
            startPos         = GameManager.instance.spaces[nextHop.xFrom, nextHop.zFrom].gameSpace.transform.position + GameManager.instance.SPACE_HEIGHT_MOD * 2;
            endPos           = GameManager.instance.spaces[nextHop.xTo, nextHop.zTo].gameSpace.transform.position + GameManager.instance.SPACE_HEIGHT_MOD * 2;
            center           = (startPos + endPos) * 0.5f;
            center          -= new Vector3(0, 0.1f, 0); // make circular movment a bit flatter (also, this line is necessary to have the arc be along the Y plane)
            relativeStartPos = startPos - center;
            relativeEndPos   = endPos - center;
            tokenToAnimate   = gameObject;
            startTime        = Time.time;
            endTime          = startTime + HOP_ANIMATION_TIME;
            isWalking        = true;
        }
        else
        {
            GameManager.instance.SetState(GameManager.STATES.AWAITING_INPUT);
            GameManager.instance.CheckForTurnCompleted();
        }
    }
        public void GetHop_ByHopType_Failed()
        {
            string given = "Any";
            Hop    hop   = _dal.GetByHopType(given);

            Assert.Null(hop);
        }
        public void GetHop_ByCode_Failed()
        {
            string given = "DEF";
            Hop    hop   = _dal.GetByCode(given);

            Assert.Null(hop);
        }
Example #14
0
        public void Deserialized_MissingRequiredParam_IsValid_False_ErrorCode()
        {
            string xml = $@"
                <HOP>
                    <VERSION>1</VERSION>
                    <ALPHA>5.0</ALPHA>
                    <AMOUNT>0.0638</AMOUNT>
                    <USE>Dry Hop</USE>
                    <TIME>60.0</TIME>
                    <NOTES>Great all purpose UK hop for ales, stouts, porters</NOTES>
                </HOP>";

            Mock <IStreamFactory> streamFactory = new Mock <IStreamFactory>();

            using (MemoryStream ms = CommonUtilities.GetTestXmlStream(xml))
            {
                streamFactory.Setup(f => f.GetFileStream(It.IsAny <string>(), It.IsAny <FileMode>())).Returns(ms);

                XDocumentBeerXMLSerializer s = new XDocumentBeerXMLSerializer();

                s.StreamFactory = streamFactory.Object;

                Hop hop = (Hop)s.Deserialize(It.IsAny <string>());

                ValidationCode errorCode = ValidationCode.SUCCESS;
                hop.IsValid(ref errorCode);

                Assert.AreEqual(ValidationCode.MISSING_REQUIRED_PROPERTY, errorCode);
            }
        }
Example #15
0
        public ActionResult CreateHop(HopViewModel vm)
        {
            using (var context = new Models.ModelsContext())
            {
                try
                {
                    Hop newHop = new Hop();

                    newHop.Name = vm.Name;
                    newHop.Alpha = (float) vm.Alpha;
                    newHop.Beta = (float) vm.Beta;
                    newHop.Caryophyllene = (float) vm.PercentCaryophyllene;
                    newHop.Cohumulone = (float) vm.PercentCohumulone;
                    newHop.HSI = (float) vm.Stability;
                    newHop.Humulene = (float) vm.PercentHumulene;

                    context.Hops.Add(newHop);
                    context.SaveChanges();
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/Ingredients/DisplayTemplates/HopViewModel.cshtml", vm);
                    }
                    else
                    {
                        return RedirectToAction("Show", new {name = vm.Name, type = "hop"});
                    }
                }
                catch (Exception e)
                {
                    return PartialView("~/Views/Ingredients/EditorTemplates/HopViewModel.cshtml", vm);
                }
            }
        }
        public async void CreateHop_WithInvalidHop_ReturnsBadRequest()
        {
            var hop         = new Hop();
            var accessToken = AuthHelper.GetAccessToken();
            var response    = await Client.PostJsonAsync(HopBaseUrl, hop, accessToken);

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
        private async Task InsertHopMetadata(Hop hop, DbConnection connection, DbTransaction transaction)
        {
            await DeleteHopMetadata(hop.HopId, connection, transaction);

            foreach (var metadata in hop?.Metadata)
            {
                await connection.ExecuteAsync("INSERT INTO hop_metadata (hop_id, key, value) VALUES(@HopId,@Key,@Value);", new { hop.HopId, metadata.Key, metadata.Value }, transaction);
            }
        }
Example #18
0
 /// <summary>
 /// Undo all hops to restore board (the cell's peg colors) to their original state.
 /// </summary>
 protected void RestoreBoard()
 {
     while (algorithm.UndoStack.Count > 0)
     {
         Hop hop = algorithm.UndoStack.Pop();
         board.UndoHopPeg(hop);
         Application.DoEvents();
     }
 }
        private async Task InsertHopSources(Hop hop, DbConnection connection, DbTransaction transaction)
        {
            await DeleteHopSources(hop.HopId, connection, transaction);

            foreach (var source in hop?.Sources)
            {
                await connection.ExecuteAsync("INSERT INTO hop_sources (hop_id, social_id, site, url) VALUES(@HopId,@SocialId,@Site,@Url);", new { hop.HopId, source.SocialId, source.Site, source.Url }, transaction);
            }
        }
        public void CreateHop_Succeeded()
        {
            Hop hop = new Hop()
            {
                Code = "ABCDEF123"
            };
            string code = _dal.Create(hop);

            Assert.AreEqual("ABCDEF123", code);
        }
Example #21
0
        protected override IDictionary <string, string> ResolveCore(Hop hop)
        {
            var metadatas = new Dictionary <string, string>();

            foreach (var metadata in hop.Metadata)
            {
                metadatas.Add(metadata.Key, metadata.Value);
            }
            return(metadatas);
        }
Example #22
0
 public ActionResult CreateHop(Hop hop)
 {
     if (!IsContentCreator())
     {
         return(new ForbidResult());
     }
     _logger.LogInformation("Creating hop: '{name}'", hop.Name);
     _homebrewingDbService.CreateHop(hop);
     return(new OkResult());
 }
        public void CreateHop_SqlException()
        {
            Hop hop = new Hop()
            {
                Code = "ABCDEF123"
            };
            string       code = _dal.Create(hop);
            DALException ex   = Assert.Throws <DALException>(() => _dal.Create(hop));

            StringAssert.StartsWith("An item with the same key has already been added", ex.InnerException.Message);
        }
 protected override IList <string> ResolveCore(Hop hop)
 {
     if (hop.Aliases != null && hop.Aliases.Any())
     {
         return(hop.Aliases.Split(';'));
     }
     else
     {
         return(new List <string>());
     }
 }
Example #25
0
        public IHttpActionResult GetHop(int id)
        {
            Hop hop = db.Hops.Find(id);

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

            return(Ok(hop));
        }
Example #26
0
        public EditHop()
        {
            InitializeComponent();

            //load the hops varities for the dropdown and set them
            this._HopVarities = Hop.loadHopVarities();
            this._SelectedItem = this._HopVarities.Keys.First();
            hopVarityPicker.ItemsSource = this._HopVarities.Keys;

            this.DataContext = this;

            this._HopItem = PhoneApplicationService.Current.State["EditItem"] as Hop;

            float alphaAcid = this._HopItem.AlphaAcid; //otherwise will be overwritten by setting SelectedItem

            this._SelectedItem = this._HopItem.Name;
            NotifyPropertyChanged("SelectedItem");

            this._HopItem.AlphaAcid = alphaAcid;
            NotifyPropertyChanged("AlphaAcid");
            NotifyPropertyChanged("Amount");
            NotifyPropertyChanged("BoilTime");
        }