예제 #1
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="deal"></param>
 /// <param name="secondExtremum">DEBUG</param>
 /// <param name="firstLongExtremums">DEBUG</param>
 /// <param name="firstShortExtremums">DEBUG</param>
 public DealEvent(Deal deal, Extremum secondExtremum = null, IReadOnlyList<Extremum> firstLongExtremums = null, IReadOnlyList<Extremum> firstShortExtremums = null)
 {
     FirstShortExtremums = firstShortExtremums;
     FirstLongExtremums = firstLongExtremums;
     SecondExtremum = secondExtremum;
     Deal = deal;
 }
예제 #2
0
        // non-static methods
        public bool addDeal(Deal deal)
        {
            bool result = true;

            // if it's an unfair client we deny his request
            if (unFairContractors.Find(contr => contr.name == deal.contractor.name) != default(Contractor))
            {
                result = false;
            }
            // if it's an established customer
            else if (regularContractors.Find(contr => contr.name == deal.contractor.name) != default(Contractor))
            {
                Random rand = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
                // probability of checking our established customers is 20 %
                if (rand.Next(1, 5) % 5 == 0)
                {
                    result = processDeal(deal);
                }
            }
            // if it's a new customer we check him anyway
            else
            {
                result = processDeal(deal);
            }

            return result;
        }
예제 #3
0
        private async void SaveDeal_Click(object sender, RoutedEventArgs e)
        {
            var deal = new Deal(Guid.NewGuid().ToString("N"));
            deal.IssuerName = "Fake Wein Club";
            deal.IsUsed = false;
            deal.MerchantName = "Fake Wein Club";
            deal.TermsAndConditions = "Pro Tag und Person ist ein Deal einlösbar.";
            deal.ExpirationDate = DateTime.Now.AddDays(14);
            deal.DisplayName = "10€ Nachlass";
            deal.Description = "Sie erhalten auf Ihren nächsten Einkauf 10€ erlassen.";
            deal.Code = "QRNachlass10";

            var qrCode = new BitmapImage();
            using (Stream logoStream = Application.GetResourceStream(new Uri("Assets/QRNachlass.png", UriKind.Relative)).Stream)
            {
                qrCode.SetSource(logoStream);
            }
            deal.BarcodeImage = qrCode;

            try
            {
                SystemTray.ProgressIndicator.IsVisible = true;
                await deal.SaveAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Es gab ein Problem beim Speichern: " + ex.Message);
            }
            finally
            {
                SystemTray.ProgressIndicator.IsVisible = false;
            }

            LoadDealsFromWallet();
        }
 //
 // GET: /deal/Create
 public ActionResult Create()
 {
     Deal p = new Deal();
     p.CreatedDate = DateTime.Now;
     ViewBag.ProviderID = new SelectList(db.Providers, "ProviderID", "Name");
     ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "Name");
     return View(p);
 }
예제 #5
0
        public void ProcessAction(CreateNewDealCommand eventObject)
        {
            var newDeal = new Deal();
            newDeal.Name = eventObject.DealName;

            this.dealRepository.Save(newDeal);

            this.eventBroker.Publish(new DealCreatedEvent(newDeal.Id), Topics.EVENTS);
        }
예제 #6
0
 private async void Button_Click_2(object sender, RoutedEventArgs e)
 {
     Deal deal = new Deal("deal1");
     deal.MerchantName = "某某公司";
     deal.DisplayName = "某某优惠卡";
     deal.IsUsed = false;
     await deal.SaveAsync();
     MessageBox.Show("添加优惠券信息成功");
 }
예제 #7
0
 internal DealView(Deal deal, PlayerBase beholder)
 {
     PlayerList = deal
         .Players
         .Select(p => new PlayerView(p, beholder))
         .ToList();
     AreHeartsBroken = deal.AreHeartsBroken;
     IsOver = deal.IsOver;
 }
        private async void btnAdicionar_Click(object sender, RoutedEventArgs e)
        {
            Conversao conv = new Conversao();

            if (chkOferta1.IsEnabled && (bool)chkOferta1.IsChecked)
            {

                Deal deal = new Deal(chkOferta1.Content.ToString());


                deal.MerchantName = "Grupo 1";
                deal.DisplayName = "Cupom 30%";
                deal.Description = "Cupom especial com 30% de desconto";
                
                deal.Logo159x159 = Conversao.GetBitmapImage("/Images/logo_159x159.png");
               // deal.BarcodeImage = GetBitmapImage("/Images/Barcode.png");

                deal.Logo336x336 = Conversao.GetBitmapImage("/Images/Barcode.png");
               // deal.Logo99x99 = GetBitmapImage("/Images/logo_159x159.png");
               
                deal.ExpirationDate = DateTime.Now.AddDays(30);
                deal.StartDate = DateTime.Now;
                deal.TermsAndConditions = "Pode ser utilizado quando quiser.";
                
                                

                await deal.SaveAsync();

                chkOferta1.IsEnabled = false;

            }

            if (chkOferta2.IsEnabled && (bool)chkOferta2.IsChecked)
            {
                Deal deal = new Deal(chkOferta2.Content.ToString());
                deal.MerchantName = "Grupo 1";
                deal.DisplayName = "Cupom 40%";
                deal.Description = "Cupom especial com 40% de desconto";

                await deal.SaveAsync();

                chkOferta2.IsEnabled = false;
            }

            if (chkOferta3.IsEnabled && (bool)chkOferta3.IsChecked)
            {
                Deal deal = new Deal(chkOferta3.Content.ToString());
                deal.MerchantName = chkOferta3.Content.ToString();
                deal.DisplayName = chkOferta3.Content.ToString();
                await deal.SaveAsync();

                chkOferta3.IsEnabled = false;
            }

            await Launcher.LaunchUriAsync(new Uri("wallet://", UriKind.RelativeOrAbsolute));
        }
예제 #9
0
        public PromotionInstance(Account sender, Account recipient, Promotion ev, Deal deal, string message)
        {
            this.Sender = sender;

            this.Promotion = ev;
            this.Deal = deal;
            this.Recipient = recipient;
            this.Message = message;
            this.CreateDateTime = DateTime.UtcNow;
            // by default response is null
            this.Status = new PromotionInstanceStatus();
        }
