private void CarregarListaDePedidoFinalizada(long idPedido) { if (idPedido == 0) { return; } PedidoDAO pedidoDAO = new PedidoDAO(); ItemDAO itemDAO = new ItemDAO(); List <ItemDoPedido> itens = new List <ItemDoPedido>(); _pedido = pedidoDAO.GetDataById(idPedido); itens = pedidoDAO.GetAllItensDoPedido(idPedido); foreach (var i in itens) // isto foi feito só para atualziar algumas informações que devem ser atualizadas { Item item = new Item(); item = itemDAO.GetDataByID(i.IdItem); i.PrecoVenda = item.PrecoVenda; i.QuantidadeEstoque = item.Quantidade; i.Tamanho = item.Tamanho; _itensNoPedido.Add(i); } grdListaDePedidos.Refresh(); txtNumeroDoPedido.Text = _pedido.Numero.ToString(); txtObservacao.Text = _pedido.Observacao; BloquearAlteracaoNaLista(true); AtualizaValorTotal(); }
public ActionResult List() { // Início: Proteção de rota if (Session["usuario_nivel"] == null) { TempData["msg"] = "Necessário estar logado!"; TempData["msg_type"] = "warning"; return(RedirectToAction("Index", "Home")); } if (Convert.ToInt32(Session["usuario_nivel"]) > 1) { TempData["msg"] = "Você não tem autorização para acessar esta área!"; TempData["msg_type"] = "danger"; return(RedirectToAction("Index", "Home")); } // Fim: Proteção de Rota try { LocalidadeDAO.AtualizaLocalidades(); ItemCategoriaDAO.AtualizaCategorias(); ItemStatusDAO.AtualizaTiposStatus(); List <Item> lista = ItemDAO.GetAll(); TempData["lista_status"] = ItemStatusDAO.lista_status; return(View(lista)); } catch { TempData["msg"] = "Erro ao buscar dados!"; TempData["msg_type"] = "danger"; return(View()); } }
private void Item() { objItem.Id = 0; objItem.Nome = Item_tbxNome.Text; objItem.Setor = SetorDAO.findById((int)Item_cbSetor.SelectedValue); objItem.Marca = MarcaDAO.findById((int)Item_cbMarca.SelectedValue); objItem.Complemento = Item_tbxComplemento.Text; objItem.Imagem = Item_tbxImagem.Text; if (Item_tbxNome.Text != "" || Item_cbSetor.SelectedValue != null || Item_cbMarca.SelectedValue != null) { if (ItemDAO.isExists(Item_tbxNome.Text) == false) { if (controller.CadastrarItem(objItem) != null) { MessageBox.Show("Cadastro realizado de :" + objItem.Nome); Item_tbxNome.Clear(); Item_tbxComplemento.Clear(); Item_tbxImagem.Clear(); tabProduto.ForeColor = Color.Black; } } else { tabProduto.ForeColor = Color.Red; } } }
public ActionResult Details(int id) { ItemDAO itemDAO = new ItemDAO(); ItemModel item = itemDAO.FetchOne(id); return(View("Details", item)); }
public FrmItemData() { InitializeComponent(); dao = new ItemDAO(Setting.GetConnectionString()); this.dgvItemData.AutoGenerateColumns = false; }
public async Task <ActionResult> ViewLowStockItems() //PredictReorderQuantity { ItemDAO itemDAO = new ItemDAO(); List <LowStockItemViewModel> list = new List <LowStockItemViewModel>(); List <Item> ItemIdsAndThresholdValue = itemDAO.GetItemIdsAndThresholdValue(); string ids = ""; foreach (var i in ItemIdsAndThresholdValue) { if (i.ThresholdValue > itemDAO.GetBalanceByItemId(i.Id)) { ids += "'" + i.Id.ToString() + "', "; } } ids = ids.TrimEnd(',', ' '); List <Item> items = itemDAO.GetLowStockItems(ids); foreach (var row in items) { LowStockItemViewModel itemVM = new LowStockItemViewModel(); itemVM.Balance = itemDAO.GetBalanceByItemId(row.Id); itemVM.ItemList = row; //////////////////////////////// itemVM.SuggestedReorderQty = await PredictReorderQuantity(row.CategoryId); //row.CategoryId //////////////////////////////// list.Add(itemVM); } ViewData["LowStockList"] = list; return(View(list)); }
public ActionResult Delete(int id) { // Início: Proteção de rota if (Session["usuario_nivel"] == null) { TempData["msg"] = "Necessário estar logado!"; TempData["msg_type"] = "warning"; return(RedirectToAction("Index", "Home")); } if (Convert.ToInt32(Session["usuario_nivel"]) > 1) { TempData["msg"] = "Você não tem autorização para acessar esta área!"; TempData["msg_type"] = "danger"; return(RedirectToAction("Index", "Home")); } // Fim: Proteção de Rota try { if (ItemDAO.Delete(id)) { TempData["msg"] = "Atualizado com sucesso!"; TempData["msg_type"] = "success"; return(RedirectToAction("Index")); } } catch (Exception) { } TempData["msg"] = "Erro ao excluir!"; TempData["msg_type"] = "danger"; return(RedirectToAction("Index")); }
public ActionResult ViewItems() { ItemDAO itemDAO = new ItemDAO(); ViewData["Items"] = itemDAO.GetAllItemsNM(); return(View()); }
public ActionResult Details(int id) { // Início: Proteção de rota if (Session["usuario_nivel"] == null) { TempData["msg"] = "Necessário estar logado!"; TempData["msg_type"] = "warning"; return(RedirectToAction("Index", "Home")); } if (Convert.ToInt32(Session["usuario_nivel"]) > 1) { TempData["msg"] = "Você não tem autorização para acessar esta área!"; TempData["msg_type"] = "danger"; return(RedirectToAction("Index", "Home")); } // Fim: Proteção de Rota try { Item item = ItemDAO.GetByID(id); return(View("Details", item)); } catch (Exception) { TempData["msg"] = "Erro ao buscar dados!"; TempData["msg_type"] = "danger"; return(View()); } }
public void Unequip(string slot) { bool canStoreItem = !(EquipmentSlots[slot].Tags.Contains(Tags.Equipment.EmptySlot)); if (canStoreItem) { Inventory.AddItem((Item)EquipmentSlots[slot]); } switch (slot) { case Slot.MainHand: case Slot.OffHand: EquipmentSlots[slot] = ItemDAO.GenerateNewEquipmentItem(EquipmentCatalog.Hands.BareHand); if (EquipmentSlots[Slot.OffHand].IdName == EquipmentCatalog.Hands.TwoHanding) { EquipmentSlots[Slot.OffHand] = ItemDAO.GenerateNewEquipmentItem(EquipmentCatalog.Hands.BareHand); } break; case Slot.Body: EquipmentSlots[slot] = ItemDAO.GenerateNewEquipmentItem(EquipmentCatalog.Body.Naked); break; case Slot.Charm1: case Slot.Charm2: EquipmentSlots[slot] = ItemDAO.GenerateNewEquipmentItem(EquipmentCatalog.Charms.None); break; } }
public void CheckItemTrue(ModelTblTest model) { var SessionItem = Session[ListCheck]; var list = (List <ItemDAO>)SessionItem; //Them moi session if (list != null) { var item = new ItemDAO(); TestDAO tblTestModel = new TestDAO(); var TestcheckTrue = tblTestModel.ListTestTrue(model.IDTest); item.Img = "~/Assets/dist/img/yes.png"; item.TestTrue = TestcheckTrue.TestTrue; item.CountTotal = item.CountTotal + 1; list.Add(item); Session[ListCheck] = list; } else { list = new List <ItemDAO>(); var item = new ItemDAO(); TestDAO tblTestModel = new TestDAO(); var TestcheckTrue = tblTestModel.ListTestTrue(model.IDTest); item.Img = "~/Assets/dist/img/yes.png"; item.TestTrue = TestcheckTrue.TestTrue; item.CountTotal = item.CountTotal + 1; list.Add(item); Session[ListCheck] = list; } }
public IActionResult Index() { ItemDAO dao = new ItemDAO(this._appDbContext); List <Item> list = dao.GetList(new ItemFilterCriterio(), 1, 10); return(View()); }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="item"></param> /// <param name="effect"></param> /// <param name="targetId"></param> /// <param name="targetCell"></param> /// <returns></returns> public override bool ProcessItem(CharacterEntity character, ItemDAO item, GenericEffect effect, long targetId, int targetCell) { return(Process(character, new Dictionary <string, string>() { { "statsId", effect.Id.ToString() }, { "value", effect.RandomJet.ToString() } })); }
public ActionResult ViewAuctionDetails(int id, FormCollection formObj) { ItemDAO itemDAO = new ItemDAO(); if (ModelState.IsValid) { int baseQuantity = Convert.ToInt32(formObj["baseItemQuantity"]); int newItemQuantity = Convert.ToInt32(formObj["newItemQuantity"]); int newTotalItems = baseQuantity + newItemQuantity; Auction auction = new Auction(id, newTotalItems); var urlBuilder = new System.UriBuilder(); if (id > 0) { try { //Update Item Quantity auctionDAO.Update(auction); urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Action("ViewAuctionDetails", "Auction"), Query = "id=" + id, }; } catch (Exception ex) { return(View("Update Item Quantity Error! ", new HandleErrorInfo(ex, "Item", "AddItem"))); } } Uri uri = urlBuilder.Uri; return(Redirect(uri.AbsoluteUri)); } return(View()); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { listCombo = ItemDAO.getAllCombo(); listItems = ItemDAO.getListItems(); //foreach (Items it in listItems) //{ // discount = ((it.Money * 10) / 100) + it.Money; //} //int num = Convert.ToInt32(txtNumber.Value); foreach (Combo it in listCombo) { foreach (Items di in listItems) { if (it.ID == di.Combox.ID) { discount = ItemDAO.getPriceByID(it.ID); } } } foreach (Combo combo in listCombo) { if (Convert.ToInt32(num.Value) > 0) { total += discount * Convert.ToInt32(num.Value); } } } }
partial void addButtonPressed(UIButton sender) { var tabBarItems = TabBarController.TabBar.Items; if (obj.allDistanceNotZero()) { switch (SegmentChoiceTypeObject.SelectedSegment) { case 0: Item item = new Item(obj); ItemDAO itemDAO = new ItemDAO(); itemDAO.insertItem(item); addBadgeTabBarItem(tabBarItems, 1); break; case 1: Box box = new Box(obj); BoxDAO boxDAO = new BoxDAO(); boxDAO.insertBox(box); addBadgeTabBarItem(tabBarItems, 2); break; default: break; } } else { alert("Non è possibile aggiungere l'oggetto", "Una delle dimensioni è uguale a 0"); } }
public ActionResult EditItem() { string name = Request["Name"]; string des = Request["Des"]; string detai = Request["Detail"]; int pold = Convert.ToInt32(Request["pold"]); int pnew = Convert.ToInt32(Request["pnew"]); int q = Convert.ToInt32(Request["quan"]); int rat = Convert.ToInt32(Request["rat"]); int Id = Convert.ToInt32(Request["Id"]); var fileName = ""; if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { fileName = System.IO.Path.GetFileName(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/Content/images/"), fileName); file.SaveAs(path); } } ItemDTO i = new ItemDTO(Id, "", name, des, detai, fileName.ToString(), "", "", pold, pnew, q, rat); ItemDAO.updateItem(i); List <ItemDTO> model1 = ItemDAO.getAllItems(); return(View("Tables", model1)); }
public ActionResult Edit(int id) { ItemDAO itemDAO = new ItemDAO(); ItemModel item = itemDAO.FetchOne(id); return(View("ItemForm", item)); }
public ActionResult UpdateViaJS() { // Início: Proteção de rota if (Session["usuario_nivel"] == null) { TempData["msg"] = "Necessário estar logado!"; TempData["msg_type"] = "warning"; return(RedirectToAction("Index", "Home")); } // Fim: Proteção de Rota Localidade local = LocalidadeDAO.GetByID(Convert.ToInt32(Request["localidade_id"])); try { ItemStatusDAO.AtualizaTiposStatus(); TempData["localidade"] = LocalidadeDAO.GetByID(local.ID); TempData["itens"] = ItemDAO.GetByLocalidade(local.ID); TempData["todos_itens"] = ItemDAO.GetAll(); TempData["lista_status"] = ItemStatusDAO.lista_status; return(View("Update")); } catch (Exception) { TempData["msg"] = "Ocorreu um erro!"; TempData["msg_type"] = "danger"; return(RedirectToAction("Index", "Home")); } }
public HomeController() { this.connectionString = ConfigurationManager.ConnectionStrings["dataSource"].ConnectionString; this.logPath = Path.Combine(Path.GetDirectoryName(System.Web.HttpContext.Current.Server.MapPath("~")), ConfigurationManager.AppSettings["relative"]); linkDAO = new EnemyItemDAO(connectionString, logPath); iDAO = new ItemDAO(connectionString, logPath); }
public void CheckEquipReq() { // create a training dummy TrainingDummy Dummy = new TrainingDummy(100, 0, 0); // knight should be able to use double slash try { Guinevere.Skillbar.Skills[0].Use(Dummy); Assert.IsTrue(true, "Knight should use the skill successfully."); } catch (SkillReqsNotMetException) { Assert.IsFalse(true, "Knight should meet skill requirements."); } // replace the knight's sword with a book and 2H it (lol) Guinevere.Inventory.AddItem(ItemDAO.CreateNewEquipmentItem("History Tome")); Guinevere.Equipment.Equip("MainHand", "History Tome"); Guinevere.Equipment.Toggle2H(); // try to use double slash, should fail because the book doesn't have a "sword" tag try { Guinevere.Skillbar.Skills[0].Use(Dummy); Assert.IsFalse(true, "Book should not meet the skill's Sword requirement."); } catch (SkillReqsNotMetException) { Assert.IsTrue(true, "Book should not meet the skill's Sword requirement."); } }
public ActionResult BuyItem(int itemId) { int characterId = Convert.ToInt32(SessionManager.GetCharacterId()); Character character = CharacterDAO.GetAllInformations(characterId); Item itemToBuy = ItemDAO.Get(itemId); if (character.Coins < itemToBuy.Price || character.Level < itemToBuy.RequiredLevel) { FlashMessage.Danger("Erro: ", "Você não possuí moedas suficientes para realizar a compra ou não tem level suficiente para adquirir o item"); return(RedirectToAction("Market", "Home", null)); } foreach (var itemInBag in character.Bag.ItemsInBag) { if (itemInBag.Item == null) { character.Coins -= itemToBuy.Price; itemInBag.Item = itemToBuy; CharacterDAO.Update(character); return(RedirectToAction("Index", "Home", null)); } } FlashMessage.Danger("Erro: ", "Você não possuí slots vazios na mochila para armazenar o item"); return(RedirectToAction("Market", "Home", null)); }
public FrmReportStock() { InitializeComponent(); _itmDAO = new ItemDAO(Setting.GetConnectionString()); _transDAO = new TransactionDAO(Setting.GetConnectionString()); }
public BoxViewController(IntPtr handle) : base(handle) { boxDAO = new BoxDAO(); itemDAO = new ItemDAO(); BoxViewDelegate = new BoxViewDelegate(this); boxImage = UIImage.FromBundle("box_image.png"); }
public ActionResult DetailsItem(string itemid) { ItemDAO itemDAO = new ItemDAO(); ViewData["itemid"] = itemid; ViewData["itemDetails"] = itemDAO.GetItemByIdNM(itemid); return(View()); }
public void BeforeEachTest() { //create DAOs items = new ItemDAO(); users = new UserDAO(); comments = new CommentDAO(); categories = new CategoryDAO(); }
public StatsController() { this.connectionString = ConfigurationManager.ConnectionStrings["dataSource"].ConnectionString; this.logPath = ConfigurationManager.AppSettings["relative"]; linkDAO = new EnemyItemDAO(connectionString, logPath); iDAO = new ItemDAO(connectionString, logPath); eDAO = new EnemyDAO(connectionString, logPath); }
public void CharacterOverburdened() { Character Guinevere = new Character("Guinevere", new Knight("F")); Guinevere.Inventory.AddItem(ItemDAO.CreateNewEquipmentItem("Plate Armor"), 5); Assert.IsTrue(Guinevere.Inventory.IsOverburdened, "Character should be overburdened when Weight > Weight Capacity."); }
public EmployeeController() { _employeeDAO = new EmployeeDAO(); _requisitionDAO = new RequisitionDAO(); _requisitionItemDAO = new RequisitionItemDAO(); _notificationChannelDAO = new NotificationChannelDAO(); _itemDAO = new ItemDAO(); }
public void CharacterRemovesItem() { Assert.IsTrue(Guinevere.Inventory.Contains("Memento"), "Knights should start with a Memento in their inventories."); Guinevere.Inventory.RemoveItem(ItemDAO.CreateNewItem("Memento")); Assert.IsFalse(Guinevere.Inventory.Contains("Memento"), "The Memento should be removed."); }
public ItemController(ItemDAO itemDAO, KeyValueModelBinder binder, CategoryHierarchyService categoryHierarchyService) { if (itemDAO == null) throw new ArgumentNullException("itemDAO"); if (binder == null) throw new ArgumentNullException("binder"); if (categoryHierarchyService == null) throw new ArgumentNullException("categoryHierarchyService"); _itemDAO = itemDAO; _binder = binder; _categoryHierarchyService = categoryHierarchyService; }
public virtual void Can_Load_Item_And_Compare_Monetary_Amount() { InitData(); ItemDAO itemDAO = new ItemDAO(); long tempAux = auctionOne.Id; Item a1 = itemDAO.GetById(tempAux); Assert.AreEqual(a1.InitialPrice, new MonetaryAmount(1.99, "USD")); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="merge"></param> /// <returns></returns> public bool AddItem(ItemDAO item, bool merge = true) { if (Items.Contains(item)) return false; if (merge) if (TryMerge(item)) return true; Items.Add(item); OnItemAdded(item); OnOwnerChange(item); return false; }
public void AuditLogInterceptor_Records_Log_Entry_When_Item_Persisted() { // Save a user without audit logging UserDAO userDAO = new UserDAO(); User seller = new User("Christian", "Bauer", "turin", "abc123", "*****@*****.**"); userDAO.MakePersistent(seller); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); // Enable interceptor AuditLogInterceptor interceptor = new AuditLogInterceptor(); NHibernateHelper.RegisterInterceptor(interceptor); interceptor.Session = NHibernateHelper.Session; interceptor.UserId = seller.Id; // Save an item with audit logging enabled Item item = new Item( "Warfdale Nearfield Monitors", "Pair of 150W nearfield monitors for the home studio.", seller, new MonetaryAmount(1.99, "USD"), new MonetaryAmount(50.33, "USD"), DateTime.Now, DateTime.Now.AddDays(1) ); ItemDAO itemDAO = new ItemDAO(); itemDAO.MakePersistent(item); // Synchronize state to trigger interceptor NHibernateHelper.Session.Flush(); // Check audit log IQuery findAuditLogRecord = NHibernateHelper.Session.CreateQuery("from AuditLogRecord record where record.EntityId = :id"); findAuditLogRecord.SetParameter("id", item.Id); AuditLogRecord foundRecord = findAuditLogRecord.UniqueResult<AuditLogRecord>(); Assert.IsNotNull(foundRecord); Assert.AreEqual(foundRecord.UserId, seller.Id); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); // Deregister interceptor NHibernateHelper.RegisterInterceptor(null); }
/// <summary> Create test data for our domain model. /// /// </summary> /// <throws> Exception </throws> protected internal virtual void InitData() { CreateDatabase(); // Prepare DAOS CategoryDAO catDAO = new CategoryDAO(); UserDAO userDAO = new UserDAO(); ItemDAO itemDAO = new ItemDAO(); CommentDAO commentDAO = new CommentDAO(); // Categories cars = new Category("Cars"); carsLuxury = new Category("Luxury Cars"); cars.AddChildCategory(carsLuxury); carsSUV = new Category("SUVs"); cars.AddChildCategory(carsSUV); catDAO.MakePersistent(cars); // Users u1 = new User("Christian", "Bauer", "turin", "abc123", "*****@*****.**"); u1.HomeAddress = new Address("Foo", "12345", "Bar"); u1.IsAdmin = true; u2 = new User("Gavin", "King", "gavin", "abc123", "*****@*****.**"); u2.HomeAddress = new Address("Foo", "12345", "Bar"); u3 = new User("Max", "Andersen", "max", "abc123", "*****@*****.**"); u3.HomeAddress = new Address("Foo", "12345", "Bar"); userDAO.MakePersistent(u1); userDAO.MakePersistent(u2); userDAO.MakePersistent(u3); // BillingDetails BillingDetails ccOne = new CreditCard( "Christian Bauer", u1, "1234567890", CreditCardType.MasterCard, "10", "2005"); BillingDetails accOne = new BankAccount( "Christian Bauer", u1, "234234234234", "FooBar Rich Bank", "foobar123foobaz"); u1.AddBillingDetails(ccOne); u1.AddBillingDetails(accOne); // Items DateTime tempAux = DateTime.Now; DateTime tempAux2 = DateTime.Now.AddDays(3);// inThreeDays auctionOne = new Item("Item One", "An item in the carsLuxury category.", u2, new MonetaryAmount(1.99, "USD"), new MonetaryAmount(50.33, "USD"), tempAux, tempAux2); auctionOne.SetPendingForApproval(); auctionOne.Approve(u1); itemDAO.MakePersistent(auctionOne); new CategorizedItem(u1.Username, carsLuxury, auctionOne); DateTime tempAux3 = DateTime.Now; DateTime tempAux4 = DateTime.Now.AddDays(5); // inFiveDays auctionTwo = new Item("Item Two", "Another item in the carsLuxury category.", u2, new MonetaryAmount(2.22, "USD"), new MonetaryAmount(100.88, "USD"), tempAux3, tempAux4); itemDAO.MakePersistent(auctionTwo); new CategorizedItem(u1.Username, carsLuxury, auctionTwo); DateTime tempAux5 = DateTime.Now; DateTime tempAux6 = DateTime.Now.AddDays(3);// inThreeDays auctionThree = new Item("Item Three", "Don't drive SUVs.", u2, new MonetaryAmount(3.11, "USD"), new MonetaryAmount(300.55, "USD"), tempAux5, tempAux6); itemDAO.MakePersistent(auctionThree); new CategorizedItem(u1.Username, carsSUV, auctionThree); DateTime tempAux7 = DateTime.Now; DateTime tempAux8 = DateTime.Now.AddDays(7);// nextWeek auctionFour = new Item("Item Four", "Really, not even luxury SUVs.", u1, new MonetaryAmount(4.55, "USD"), new MonetaryAmount(40.99, "USD"), tempAux7, tempAux8); itemDAO.MakePersistent(auctionFour); new CategorizedItem(u1.Username, carsLuxury, auctionFour); new CategorizedItem(u1.Username, carsSUV, auctionFour); // Bids Model.Bid bidOne1 = new Model.Bid(new MonetaryAmount(12.12, "USD"), auctionOne, u3); Model.Bid bidOne2 = new Model.Bid(new MonetaryAmount(13.13, "USD"), auctionOne, u1); Model.Bid bidOne3 = new Model.Bid(new MonetaryAmount(14.14, "USD"), auctionOne, u3); auctionOne.AddBid(bidOne1); auctionOne.AddBid(bidOne2); auctionOne.AddBid(bidOne3); // Successful Bid auctionOne.SuccessfulBid = bidOne3; // Comments Comment commentOne = new Comment(Rating.Excellent, "This is Excellent.", u3, auctionOne); Comment commentTwo = new Comment(Rating.Low, "This is very Low.", u1, auctionThree); commentDAO.MakePersistent(commentOne); commentDAO.MakePersistent(commentTwo); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public bool IsValidForThisCategory(ItemDAO item) { AuctionEntry auction = FirstOrDefault(); if (auction == null) throw new InvalidOperationException("AuctionCategory::IsValidForThisCategory empty category, should not happend."); return auction.Item.StringEffects == item.StringEffects; }
public void SetUpData() { //create database CreateDatabase(); //create common test data tobin = CreateTobin(); iMac = CreateAppleiMac(tobin); //save them using DAOs items = new ItemDAO(); users = new UserDAO(); users.MakePersistent(tobin); items.MakePersistent(iMac); //commit NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); }
/// <summary> /// /// </summary> /// <param name="item"></param> public override void OnOwnerChange(ItemDAO item) { item.OwnerId = OwnerId; item.OwnerType = OwnerType; }
public virtual void Can_Place_Bid_For_Item() { InitData(); ItemDAO itemDAO = new ItemDAO(); UserDAO userDAO = new UserDAO(); long tempAux = auctionTwo.Id; Bid currentMaxBid = itemDAO.GetMaxBid(tempAux); long tempAux2 = auctionTwo.Id; Bid currentMinBid = itemDAO.GetMinBid(tempAux2); long tempAux3 = auctionTwo.Id; Item a2 = itemDAO.GetById(tempAux3, true); // Fail, auction is not active yet try { double bidAmount = 99.99; MonetaryAmount newAmount = new MonetaryAmount(bidAmount, "USD"); long tempAux4 = u3.Id; a2.PlaceBid(userDAO.GetById(tempAux4), newAmount, currentMaxBid, currentMinBid); } catch(BusinessException success) { } // Fail, user isn't an admin try { a2.Approve(u3); } catch(PermissionException success) { } // Success, set active a2.SetPendingForApproval(); a2.Approve(u1); // Success, place a bid try { double bidAmount = 100.00; MonetaryAmount newAmount = new MonetaryAmount(bidAmount, "USD"); long tempAux5 = u3.Id; a2.PlaceBid(userDAO.GetById(tempAux5), newAmount, currentMaxBid, currentMinBid); } catch(BusinessException failure) { throw failure; } // Fail, bid amount is too low try { double bidAmount = 99.99; MonetaryAmount newAmount = new MonetaryAmount(bidAmount, "USD"); long tempAux6 = u3.Id; a2.PlaceBid(userDAO.GetById(tempAux6), newAmount, currentMaxBid, currentMinBid); } catch(BusinessException success) { } NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public bool TryMerge(ItemDAO item) { var sameItem = Items.Find( entry => entry.TemplateId == item.TemplateId && entry.StringEffects == item.StringEffects && entry.Id != item.Id && entry.SlotId == item.SlotId && !ItemDAO.IsEquipedSlot(entry.Slot)); if(sameItem != null) { sameItem.Quantity += item.Quantity; OnItemQuantity(sameItem.Id, sameItem.Quantity); return true; } return false; }
/// <summary> /// /// </summary> /// <param name="item"></param> public void AddSet(ItemDAO item) { if (item.Template.SetId == 0 || item.Template.Set == null) return; var set = item.Template.Set; if (!m_equippedSets.ContainsKey(set.Id)) m_equippedSets.Add(set.Id, 0); var count = ++m_equippedSets[set.Id]; if (count > 0) { Entity.Statistics.UnMerge(Stats.StatsType.TYPE_ITEM, set.GetStats(count - 1)); Entity.Statistics.Merge(Stats.StatsType.TYPE_ITEM, set.GetStats(count)); } }
/// <summary> /// /// </summary> public void RemoveSet(ItemDAO item) { if (item.Template.SetId == 0 || item.Template.Set == null) return; var set = item.Template.Set; var count = --m_equippedSets[set.Id]; if (count > 0) { Entity.Statistics.Merge(Stats.StatsType.TYPE_ITEM, set.GetStats(count)); Entity.Statistics.UnMerge(Stats.StatsType.TYPE_ITEM, set.GetStats(count + 1)); } }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="slot"></param> /// <param name="quantity"></param> public void MoveItem(ItemDAO item, ItemSlotEnum slot, int quantity = 1) { if (slot == item.Slot) return; if (quantity > item.Quantity || quantity < 1) quantity = item.Quantity; if (item.IsEquiped && !ItemDAO.IsEquipedSlot(slot)) { if (item.IsBoostEquiped) Entity.Statistics.UnMerge(StatsType.TYPE_BOOST, item.Statistics); else Entity.Statistics.UnMerge(StatsType.TYPE_ITEM, item.Statistics); if (item.Slot == ItemSlotEnum.SLOT_WEAPON) { Entity.Dispatch(WorldMessage.JOB_TOOL_EQUIPPED()); } item.SlotId = (int)slot; m_entityLookRefresh = true; bool merged = AddItem(MoveQuantity(item, 1)); RemoveSet(item); // send new stats if (Entity.Type == EntityTypeEnum.TYPE_CHARACTER) { Entity.MovementHandler.Dispatch(WorldMessage.ENTITY_OBJECT_ACTUALIZE(Entity)); CachedBuffer = true; if (!merged) Dispatch(WorldMessage.OBJECT_MOVE_SUCCESS(item.Id, item.SlotId)); Dispatch(WorldMessage.ACCOUNT_STATS((CharacterEntity)Entity)); if (item.Template.SetId != 0) Dispatch(WorldMessage.ITEM_SET(item.Template.Set, Items.Where(entry => entry.Template.SetId == item.Template.SetId && entry.IsEquiped))); CachedBuffer = false; } return; } else if (!item.IsEquiped && ItemDAO.IsEquipedSlot(slot)) { if (!ItemTemplateDAO.CanPlaceInSlot((ItemTypeEnum)item.Template.Type, slot)) { base.Dispatch(WorldMessage.OBJECT_MOVE_ERROR()); return; } // level required if (Entity.Level < item.Template.Level) { base.Dispatch(WorldMessage.OBJECT_MOVE_ERROR_REQUIRED_LEVEL()); return; } // Already equiped template if (HasTemplateEquiped(item.TemplateId)) { base.Dispatch(WorldMessage.OBJECT_MOVE_ERROR_ALREADY_EQUIPED()); return; } if (Entity.Type == EntityTypeEnum.TYPE_CHARACTER) { if (!item.SatisfyConditions((CharacterEntity)Entity)) { base.Dispatch(WorldMessage.INFORMATION_MESSAGE(InformationTypeEnum.ERROR, InformationEnum.ERROR_CONDITIONS_UNSATISFIED)); return; } } var equipedItem = Items.Find(entry => entry.SlotId == (int)slot && entry.Id != item.Id); // already equiped in slot ? remove it if (equipedItem != null) { MoveItem(equipedItem, ItemSlotEnum.SLOT_INVENTORY); } m_entityLookRefresh = true; var newItem = MoveQuantity(item, 1); newItem.SlotId = (int)slot; AddItem(newItem, false); AddSet(newItem); if (item.IsBoostEquiped) Entity.Statistics.Merge(StatsType.TYPE_BOOST, item.Statistics); else Entity.Statistics.Merge(StatsType.TYPE_ITEM, item.Statistics); // send new stats if (Entity.Type == EntityTypeEnum.TYPE_CHARACTER) { Entity.MovementHandler.Dispatch(WorldMessage.ENTITY_OBJECT_ACTUALIZE(Entity)); base.CachedBuffer = true; Entity.MovementHandler.Dispatch(WorldMessage.ENTITY_OBJECT_ACTUALIZE(Entity)); base.Dispatch(WorldMessage.ACCOUNT_STATS((CharacterEntity)Entity)); if(item.Template.SetId != 0) base.Dispatch(WorldMessage.ITEM_SET(item.Template.Set, Items.Where(entry => entry.Template.SetId == item.Template.SetId && entry.IsEquiped))); if (newItem.Slot == ItemSlotEnum.SLOT_WEAPON) { var character = (CharacterEntity)Entity; character.CharacterJobs.ToolEquipped(item.TemplateId); } base.CachedBuffer = false; } } else { var newItem = MoveQuantity(item, quantity); newItem.SlotId = (int)slot; if(!AddItem(newItem, false)) base.Dispatch(WorldMessage.OBJECT_MOVE_SUCCESS(item.Id, item.SlotId)); } }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="quantity"></param> /// <param name="slot"></param> /// <returns></returns> public ItemDAO MoveQuantity(ItemDAO item, int quantity, ItemSlotEnum slot = ItemSlotEnum.SLOT_INVENTORY) { if(quantity >= item.Quantity) return RemoveItem(item.Id, item.Quantity); item.Quantity -= quantity; OnItemQuantity(item.Id, item.Quantity); return item.Clone(quantity); }
/// <summary> /// /// </summary> /// <param name="item"></param> public virtual void OnItemAdded(ItemDAO item) { }
/// <summary> /// /// </summary> /// <param name="fighter"></param> /// <param name="cellId"></param> /// <returns></returns> public bool CanUseWeapon(AbstractFighter fighter, ItemDAO weapon, int cellId) { var template = weapon.Template; if (LoopState != FightLoopStateEnum.STATE_WAIT_TURN) { Logger.Debug("Fight::CanUseWeapon trying to cast spell withouth being in turn wait phase : " + fighter.Name); return false; } if (CurrentFighter != fighter) { Logger.Debug("Fight::CanUseWeapon fighter try to use weapon but its not his turn : " + fighter.Name); return false; } if (GetCell(cellId) == null) { Logger.Debug("Fight::CanUseWeapon null cast cell : " + fighter.Name); return false; } if (fighter.AP < template.APCost) { Logger.Debug("Fight::CanUseWeapon not enought AP : " + fighter.Name); return false; } var distance = Pathfinding.GoalDistance(Map, fighter.Cell.Id, cellId); var poMax = template.POMax + fighter.Statistics.GetTotal(EffectEnum.AddPO); if (poMax - template.POMin < 1) poMax = template.POMin; if (distance > poMax || distance < template.POMin) { Logger.Debug("Fight::CanUseWeapon target cell not in range : " + fighter.Name); return false; } return true; }
/// <summary> /// /// </summary> /// <param name="item"></param> public override void OnItemAdded(ItemDAO item) { Dispatch(WorldMessage.OBJECT_ADD_SUCCESS(item)); }
/// <summary> /// /// </summary> /// <param name="item"></param> public override void OnItemAdded(ItemDAO item) { Dispatch(WorldMessage.EXCHANGE_STORAGE_MOVEMENT(ExchangeMoveEnum.MOVE_OBJECT, OperatorEnum.OPERATOR_ADD, item.ToExchangeString())); }
/// <summary> /// /// </summary> /// <param name="item"></param> public virtual void OnOwnerChange(ItemDAO item) { }