예제 #10
0
        public ActionResult Create(Deal deal)
        {
            if (ModelState.IsValid)
            {
                db.Deals.Add(deal);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ProviderID = new SelectList(db.Providers, "ProviderID", "Name", deal.ProviderID);
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "Name");
            return View(deal);
        }
예제 #11
0
 public static Deal GetDeal(string description, int available)
 {
     var d = new Deal()
     {
         Available = available,
         Taken = 0,
         DealValue = 5,
         Description = "description",
         EndDateTime = DateTime.Now.AddDays(5),
         StartDateTime = DateTime.Now,
     };
     return d;
 }
예제 #12
0
        public ActionResult Create(Deal deal)
        {
            if (ModelState.IsValid)
            {
                deal.DealID = Guid.NewGuid();
                db.Deals.Add(deal);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.BuyerID = new SelectList(db.Contacts, "ContactID", "FirstName", deal.BuyerID);
            ViewBag.DealDealershipID = new SelectList(db.Dealerships, "DealershipID", "Name", deal.DealDealershipID);
            return View(deal);
        }
예제 #13
0
        public DealViewModel(Deal deal)
        {
            Id = deal.Id.ToString();
            ShortTitle = deal.ShortTitle;
            ShortDescription = deal.ShortDescription;
            RegularPrice = deal.RegularPrice;
            SpecialPrice = deal.SpecialPrice;
            CanonicalUrl = deal.CanonicalUrl;
            EndTime = deal.EndTime;

            ImageUrls = deal.Pictures.Select(p => p.RelativeUrl).ToList();
            DealOptions = deal.DealOptions.Select(d => new DealOptionViewModel(d)).ToList();
            Pictures = deal.Pictures.Select(d => new DealImageViewModel(d)).ToList();
            Thumbnails = deal.Pictures.Select(d => new DealThumbnailViewModel(d)).ToList();
        }
예제 #14
0
        public ActionResult Create(DealViewModel viewModel)
        {
            if (viewModel != null && this.ModelState.IsValid)
            {
                Deal deal = new Deal()
                {
                    Name = this.sanitizer.Sanitize(viewModel.Name),
                    ClientId = this.User.Identity.GetUserId(),
                    Value = viewModel.Value
                };

                this.deals.Create(deal);
                this.deals.SaveChanges();
            }

            return this.RedirectToAction("Index", "Home", new { area = "Deals" });
        }
예제 #15
0
		protected override async void OnNavigatedTo(NavigationEventArgs e)
		{
			var dealPar = (DealsInCategoryViewModel)e.Parameter;

			pageTitle.Text = dealPar.Title;

			thisDeal = await DealData.GetDealAsync(dealPar.DealId);
			var dealImages = await DealImageData.GetDealImagesAsync(thisDeal.DealId, "250x250");

			imageGrid.ItemsSource = dealImages;

			title.Text = thisDeal.Title;
			description.Text = thisDeal.Description;
			tblPrice.Text = string.Format("{0:C}", thisDeal.Price);

			tbBeginDeal.Text = string.Format("{0:d MMM}", thisDeal.BeginDeal) + " - " + string.Format("{0:d MMM}", thisDeal.EndDeal);
		}
예제 #16
0
        // non-static methods
        // checks given deal. this method is just abstraction
        public bool checkDeal(Deal dealToCheck)
        {
            bool isDealFair;

            // we get fairness of the deal
            dealToCheck.GetFairness(this, out isDealFair);

            Random rand = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);

            // auditor makes a mistake in 2 % of cases
            if (rand.Next(1, 20) % 10 == 0)
            {
                isDealFair = !isDealFair;
            }

            return isDealFair;
        }
예제 #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int dealID = Convert.ToInt16( Request.QueryString["dealID"]);

        selectedDeal = DealsController.getDealByDealID(dealID);

        TimeSpan time = (selectedDeal.ExpiresOn).Subtract(DateTime.Now);

        string format = "HH mm ss";

        Label1.Text = new DateTime((long)time.Ticks).ToString(format);

        List<Deal> list = new List<Deal>();
        list.Add(selectedDeal);

        Repeater1.DataSource = list;
        Repeater1.DataBind();
    }
예제 #18
0
        /// <summary>
        /// GET comments
        /// </summary>
        /// <returns>Action</returns>
        public ActionResult Comment()
        {
            int dealId = int.Parse(RouteData.Values["DealID"].ToString());

            IList<Comment> comments = new List<Comment>();
            Deal deal = new Deal();

            try
            {
                comments = commentDataAccess.GetDealComments(dealId);
                deal = dealDataAccess.GetDeal(dealId);
            }
            catch (DealDatabaseException)
            {
                log.Warn("Could not get deal from database when loading comments");
            }
            catch (CommentDatabaseException)
            {
                log.Warn("Could not get comments from database");
            }

            Dictionary<User, Comment> userComments = new Dictionary<User, Comment>();

            foreach (Comment comment in comments)
            {
                try
                {
                    userComments[memberDataAccess.GetUser(comment.UserName)] = comment;
                }
                catch (MemberDatabaseException)
                {
                    log.Warn("Could not get user from database when loading comments");
                }
            }

            DealComments dealComments = new DealComments()
                {
                    Comments = userComments.OrderByDescending(a => a.Value.Date),
                    Deal = deal,
                    CurrentUsername = userName
                };

            return PartialView(dealComments);
        }
예제 #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int deaID = Convert.ToInt16( Request.QueryString["dealID"]);

        purchasingDeal = DealsController.getDealByDealID(deaID);

        if (!Page.IsPostBack)
        {
            List<int> num = new List<int>();

            for (int i = 1; i < purchasingDeal.NoOfVouchers; i++)
            {
                num.Add(i);
            }
            inputQty.DataSource = num;
            inputQty.DataBind();
            total.Text = purchasingDeal.DiscountedPrice.ToString();
        }

        total.Text = "Rs. "+ (purchasingDeal.DiscountedPrice * Convert.ToInt16(inputQty.SelectedValue)).ToString("N2") +"/-";
    }
예제 #20
0
        protected void ExecDealDetailsView(Deal targetDeal)
        {
            if (!CRMSecurity.CanAccessTo(targetDeal))
            {
                Response.Redirect(PathProvider.StartURL());
            }

            var dealActionViewControl = (DealDetailsView)LoadControl(DealDetailsView.Location);

            dealActionViewControl.TargetDeal = targetDeal;
            CommonContainerHolder.Controls.Add(dealActionViewControl);

            var headerTitle = targetDeal.Title;

            Master.CurrentPageCaption = headerTitle;

            Master.CommonContainerHeader = Global.RenderItemHeaderWithMenu(headerTitle.HtmlEncode(), EntityType.Opportunity, CRMSecurity.IsPrivate(targetDeal), true);

            TabsHolder.Visible = true;

            Title = HeaderStringHelper.GetPageTitle(headerTitle);
        }
        public async Task <int> CreateAsync(string dealName, string userId, string description, Stage stage, int accountId)
        {
            var user = await this.userManager.FindByIdAsync(userId);

            var userName = user.UserName;


            var deal = new Deal
            {
                Name        = dealName,
                UserId      = userId,
                AccountId   = accountId,
                Description = description,
                Stage       = stage,
            };

            await this.dealRepository.AddAsync(deal);

            await this.dealRepository.SaveChangesAsync();

            return(deal.Id);
        }
예제 #22
0
        public void MenuTest_ReturnValue()
        {
            FakeWriterClass writer      = new FakeWriterClass();
            FakeUserInput   userInput   = new FakeUserInput(writer);
            PlayersHand     playersHand = new PlayersHand(writer, userInput);
            ShowPlayers     showPlayers = new ShowPlayers(writer);
            Deal            deal        = new Deal();
            Menu            menu        = new Menu(writer, deal, playersHand, showPlayers, userInput);


            var mockList = new List <Player>();

            mockList.Add(new Player("Test", 0));
            mockList.Add(new Player("Test1", 1));
            mockList.Add(new Player("Test2", 2));
            var mockDeck = new List <KeyValuePair <string, string> >();

            mockDeck.Add(new KeyValuePair <string, string>("Key1", "Value1"));
            mockDeck.Add(new KeyValuePair <string, string>("Key2", "Value2"));
            mockDeck.Add(new KeyValuePair <string, string>("Key3", "Value3"));
            menu.GameMenu(mockList, mockDeck);
        }
예제 #23
0
        public void CalculatePaymentsTest(decimal amount, int period, int paymentCount,
                                          decimal interestRate)
        {
            var deal = new Deal
            {
                Amount       = amount,
                DealPeriod   = period,
                PaymentCount = paymentCount,
                PaymentPlan  = new PaymentPlan {
                    CreateTime = DateTime.Now, Id = 1
                },
                InterestRate = interestRate
            };
            var mockData       = new Mock <ITrueMoneyContext>();
            var paymentService = new PaymentService(mockData.Object);
            var result         = paymentService.CalculatePayments(deal);

            Assert.NotNull(result);
            Assert.AreEqual(result.Count, paymentCount);
            Assert.AreEqual(result[result.Count - 1].DueDate.Date, DateTime.Now.AddDays(period).Date);
            Assert.IsTrue(Math.Abs(result.Sum(x => x.Amount) - amount * (1 + interestRate / 100)) < NumericConstants.Eps);
        }
예제 #24
0
        public ActionResult DeleteDeal(int id, FormCollection collection)
        {
            var userId = Convert.ToInt32(Session[KeyList.SessionKeys.UserID].ToString());
            var _deal  = dealServices.GetByID(id);

            if (_deal.IsDeleted == false)
            {
                Deal deal = dealServices.GetByID(id);
                deal.IsDeleted = true;
                dealServices.UpdateDeal(deal);
            }
            else
            {
                Deal deal = dealServices.GetByID(id);
                deal.IsDeleted = false;
                dealServices.UpdateDeal(deal);
            }
            Logs GenerateLog = new Logs();

            GenerateLog.CreateLog(Convert.ToInt32(userId), KeyList.LogMessages.DeleteStore);
            return(RedirectToAction("Deal"));
        }
예제 #25
0
파일: Form1.cs 프로젝트: Bazingaa99/DotNet
        private void DisplaySelectedDeal(ListView listView)
        {
            Deal deal = GetSelectedObject <Deal>(listView);

            if (deal == null)
            {
                return;
            }

            if (myList.Contains(deal.id))
            {
                btnAddToList.Text = REMOVE_ITEM_STRING;
                btnAddToList.Tag  = deal.id;
            }
            else
            {
                btnAddToList.Text = ADD_ITEM_STRING;
                btnAddToList.Tag  = deal.id;
            }

            UpdateSelectedItemDisplay(deal);
        }
예제 #26
0
        public ActionResult DealRequest(int Id)
        {
            if (!ModelState.IsValid)
            {
                return(HttpNotFound());
            }
            var deal    = new Deal();
            var product = _context.Products.Single(p => p.Id == Id);
            var buyerId = User.Identity.GetUserId();
            var buyer   = _context.Users.Single(u => u.Id == buyerId);

            deal.FarmerId = product.FarmerId;
            deal.Product  = product;
            deal.BuyerId  = buyerId;
            deal.Buyer    = buyer;
            deal.Status   = "Waiting";
            deal.Date     = DateTime.Now;
            _context.Deals.Add(deal);
            _context.SaveChanges();
            TempData["Message"] = "Deal request sent";
            return(RedirectToAction("Index", new { @CatId = product.CategoryId }));
        }
예제 #27
0
        public ActionResult Edit(FormCollection collection)
        {
            Deal deal = db.Deal.Find(Int32.Parse(collection["id"]));

            if (TryUpdateModel(deal, collection))
            {
                try
                {
                    // TODO: Add update logic here
                    deal.agent_id     = Int32.Parse(Session["user_id"].ToString());
                    deal.date_updated = DateTime.Now;
                    db.SaveChanges();
                    ViewData["mode"] = "edit";
                    return(Json(new { status = "success", message = "Customer information updated", deal = db.Deal.Find(Int32.Parse(collection["id"])), customer = db.Customer.Find(deal.customer_id) }));
                }
                catch
                {
                    return(Json(new { status = "error", message = "Something went wrong. " }));
                }
            }
            return(Json(new { status = "error", message = "Something went wrong. Unable to save changes." }));
        }
예제 #28
0
        public void ShouldReshuffleTheDeck()
        {
            Deck deck        = new Deck();
            var  createdDeck = deck.createDeck();

            createdDeck.RemoveRange(0, 30);

            Player player = new Player();

            player.playersHand(createdDeck.GetRange(0, 1));

            DiscardPile discardPile = new DiscardPile();

            discardPile.addCardsToDiscardPile(createdDeck.GetRange(0, 24));
            createdDeck.Clear();

            Deal deal       = new Deal(createdDeck);
            var  cardsDrawn = deal.drawCards(player, discardPile);

            Assert.AreEqual(20, deal.Deck.Count);
            Assert.AreEqual(4, cardsDrawn.Count);
        }
예제 #29
0
        public List <Deal> GetAllDeals()
        {
            List <Deal> deals = new List <Deal>();

            foreach (ProductPurchase purchase in ObjectCtx.Context.ProductPurchases.Include(pp => pp.Product).
                     Where(pp => pp.Product == this))
            {
                Deal deal = new Deal
                {
                    Details         = purchase.Remarks,
                    NumItems        = purchase.NumItems,
                    UnitPrice       = purchase.Price,
                    TransactionDate = purchase.PurchaseDate,
                    TransactionType = DealType.Purchase
                };
                deals.Add(deal);
            }

            foreach (ProductSale productSale in ObjectCtx.Context.ProductSales.Include(ps => ps.SaleItems))
            {
                foreach (SaleItem saleItem in productSale.SaleItems.Where(si => si.Product == this))
                {
                    Deal deal = new Deal
                    {
                        Details         = productSale.Remarks,
                        Buyer           = productSale.Customer,
                        TransactionDate = productSale.SaleDate,
                        NumItems        = saleItem.NumSold,
                        UnitPrice       = saleItem.UnitPrice,
                        TransactionType = DealType.Sale
                    };
                    deals.Add(deal);
                }
            }

            deals.Sort((deal1, deal2) => deal1.TransactionDate.CompareTo(deal2.TransactionDate));

            return(deals);
        }
예제 #30
0
        public DealSpecificProductViewModel(Deal model, IEnumerable<Deal> popularDeals)
        {
            ImageUrls = model.Pictures.Select(p => p.RelativeUrl).ToList();

            OriginalPrice = model.RegularPrice;
            DiscountedPrice = model.SpecialPrice;
            EndDate = model.EndTime;

            LongTitle = model.LongTitle;
            ShortDescription = model.ShortDescription;
            LongDescription = model.LongDescription;

            Fineprint = model.FinePrint;
            Highlight = model.Highlight;

            DealOptions = model.DealOptions.Select(d => new DealOptionViewModel(d)).ToList();
            Comments = model.Comments.Select(c => new DealSpecificProductCommentViewModel(c)).ToList();
            Merchant = new DealSpecificProductMerchantViewModel(model.Merchant);
            PopularDeals = new PopularDealsViewModel(popularDeals);

            Id = model.Id.ToString();
        }
예제 #31
0
        /// <summary>
        /// 无结果或搜索时发生异常,修改主窗的status状态。
        /// </summary>
        private void NullResult()
        {
            this.dtStop = DateTime.Now;
            //无结果时也是只有1页。
            this.currentPage = 1;
            this.pageNums    = 1;
            CrossThreadOperateControl CrossUpdateStatus = delegate()
            {
                lock (this.form)
                {
                    this.form.IsSearch = false;
                    ////无结果无法保存。
                    //this.form.保存结果ToolStripMenuItem.Enabled = false;
                    this.form.OrginalStatusText = "0 个对象     用时:"
                                                  + (this.dtStop - this.dtStart).TotalSeconds + "秒";
                    this.form.tsslStatus.Text = Deal.LimitStringLength(this.form.OrginalStatusText,
                                                                       this.form.TsslLength);
                }
            };

            this.form.Invoke(CrossUpdateStatus);
        }
예제 #32
0
        public void SendAboutResponsibleForOpportunity(Deal deal)
        {
            var recipient = ToRecipient(deal.ResponsibleID);

            if (recipient == null)
            {
                return;
            }

            client.SendNoticeToAsync(
                NotifyConstants.Event_ResponsibleForOpportunity,
                null,
                new[] { recipient },
                true,
                new TagValue(NotifyConstants.Tag_EntityTitle, deal.Title),
                new TagValue(NotifyConstants.Tag_EntityID, deal.ID),
                new TagValue(NotifyConstants.Tag_AdditionalData,
                             new Hashtable {
                { "OpportunityDescription", HttpUtility.HtmlEncode(deal.Description) }
            })
                );
        }
예제 #33
0
 public void UpdateData(Deal dealpro)
 {
     //try
     //{
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
         using (SqlCommand cmd = new SqlCommand("UpdateData", conn))
         {
             cmd.CommandType = System.Data.CommandType.StoredProcedure;
             conn.Open();
             cmd.Parameters.AddWithValue("@description", dealpro.description);
             cmd.Parameters.AddWithValue("@price", dealpro.price);
             cmd.Parameters.AddWithValue("@id", dealpro.id);
             cmd.ExecuteNonQuery();
         }
     }
     //    }
     //    catch (Exception ex)
     //    {
     //Debug.WriteLine("Exception Message: " + ex.Message);
     //    }
 }
예제 #34
0
        public static void NewDeal(Deal deal, decimal order_price, int type = 0)
        {
            //计算手续费,佣金最少收5元
            string key_unit = "U_" + deal.unit_id;
            Unit   unit     = UnitRA.Get(key_unit);

            deal.commission     = Math.Max(Math.Round(deal.money * unit.ratio_commission, 2), 5);
            deal.management_fee = Math.Round(deal.money * unit.ratio_management_fee, 2);

            //卖单计算盈亏
            Position position = PositionRA.Get("P_" + deal.code + "_A_" + deal.account_id + "_U_" + deal.unit_id);

            if (deal.type == 1 && position != null)
            {
                deal.profit = Math.Round((deal.price - position.price_cost) * deal.count - deal.commission, 2);
            }

            //更新手续费和盈亏
            DealRA.UpdateFee(deal, "D_" + deal.deal_no + "_O_" + deal.order_no + "_U_" + deal.unit_id);

            AdjustPosition(position, deal, order_price, type);
        }
예제 #35
0
        public async Task <IActionResult> OnGetAsync(int id)
        {
            var user = await GetUser();

            Deal = await _db.Deal
                   .Include(c => c.Merchant).FirstOrDefaultAsync(m => m.Id == id);

            if (!user.IsAdmin)
            {
                if (user.MerchantId != Deal.MerchantId)
                {
                    StatusMessage = "Only Admin users or deal owning merchants may edit a deal.";
                }
            }

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

            return(Page());
        }
예제 #36
0
        /// <summary>
        /// Determines whether the deal must be claimed for the card.
        /// </summary>
        /// <param name="deal">
        /// The deal that may need to be claimed.
        /// </param>
        /// <param name="card">
        /// The card for which the deal may need to be claimed.
        /// </param>
        /// <returns>
        /// * True if the deal must be claimed for the card.
        /// * Else returns false.
        /// </returns>
        private bool MustClaim(Deal deal,
                               Card card)
        {
            bool result = true;

            // A deal only has to be claimed for the card if
            // the deal is registered with First Data,
            result = deal.PartnerDealInfoList.Any(info => info.PartnerId == Partner.FirstData);

            if (result == true)
            {
                // the card has been registered with First Data,
                result = card.PartnerCardInfoList.Any(info => info.PartnerId == Partner.FirstData);
            }

            if (result == true)
            {
                // the deal pays back currency, and
                if (deal.ReimbursementTender == ReimbursementTender.DeprecatedEarn)
                {
                    // the card is in the CLO offers program.
                    result = (card.RewardPrograms & RewardPrograms.CardLinkOffers) == RewardPrograms.CardLinkOffers;
                }
                // or the deal burns earned credits, and
                else if (deal.ReimbursementTender == ReimbursementTender.MicrosoftBurn)
                {
                    // the card is in the EarnBurn program.
                    result = (card.RewardPrograms & RewardPrograms.EarnBurn) == RewardPrograms.EarnBurn;
                }
                // Otherwise, the card and deal are not in compatible programs, so no claim should be made.
                else
                {
                    result = false;
                }
            }

            return(result);
        }
        /// <summary>
        /// Dequeues an item from the specified queue and processes the message
        /// </summary>
        private void ProcessNextRequest()
        {
            PartnerTransactionReportingCargo partnerTransactionReportingCargo = null;

            try
            {
                if (this._jobsQueue.TryDequeue(out partnerTransactionReportingCargo))
                {
                    Log.Info("Dequeued transaction job from partner-transactions queue. Cargo : {0}", partnerTransactionReportingCargo.ToString());
                    //Get the deal id from the cargo and query the deals server for the deal info
                    List <Guid> dealsGuid = new List <Guid> {
                        new Guid(partnerTransactionReportingCargo.DealId)
                    };
                    Log.Info("Querying the deal server for deal id : {0}", partnerTransactionReportingCargo.DealId);
                    Task <IEnumerable <Deal> > dealsByGuidTask = _dealsClient.GetDealsById(dealsGuid, format: "all");
                    IEnumerable <Deal>         deals           = dealsByGuidTask.Result.ToList();
                    if (deals.Any())
                    {
                        Deal deal = deals.First();
                        InvokeTransactionReporter(deal, partnerTransactionReportingCargo);
                    }
                    else
                    {
                        Log.Warn(string.Format("Deal {0} not found in deals server", partnerTransactionReportingCargo.DealId));
                    }
                }
                else
                {
                    // No jobs in the queue.
                    Log.Verbose("No jobs in the partner-transaction jobs queue. Agent Id: {0} is going to sleep for {1} seconds", this._agentId, SleepTimeWhenQueueEmpty.TotalSeconds);
                    Thread.Sleep(SleepTimeWhenQueueEmpty);
                }
            }
            catch (Exception exp)
            {
                this.HandleError(EventCode.EmailAgentUnexpectedError, exp, "Unexpected Error", this._agentId, partnerTransactionReportingCargo);
            }
        }
예제 #38
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            int  dealID = Convert.ToInt32(listViewDeals.SelectedItems[0].SubItems[0].Text);
            Deal deal   = rh.GetDeal(dealID);

            Car      car       = (Car)comboCar.SelectedItem;
            DateTime startDate = dateTimePickerStartDay.Value;
            DateTime endDate   = dateTimePickerEndDay.Value;
            bool     isInsured = checkBoxInsurance.Checked;

            RentedCar rentedCar = new RentedCar(car, deal, startDate, endDate, isInsured);

            if (rentedCarID == 0)
            {
                try
                {
                    rh.SetRentedCarWithCheck(rentedCar);
                    GetRentedCars();
                }
                catch (ArgumentException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                try
                {
                    rentedCar.rentedCarID = rentedCarID;
                    rh.UpdateRentedCarWithCheck(rentedCar);
                    GetRentedCars();
                }
                catch (ArgumentException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
예제 #39
0
        public ActionResult create(CreateDealViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = User.Identity.GetUserId();
                var md   = new Deal();
                var now  = DateTime.Now;
                md.BulkBuyingScore = model.BulkBuyingScore;
                md.Created         = DateTime.Now;
                md.Duration        = model.Duration;
                md.DurationScore   = model.DurationScore;
                if (model.Starts != null)
                {
                    md.Starts = model.Starts;
                    md.Ends   = model.Starts.Value.AddDays(model.Duration);
                }
                else
                {
                    md.Starts = now;
                    md.Ends   = now.AddDays(model.Duration);
                }
                md.Listing       = db.Listings.Find(model.ListingId);
                md.ListingId     = model.ListingId;
                md.OutreachScore = model.OutreachScore;
                md.PriceScore    = model.PriceScore;
                md.QualityScore  = model.QualityScore;
                md.Updated       = now;
                md.Created       = now;
                md.UpdaterId     = user;
                db.Deals.Add(md);
                db.SaveChanges();
                return(RedirectToAction("index"));
            }
            var t = db.Listings.Find(model.ListingId);

            model.Listing = t;
            return(View(model));
        }
예제 #40
0
        public async Task <Deal> CreateDeal(Deal deal)
        {
            var tmpDeal = await _dealRepositoryAsync.Queryable().FirstOrDefaultAsync(x => x.BuyerAccountId == deal.BuyerAccountId && x.PublisherId == deal.PublisherId && x.DealKey == deal.DealKey);

            if (tmpDeal != null)
            {
                if (tmpDeal.DealStatusId != (int)CampaignStatusEnum.Deleted)
                {
                    throw new BrandscreenException("Found duplicated deal key under the same buyer account and publisher.");
                }

                // recover from deleted deal
                tmpDeal.ObjectState       = ObjectState.Modified;
                tmpDeal.DealName          = deal.DealName;
                tmpDeal.DealTypeId        = deal.DealTypeId;
                tmpDeal.FloorPriceCents   = deal.FloorPriceCents;
                tmpDeal.CeilingPriceCents = deal.CeilingPriceCents;
                tmpDeal.UtcStartDateTime  = deal.UtcStartDateTime;
                tmpDeal.UtcEndDateTime    = deal.UtcEndDateTime;
                tmpDeal.CurrencyId        = deal.CurrencyId;
                deal = tmpDeal;
            }
            else
            {
                deal.ObjectState = ObjectState.Added;
                deal.DealUuid    = IdentityValue.GenerateNewId();
            }

            deal.DealStatusId        = (int)CampaignStatusEnum.Live;
            deal.UtcCreatedDateTime  = _clock.UtcNow;
            deal.UtcModifiedDateTime = null;

            // save
            _dealRepositoryAsync.InsertOrUpdateGraph(deal);
            await _brandscreenContext.SaveChangesAsync();

            return(deal);
        }
예제 #41
0
        public static void DemandCreateOrUpdate(Deal deal)
        {
            if (string.IsNullOrEmpty(deal.Title) || deal.ResponsibleID == Guid.Empty ||
                deal.DealMilestoneID <= 0 || string.IsNullOrEmpty(deal.BidCurrency))
            {
                throw new ArgumentException();
            }


            var listItem = Global.DaoFactory.GetDealMilestoneDao().GetByID(deal.DealMilestoneID);

            if (listItem == null)
            {
                throw new ArgumentException("Deal milestone is not found");
            }

            if (deal.ContactID != 0)
            {
                var contact = Global.DaoFactory.GetContactDao().GetByID(deal.ContactID);
                if (contact == null)
                {
                    throw new ArgumentException();
                }
                CRMSecurity.DemandAccessTo(contact);
            }

            if (string.IsNullOrEmpty(deal.BidCurrency))
            {
                throw new ArgumentException();
            }
            else
            {
                if (CurrencyProvider.Get(deal.BidCurrency.ToUpper()) == null)
                {
                    throw new ArgumentException();
                }
            }
        }
예제 #42
0
        protected override void PageLoad()
        {
            int dealID;

            if (int.TryParse(Request["id"], out dealID))
            {
                Deal targetDeal = Global.DaoFactory.GetDealDao().GetByID(dealID);

                if (targetDeal == null || !CRMSecurity.CanAccessTo(targetDeal))
                {
                    Response.Redirect(PathProvider.StartURL() + "deals.aspx");
                }

                if (String.Compare(Request["action"], "manage", true) == 0)
                {
                    ExecDealActionView(targetDeal);
                }
                else
                {
                    ExecDealDetailsView(targetDeal);
                }
            }
            else
            {
                if (String.Compare(Request["action"], "manage", true) == 0)
                {
                    ExecDealActionView(null);
                }
                else if (String.Compare(UrlParameters.Action, "import", true) == 0)
                {
                    ExecImportView();
                }
                else
                {
                    ExecListDealView();
                }
            }
        }
예제 #43
0
        private int CreateNewDeal(Deal deal, DbManager db)
        {
            if (String.IsNullOrEmpty(deal.Title) || deal.ResponsibleID == Guid.Empty || deal.DealMilestoneID <= 0)
            {
                throw new ArgumentException();
            }

            // Delete relative  keys
            _cache.Remove(_dealCacheKey);
            _cache.Insert(_dealCacheKey, String.Empty);


            var dealID = db.ExecuteScalar <int>(
                Insert("crm_deal")
                .InColumnValue("id", 0)
                .InColumnValue("title", deal.Title)
                .InColumnValue("description", deal.Description)
                .InColumnValue("responsible_id", deal.ResponsibleID)
                .InColumnValue("contact_id", deal.ContactID)
                .InColumnValue("bid_currency", deal.BidCurrency)
                .InColumnValue("bid_value", deal.BidValue)
                .InColumnValue("bid_type", deal.BidType)
                .InColumnValue("deal_milestone_id", deal.DealMilestoneID)
                .InColumnValue("deal_milestone_probability", deal.DealMilestoneProbability)
                .InColumnValue("expected_close_date", TenantUtil.DateTimeToUtc(deal.ExpectedCloseDate))
                .InColumnValue("actual_close_date", TenantUtil.DateTimeToUtc(deal.ActualCloseDate))
                .InColumnValue("per_period_value", deal.PerPeriodValue)
                .InColumnValue("create_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
                .InColumnValue("create_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                .InColumnValue("last_modifed_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
                .InColumnValue("last_modifed_by", ASC.Core.SecurityContext.CurrentAccount.ID)
                .Identity(1, 0, true));

            //    if (deal.ContactID > 0)
            //      AddMember(dealID, deal.ContactID);

            return(dealID);
        }
예제 #44
0
        private decimal CalculateTwoForThree(
            List <Product> products, List <Product> tempProducts, Deal deal, decimal totalPrice)
        {
            var validForDiscount = new Dictionary <string, Product>();
            int counter          = 0;

            for (int i = 0; i < products.Count; i++)
            {
                var product = products[i];

                if (deal.Products.Any(pd => pd.Product.Name == product.Name))
                {
                    if (!validForDiscount.ContainsKey(product.Name))
                    {
                        validForDiscount.Add(product.Name, product);
                    }
                    counter++;
                }
                else
                {
                    tempProducts.Add(product);
                }

                if (counter == 3)
                {
                    totalPrice -= validForDiscount.Values.Min(v => v.Price);
                    validForDiscount.Clear();
                    counter = 0;
                }
            }

            if (validForDiscount.Count > 0)
            {
                tempProducts.AddRange(validForDiscount.Values);
            }

            return(totalPrice);
        }
예제 #45
0
        public void RegisterNewDeal(Client seller, Client buyer, Stock stock, decimal cost)
        {
            if (!stock.IsForSale)
            {
                throw new ArgumentException("The stock is not allowed to be selled.", "stock");
            }
            if (!seller.Stocks.Remove(stock))
            {
                throw new ArgumentException("The stock does not belong to the seller.", "stock, seller");
            }
            buyer.Stocks.Add(stock);
            seller.Balance += cost;
            seller.Zone     = GetZone(seller.Balance);
            buyer.Balance  -= cost;
            buyer.Zone      = GetZone(buyer.Balance);
            var newDeal = new Deal()
            {
                Buyer = buyer, Seller = seller, Cost = cost, Stock = stock
            };

            this.dataContext.Add(newDeal);
            this.dataContext.SaveChanges();
        }
 private void initFormOperations(int dealId)
 {
     deal                          = Deal.getById(dealId);
     tb_DealName.Text              = deal.Name;
     tb_DealSalePrice.Text         = Convert.ToString(deal.SalePrice);
     cbx_ManageInventory.IsChecked = deal.ManageInventory;
     foreach (FoodItemSmallModel item in Deal.getMAppedListOfDealDetailsToFoodItemSmallModelByDealId(dealId))
     {
         dg_DealFoodItems.Items.Add(item);
     }
     foreach (FoodItemSmallModel item in FoodItem.getMappedListOfAllFoodItemToFoodItemSmallModel())
     {
         dg_AllFoodItems.Items.Add(item);
     }
     foreach (tbl_FoodItemCategory item in FoodItemCategory.getAll())
     {
         cb_Cat.ItemsSource       = FoodItemCategory.getAll();
         cb_Cat.DisplayMemberPath = "Name";
         cb_Cat.SelectedValuePath = "Id";
     }
     cb_Cat.SelectedValue = deal.Category_Id;
     update_lbl_Total();
 }
예제 #47
0
        private void comboBox_DealID_SelectionChangeCommitted(object sender, EventArgs e)
        {
            label_DealID.Text = comboBox_DealID.SelectedValue.ToString();
            aDeal.ID          = Convert.ToInt32(label_DealID.Text);

            if (aDeal.ID > 0)
            {
                aDeal = aDealH.GetItem(aDeal.ID);

                if (comboBox_TransactionType.SelectedIndex.ParseEnum <ProductTransactionType>() == ProductTransactionType.Purchase)
                {
                    numericUpDown_FullAmount.Value    = Convert.ToDecimal(aDeal.PurchaseAmount);
                    numericUpDown_BalanceAmount.Value = Convert.ToDecimal(aDeal.PurchaseAmount_Remaining);
                    label_Amount.Text = Convert.ToString(aDeal.PurchaseAmount_Remaining);
                }
                else if (comboBox_TransactionType.SelectedIndex.ParseEnum <ProductTransactionType>() == ProductTransactionType.Sale)
                {
                    numericUpDown_FullAmount.Value    = Convert.ToDecimal(aDeal.SaleAmount);
                    numericUpDown_BalanceAmount.Value = Convert.ToDecimal(aDeal.SaleAmount_Remaining);
                    label_Amount.Text = Convert.ToString(aDeal.SaleAmount_Remaining);
                }
            }
        }
예제 #48
0
        public Result Transfer(Transfer model)
        {
            string[] keys = TradeRA.KeySearch("D_" + model.deal_no + "_*_U_0");
            if (keys.Length > 0 && TradeRA.KeyExists("U_" + model.unit_id))
            {
                Deal deal = DealRA.Get(keys[0]);
                if (deal.type_enum == OrderTypeEnum.Sell)
                {
                    int sellable_count = PositionRA.GetSellable(model.unit_id, deal.code, deal.account_id);
                    if (deal.count > sellable_count)
                    {
                        return(Result(ApiResultEnum.Order_Account_Negative_Position));
                    }
                }

                deal.unit_id = model.unit_id;
                DealRA.UpdateUnit(model.unit_id, keys[0]);
                TradeRA.KeyRename(keys[0], keys[0].Substring(0, keys[0].Length - 1) + model.unit_id);
                TradeBiz.NewDeal(deal, deal.price, 1);
                return(Result(ApiResultEnum.Success));
            }
            return(Result(ApiResultEnum.Failed));
        }
예제 #49
0
 public static void SaveDeal(ref Dictionary <int, decimal[]> dic)
 {
     string[] keys = TradeRA.KeySearch("D_*");
     foreach (string key in keys)
     {
         Deal deal = DealRA.Get(key);
         DealDA.Add(deal);
         if (deal.unit_id > 0)
         {
             if (dic.ContainsKey(deal.unit_id))
             {
                 dic[deal.unit_id][0] = dic[deal.unit_id][0] + deal.commission;
                 dic[deal.unit_id][1] = dic[deal.unit_id][1] + deal.profit;
             }
             else
             {
                 dic.Add(deal.unit_id, new decimal[2] {
                     deal.commission, deal.profit
                 });
             }
         }
     }
 }
예제 #50
0
 /// <summary>
 /// 每隔1秒显示正在扫描的文件夹
 /// </summary>
 private void tmrIndexStatus_Tick(object sender, EventArgs e)
 {
     if (this.index.IsIndexComplete == true)
     {
         this.orginalStatusText = "索引完成 用时:" + index.IndexTime + " 秒  "
                                  + this.index.IndexFileFolderNum;
         this.tsslStatus.Text        = Deal.LimitStringLength(this.orginalStatusText, this.tsslLength);
         this.tmrIndexStatus.Enabled = false;
         this.search.SetSearcher(this.searchMode);
         this.btnUpdate.Visible   = false;
         this.tmrReSearch.Enabled = true;
         this.index.Dispose();
     }
     else
     {
         this.currentDirectory = this.index.GetCurrentDirectory();
         if (currentDirectory != "")
         {
             this.orginalStatusText = "正在扫描 " + this.currentDirectory;
             this.tsslStatus.Text   = Deal.LimitStringLength(this.orginalStatusText, this.tsslLength);
         }
     }
 }
예제 #51
0
    // **********************************************************************

    public override void Read(bool push)
    {
      Deal d = new Deal();

      DealFlagsV3 flags = (DealFlagsV3)dr.ReadByte();

      if((flags & DealFlagsV3.DateTime) != 0)
        d.DateTime = lastDateTime = dr.ReadDateTime(ref baseDateTime);
      else
        d.DateTime = lastDateTime;

      if((flags & DealFlagsV3.Price) != 0)
        d.Price = lastPrice = Security.GetPrice(dr.ReadRelative(ref basePrice));
      else
        d.Price = lastPrice;

      if((flags & DealFlagsV3.Volume) != 0)
        d.Volume = lastVolume = dr.ReadPackInt();
      else
        d.Volume = lastVolume;

      if((flags & DealFlagsV3.OI) != 0)
        d.OI = lastOI = dr.ReadRelative(ref baseOI);
      else
        d.OI = lastOI;

      if((flags & DealFlagsV3.Id) != 0)
        d.Id = dr.ReadRelative(ref lastId);

      d.Type = (DealType)(flags & DealFlagsV3.Type);

      if(push && Handler != null)
      {
        d.SecKey = Security.Key;
        Handler(d);
      }
    }
예제 #52
0
 public StopLossEvent(Deal deal)
     : base(deal)
 {
 }
예제 #53
0
 public Promotion(Business business, Event ev, Deal deal, int available, byte maxReferal)
     : this(business, ev, new Deal[] { deal }, available, maxReferal)
 {
 }
예제 #54
0
        /// <summary>
        /// Save deal
        /// </summary>
        /// <param name="deal">Deal model</param>
        public void SaveDeal(Deal deal)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ReadWriteDatabase"].ConnectionString;

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = SaveDealQuery;

                        command.Parameters.AddWithValue("@active", true);
                        command.Parameters.AddWithValue("@date", DateTime.Now);
                        command.Parameters.AddWithValue("@description", deal.Description ?? string.Empty);
                        command.Parameters.AddWithValue("@imageUrl", deal.ImageUrl);
                        command.Parameters.AddWithValue("@price", deal.Price);
                        command.Parameters.AddWithValue("@retailer", deal.Retailer);
                        command.Parameters.AddWithValue("@title", deal.Title);
                        command.Parameters.AddWithValue("@url", deal.Url);
                        command.Parameters.AddWithValue("@username", deal.UserName);

                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                log.Warn(e, "Could not save deal - title: {0} description: {1} url: {2} image: {3} user: {4}", deal.Title, deal.Description, deal.Url, deal.ImageUrl, deal.UserName);
            }
        }
예제 #55
0
        public ActionResult Open([Bind(Include = "HouseholdId,AccountName,HeldAt,AccountNumber,OpeningBalance,OpeningDate,BalanceCurrent")] BankAcctViewModel bankAcct)
        {
            if (ModelState.IsValid)
            {
                bankAcct.AccountName = bankAcct.HeldAt + "::" + bankAcct.AccountNumber;

                if (db.BankAccts.Any(a => a.AccountName == bankAcct.AccountName))
                {
                    ModelState.AddModelError("AccountName", "Please enter a unique Account number for this Institution.");
                    return View(bankAcct);
                }

                if (bankAcct.OpeningDate == null)
                    bankAcct.OpeningDate = System.DateTimeOffset.Now;

                var newBankAcct = new BankAcct();

                newBankAcct.AccountNumber = bankAcct.AccountNumber;
                newBankAcct.HeldAt = bankAcct.HeldAt;
                newBankAcct.AccountName = bankAcct.AccountName;
                newBankAcct.HouseholdId = bankAcct.HouseholdId;
                newBankAcct.Opened = bankAcct.OpeningDate;
                newBankAcct.BalanceCurrent = bankAcct.OpeningBalance;
                db.BankAccts.Add(newBankAcct);
                if (bankAcct.OpeningBalance != 0)
                {
                    var openDeal = new Deal();
                    openDeal.BankAcctId = newBankAcct.Id;
                    var cat = db.Categories.FirstOrDefault(c => c.HouseholdId == newBankAcct.HouseholdId && c.Name == "Other Income");
                    openDeal.CategoryId = cat.Id;
                    openDeal.Amount = bankAcct.OpeningBalance;
                    openDeal.DealDate = (DateTimeOffset)bankAcct.OpeningDate;
                    openDeal.Description = "Opening Transaction";
                    openDeal.Payee = "Deposit";
                    openDeal.Reconciled = false;
                    db.Deals.Add(openDeal);
                }
                db.SaveChanges();
                return RedirectToAction("Index", "BankAccts");
            }

            return RedirectToAction("Index", "BankAccts");
        }
예제 #56
0
        // PUT api/DealApi/5
        public HttpResponseMessage PutDeal(Guid id, Deal deal)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != deal.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

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

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
예제 #57
0
        // POST api/DealApi
        public HttpResponseMessage PostDeal(Deal deal)
        {
            if (ModelState.IsValid)
            {
                db.Deals.Add(deal);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, deal);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = deal.Id }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
예제 #58
0
        private static Deal GetDeal(SqlDataReader reader)
        {
            Deal deal = new Deal
            {
                Title = reader.GetString(reader.GetOrdinal("Title")).Trim(),
                DealID = reader.GetInt32(reader.GetOrdinal("DealId")),
                UserName = reader.GetString(reader.GetOrdinal("Username")).Trim(),
                Description = reader.GetString(reader.GetOrdinal("Description")).Trim(),
                Retailer = reader.GetString(reader.GetOrdinal("Retailer")).Trim(),
                Price = Math.Round(reader.GetFloat(reader.GetOrdinal("Price")), 2),
                Url = reader.GetString(reader.GetOrdinal("Url")).Trim(),
                ImageUrl = reader.GetString(reader.GetOrdinal("ImageUrl")).Trim(),
                Date = reader.GetDateTime(reader.GetOrdinal("Date")),
                Active = reader.GetBoolean(reader.GetOrdinal("Active"))
            };

            return deal;
        }
예제 #59
0
    public bool insertOrUpdate(Deal deal)
    {
        // This is an update
        if (deal.DealID > 0)
        {
            return submitChanges();
        }
        else {

            db.Deals.InsertOnSubmit(deal);

            return submitChanges();
        }
    }
예제 #60
0
    public bool deleteDeal(Deal deal)
    {
        db.Deals.DeleteOnSubmit(deal);

        return submitChanges();
    }