Inheritance: Gtk.TreeView
示例#1
1
文件: Job.cs 项目: t-h-e/HeuristicLab
 protected Job(Job original, Cloner cloner)
   : base(original, cloner) {
   this.dueDate = original.DueDate;
   this.index = original.Index;
   this.tasks = cloner.Clone(original.Tasks);
   RegisterEventHandlers();
 }
        public override ItemList ProcessShow(ShowItem si, bool forceRefresh)
        {
            // for each tv show, optionally write a tvshow.nfo file
            if (TVSettings.Instance.NFOs)
            {
                ItemList TheActionList = new ItemList();
                FileInfo tvshownfo = FileHelper.FileInFolder(si.AutoAdd_FolderBase, "tvshow.nfo");

                bool needUpdate = !tvshownfo.Exists ||
                                  (si.TheSeries().Srv_LastUpdated > TimeZone.Epoch(tvshownfo.LastWriteTime)) ||
                    // was it written before we fixed the bug in <episodeguideurl> ?
                                  (tvshownfo.LastWriteTime.ToUniversalTime().CompareTo(new DateTime(2009, 9, 13, 7, 30, 0, 0, DateTimeKind.Utc)) < 0);

                bool alreadyOnTheList = DownloadXBMCMetaData.doneNFO.Contains(tvshownfo.FullName);

                if ((forceRefresh || needUpdate) && !alreadyOnTheList)
                {
                    TheActionList.Add(new ActionNFO(tvshownfo, si));
                    DownloadXBMCMetaData.doneNFO.Add(tvshownfo.FullName);
                }
                return TheActionList;

            }
            return base.ProcessShow(si, forceRefresh);
        }
示例#3
0
文件: Package.cs 项目: oleeq2/ToDo
 public Request(ItemAction action, ItemList data)
 {
     this.action     = action;
        this.data       = data;
        this.filter     = 0;
        this.filter_key = string.Empty;
 }
示例#4
0
文件: RemoteList.cs 项目: oleeq2/ToDo
 public void Add(Item itm)
 {
     ItemList data = new ItemList();
     data.Add(itm);
     Request request = new Request(ItemAction.Add, data);
     request.SendPackage(_sck);
 }
示例#5
0
        public override void LoadContent()
        {
            base.LoadContent();

            sp = mainGame.mySpriteBatch;
            font = mainGame.Content.Load<SpriteFont>("Important/meirio_14");

            //背景
            backTexture = mainGame.Content.Load<Texture2D>("Profile/eraSelectBack");
            backRectangle = new Rectangle(50, height / 100, width - 100, height * 98 / 100);

            //事件一覧
            eventList = new ItemList<Event>(
                mainGame,
                Event.PersonSelectEvent(mainGame.person),
                font,
                new Rectangle(
                     backRectangle.X + backRectangle.Width / 10,
                     backRectangle.Y + backRectangle.Height / 5,
                     backRectangle.Width * 8 / 10,
                     backRectangle.Height * 5 / 10));
            eventList.LoadContent();

            //フェードインを有効にする
            fadeIn.isEnabled = true;
        }
示例#6
0
 public Schedule(int nrOfResources) {
   Resources = new ItemList<Resource>();
   for (int i = 0; i < nrOfResources; i++) {
     Resources.Add(new Resource(i));
   }
   lastScheduledTaskOfJob = new Dictionary<int, ScheduledTask>();
 }
    protected override void OnContentChanged() {
      base.OnContentChanged();
      if (Content != null) {
        var data = Content.Data;
        var filterLogic = new FilterLogic(data);
        var searchLogic = new SearchLogic(data, filterLogic);
        var statisticsLogic = new StatisticsLogic(data, searchLogic);
        var manipulationLogic = new ManipulationLogic(data, searchLogic, statisticsLogic);

        var viewShortcuts = new ItemList<IViewShortcut> {
          new DataGridContent(data, manipulationLogic, filterLogic),
          new StatisticsContent(statisticsLogic),

          new LineChartContent(data),
          new HistogramContent(data),
          new ScatterPlotContent(data),
          new CorrelationMatrixContent(Content),
          new DataCompletenessChartContent(searchLogic),
          
          new FilterContent(filterLogic),
          new ManipulationContent(manipulationLogic, searchLogic, filterLogic),
          new TransformationContent(data, filterLogic)
        };

        viewShortcutListView.Content = viewShortcuts.AsReadOnly();

        viewShortcutListView.ItemsListView.Items[0].Selected = true;
        viewShortcutListView.Select();

      } else {
        viewShortcutListView.Content = null;
      }
    }
示例#8
0
文件: TVDoc.cs 项目: mudboy/tvrename
                                         }; // TODO: move into settings, and allow user to edit these

        #endregion Fields

        #region Constructors

        public TVDoc(FileInfo settingsFile, TheTVDB tvdb, CommandLineArgs args)
        {
            this.mTVDB = tvdb;
            this.Args = args;

            this.Ignore = new List<IgnoreItem>();

            this.Workers = null;
            this.WorkerSemaphore = null;

            this.mStats = new TVRenameStats();
            this.mDirty = false;
            this.TheActionList = new ItemList();

            this.Settings = new TVSettings();

            this.MonitorFolders = new List<String>();
            this.IgnoreFolders = new List<String>();
            this.SearchFolders = new List<String>();

            ShowItems = new List<ShowItem>();
            this.AddItems = new FolderMonitorEntryList();

            this.DownloadDone = true;
            this.DownloadOK = true;

            this.ActionCancel = false;
            this.ScanProgDlg = null;

            this.LoadOK = ((settingsFile == null) || this.LoadXMLSettings(settingsFile)) && this.mTVDB.LoadOK;

            UpdateTVDBLanguage();

            //    StartServer();
        }
示例#9
0
        private IEnumerable<ContentItem> GetChildren(bool getPages)
        {
            var items = new ItemList();
            foreach (var parent in gateway.FindTranslations(Selection.SelectedItem))
            {
	            if (getPages)
	            {
		            foreach (ContentItem child in parent.GetChildPagesUnfiltered().Where(Engine.EditManager.GetEditorFilter(User)))
			            if (!items.ContainsAny(gateway.FindTranslations(child)))
				            items.Add(child);
	            }
	            else
	            {
					foreach (ContentItem child in parent.GetChildPartsUnfiltered().Where(Engine.EditManager.GetEditorFilter(User)))
						if (!items.ContainsAny(gateway.FindTranslations(child)))
							items.Add(child);
	            }
            }
            items.Sort();

            foreach (ContentItem item in items)
            {
	            if (item is ILanguage)
                    continue;
	            if (item.IsPage == getPages)
		            yield return item;
            }
        }
示例#10
0
        public override ItemList ProcessSeason(ShowItem si, string folder, int snum, bool forceRefresh)
        {
            if (TVSettings.Instance.FolderJpg)
            {
                // season folders JPGs

                ItemList TheActionList = new ItemList();
                FileInfo fi = FileHelper.FileInFolder(folder, defaultFileName);
                if (!doneFolderJPG.Contains(fi.FullName) && (!fi.Exists|| forceRefresh))
                // some folders may come up multiple times
                {

                    string bannerPath = "";

                    if (TVSettings.Instance.SeasonSpecificFolderJPG())
                    {
                        //We are getting a Series Level image
                        bannerPath = si.TheSeries().GetSeasonBannerPath(snum);
                    }
                    else
                    {
                        //We are getting a Show Level image
                        bannerPath = si.TheSeries().GetItem(TVSettings.Instance.ItemForFolderJpg());
                    }
                    if (!string.IsNullOrEmpty(bannerPath))
                        TheActionList.Add(new ActionDownload(si, null, fi, bannerPath,
                                                                  TVSettings.Instance.ShrinkLargeMede8erImages));
                    doneFolderJPG.Add(fi.FullName);
                }
                return TheActionList;
            }

            
            return base.ProcessSeason(si,folder,snum,forceRefresh);
        }
示例#11
0
        public override ItemList ProcessShow(ShowItem si, bool forceRefresh)
        {
            

            if (TVSettings.Instance.FolderJpg)
            {
                ItemList TheActionList = new ItemList();
                FileInfo fi = FileHelper.FileInFolder(si.AutoAdd_FolderBase, defaultFileName);
                bool fileDoesntExist = !doneFolderJPG.Contains(fi.FullName) && !fi.Exists;

                if (forceRefresh || fileDoesntExist)
                {
                    //default to poster when we want season posters for the season specific folders;
                    string itemToGet = (TVSettings.Instance.SeasonSpecificFolderJPG()) ? "poster" : TVSettings.Instance.ItemForFolderJpg();

                    string bannerPath = bannerPath = si.TheSeries().GetItem(itemToGet);

                    if (!string.IsNullOrEmpty(bannerPath))
                        TheActionList.Add(new ActionDownload(si, null, fi, bannerPath, false));
                    doneFolderJPG.Add(fi.FullName);
                }
                return TheActionList;

            }
            return null;
        }
示例#12
0
        protected void AddReferencesRecursive(ContentItem current, ItemList referrers)
        {
            referrers.AddRange(Content.Search.Repository.Find(Parameter.Equal(null, Item).Detail()));
			foreach (ContentItem child in current.Children.WhereAccessible())
            {
                AddReferencesRecursive(child, referrers);
            }
        }
		protected ItemList CreateList()
		{
			ItemList list = new ItemList();
			list.Add(CreateOneItem<FirstItem>(1, "one", null));
			list.Add(CreateOneItem<SecondItem>(2, "two", null));
			list.Add(CreateOneItem<NonPageItem>(3, "three", null));
			return list;
		}
示例#14
0
 protected void AddReferencesRecursive(ContentItem current, ItemList referrers)
 {
     referrers.AddRange(Find.Items.Where.Detail().Eq(Item).Select());
     foreach (ContentItem child in current.GetChildren())
     {
         AddReferencesRecursive(child, referrers);
     }
 }
示例#15
0
 public static JSMEncoding CreateTestJSM2() {
   JSMEncoding result = new JSMEncoding();
   ItemList<Permutation> jsm = new ItemList<Permutation>();
   for (int i = 0; i < 6; i++)
     jsm.Add(new Permutation(PermutationTypes.Absolute, new int[] { 5, 4, 3, 2, 1, 0 }));
   result.JobSequenceMatrix = jsm;
   return result;
 }
示例#16
0
 //longest processing time    
 private Task LPTRule(ItemList<Task> tasks) {
   Task currentResult = RandomRule(tasks);
   foreach (Task t in tasks) {
     if (t.Duration > currentResult.Duration)
       currentResult = t;
   }
   return currentResult;
 }
示例#17
0
 public FakeItem(FieldList fieldList, ID itemid, ID templateId, string itemName = DefaultitemName, string databaseName = DefaultDatabaseName)
     : base(itemid,
         new ItemData(new ItemDefinition(ID.NewID, itemName, templateId, ID.NewID),
                      Globalization.Language.Invariant, new Data.Version(1), fieldList),
         new Database(databaseName))
 {
     FakeChildren = new ItemList();
 }
示例#18
0
 public static CommonHash MessagesResponse(ItemList<MailMessageItem> messages, long total_messages, int page, string precised_time_folder)
 {
     return new CommonHash() { 
         Messages = messages, 
         TotalMessagesFiltered = total_messages, 
         Page = page,
         PrecisedTimeFolder = precised_time_folder };
 }
    protected override ItemList DoExecute()
    {
      var item = this.innerCommand.DataStorage.GetFakeItem(this.Item.ID);
      var itemList = new ItemList();

      itemList.AddRange(item.Children.Select(child => this.innerCommand.DataStorage.GetSitecoreItem(child.ID, this.Item.Language)));

      return itemList;
    }
 public ItemList ProcessShow(ShowItem si)
 {
     ItemList TheActionList = new ItemList(); 
     foreach (DownloadIdentifier di in Identifiers)
     {
         TheActionList.Add(di.ProcessShow(si));
     }
     return TheActionList;
 }
 public ItemList ProcessEpisode(ProcessedEpisode dbep, FileInfo filo)
 {
     ItemList TheActionList = new ItemList();
     foreach (DownloadIdentifier di in Identifiers)
     {
         TheActionList.Add(di.ProcessEpisode(dbep,filo));
     }
     return TheActionList;
 }
 public ItemList ProcessSeason(ShowItem si, string folder, int snum)
 {
     ItemList TheActionList = new ItemList(); 
     foreach (DownloadIdentifier di in Identifiers)
     {
         TheActionList.Add(di.ProcessSeason (si,folder,snum));
     }
     return TheActionList;
 }
		protected void AddReferencesRecursive(ContentItem current, ItemList referrers)
		{
			referrers.AddRange(Content.Search.Repository.Find(Parameter.Equal(null, Item).Detail()));
				//Find.Items.Where.Detail().Eq(Item).Select());
			foreach (ContentItem child in current.GetChildren())
			{
				AddReferencesRecursive(child, referrers);
			}
		}
示例#24
0
        public void CanCastItemList()
        {
            ItemList items = new ItemList();
            items.Add(CreateOneItem<FirstItem>(1, "one", null));
            items.Add(CreateOneItem<SecondItem>(1, "two", null));

            ItemList<FirstItem> firsts = items.Cast<FirstItem>();
            Assert.That(firsts.Count, Is.EqualTo(1));
        }
		public ItemList CreateItems(int numberOfItems)
		{
			ItemList items = new ItemList();
			for (int i = 0; i < numberOfItems; i++)
			{
				items.Add(CreateOneItem<FirstItem>(i + 1, i.ToString(), null));
			}
			return items;
		}
		public void CanRemoveTwoDuplicatesWithStaticMethod()
		{
			ContentItem item = CreateOneItem<FirstItem>(1, "one", null);
			ItemList list = new ItemList();
			list.Add(item);
			list.Add(item);
			DuplicateFilter.FilterDuplicates(list);
			Assert.AreEqual(1, list.Count);
		}
 public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
   if (move.IsInvert) {
     return PTSPEstimatedInversionMoveEvaluator.EvaluateMove(permutation,
       new InversionMove(move.Index1, move.Index2, move.Permutation), distance, realizations);
   } else {
     return PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(permutation,
       new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, realizations);
   }
 }
		public void CanRemoveTwoDuplicatesWithWithFilterInstance()
		{
			ContentItem item = CreateOneItem<FirstItem>(1, "one", null);
			ItemList list = new ItemList();
			list.Add(item);
			list.Add(item);
			DuplicateFilter filter = new DuplicateFilter();
			((ItemFilter)filter).Filter(list);
			Assert.AreEqual(1, list.Count);
		}
 public ItemList ForceUpdateSeason(DownloadIdentifier.DownloadType dt, ShowItem si, string folder, int snum)
 {
     ItemList TheActionList = new ItemList();
     foreach (DownloadIdentifier di in Identifiers)
     {
         if (dt == di.GetDownloadType())
             TheActionList.Add(di.ProcessSeason(si, folder,snum, true));
     }
     return TheActionList;
 }
示例#30
0
		public ChildGroupContainer(ContentItem parent, string title, string name, Func<IEnumerable<ContentItem>> childFactory = null)
		{
			ID = -1;
			Title = title;
			Name = name;
			Parent = parent;

			if (childFactory != null)
				Children = new ItemList(childFactory);
		}
示例#31
0
 /// <summary>
 /// ITypicalItemStorage
 /// </summary>
 public Agent PopAgent(Agent argAgent)
 {
     ItemList.Remove(argAgent);
     return(argAgent);
 }
示例#32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            // ###Items
            // Items within a transaction.
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            itemList.items.Add(new Item()
            {
                name     = "Item Name",
                currency = "USD",
                price    = "15",
                quantity = "5",
                sku      = "sku"
            });

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Details
            // Let's you specify details of a payment amount.
            var details = new Details()
            {
                tax      = "15",
                shipping = "10",
                subtotal = "75"
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = "USD",
                total    = "100", // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            var transactionList = new List <Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount      = amount,
                item_list   = itemList
            });

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a valid APIContext
            return(this.payment.Create(apiContext));
        }
示例#33
0
        public bool Execute(IDebugConsole console, params string[] args)
        {
            var window = new SS14Window {
                CustomMinimumSize = (500, 400)
            };
            var tabContainer = new TabContainer();

            window.Contents.AddChild(tabContainer);
            var scroll = new ScrollContainer();

            tabContainer.AddChild(scroll);
            //scroll.SetAnchorAndMarginPreset(Control.LayoutPreset.Wide);
            var vBox = new VBoxContainer();

            scroll.AddChild(vBox);

            var progressBar = new ProgressBar {
                MaxValue = 10, Value = 5
            };

            vBox.AddChild(progressBar);

            var optionButton = new OptionButton();

            optionButton.AddItem("Honk");
            optionButton.AddItem("Foo");
            optionButton.AddItem("Bar");
            optionButton.AddItem("Baz");
            optionButton.OnItemSelected += eventArgs => optionButton.SelectId(eventArgs.Id);
            vBox.AddChild(optionButton);

            var tree = new Tree {
                SizeFlagsVertical = Control.SizeFlags.FillExpand
            };
            var root = tree.CreateItem();

            root.Text = "Honk!";
            var child = tree.CreateItem();

            child.Text = "Foo";
            for (var i = 0; i < 20; i++)
            {
                child      = tree.CreateItem();
                child.Text = $"Bar {i}";
            }

            vBox.AddChild(tree);

            var rich    = new RichTextLabel();
            var message = new FormattedMessage();

            message.AddText("Foo\n");
            message.PushColor(Color.Red);
            message.AddText("Bar");
            message.Pop();
            rich.SetMessage(message);
            vBox.AddChild(rich);

            var itemList = new ItemList();

            tabContainer.AddChild(itemList);
            for (var i = 0; i < 10; i++)
            {
                itemList.AddItem(i.ToString());
            }

            var grid = new GridContainer {
                Columns = 3
            };

            tabContainer.AddChild(grid);
            for (var y = 0; y < 3; y++)
            {
                for (var x = 0; x < 3; x++)
                {
                    grid.AddChild(new Button
                    {
                        CustomMinimumSize = (50, 50),
                        Text = $"{x}, {y}"
                    });
        public Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            itemList.items.Add(new Item()
            {
                name     = "el hamra",
                currency = "USD",
                price    = "1500",
                quantity = "1",
                sku      = "sku"
            });

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax      = "0",
                shipping = "0",
                subtotal = "1500"
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total    = "1500", // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            var transactionList = new List <Transaction>();

            transactionList.Add(new Transaction()
            {
                description    = "Transaction description.",
                invoice_number = "your invoice number",
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
示例#35
0
        public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList <BoolArray> realizations, CancellationToken cancellation)
        {
            var distanceM = (DistanceMatrix)distances;
            Func <int, int, double> distance = (a, b) => distanceM[a, b];

            for (var i = localIterations.Value; i < maxIterations; i++)
            {
                TranslocationMove bestMove    = null;
                double            bestQuality = 0; // we have to make an improvement, so 0 is the baseline
                double            evaluations = 0.0;
                foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment))
                {
                    double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
                    evaluations += realizations.Count * 6.0 / (assignment.Length * assignment.Length);
                    if (maximization && moveQuality > bestQuality ||
                        !maximization && moveQuality < bestQuality)
                    {
                        bestQuality = moveQuality;
                        bestMove    = move;
                    }
                }
                evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
                if (bestMove == null)
                {
                    break;
                }
                TranslocationManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2, bestMove.Index3);
                quality.Value += bestQuality;
                localIterations.Value++;
                cancellation.ThrowIfCancellationRequested();
            }
        }
示例#36
0
 // Start is called before the first frame update
 void Start()
 {
     itemGenList = itemGenerator.GetComponent <ItemList>();
 }
示例#37
0
        private void BtnOpenInExcel_Click(object sender, RoutedEventArgs e)
        {
            ItemList i = new ItemList();

            i.SaveToDisk();
        }
        public ActionResult PayPalPayment(string UserId)
        {
            try
            {
                var    apiContext = PaypalConfiguration.GetAPIContext();
                string payerId    = Request.Params["PayerID"];
                if (string.IsNullOrEmpty(payerId))
                {
                    //Get Items From Session Storage
                    var itemList = new ItemList()
                    {
                        items = Session["CartList"] as List <Item>
                    };

                    //Return To Cart If He Doest Have Anything In Cart
                    if (itemList.items == null)
                    {
                        return(View("Index"));
                    }


                    var payer = new Payer()
                    {
                        payment_method = "paypal"
                    };

                    var baseURI     = Request.Url.Scheme + "://" + Request.Url.Authority + "/PayPal/PayPalPayment?";
                    var guid        = Convert.ToString((new Random()).Next(100000));
                    var redirectUrl = baseURI + "guid=" + guid;
                    var redirUrls   = new RedirectUrls()
                    {
                        cancel_url = redirectUrl + "&cancel=true",
                        return_url = redirectUrl
                    };

                    var details = new Details()
                    {
                        tax      = "0",
                        shipping = "0",
                        subtotal = itemList.items.Select(x => int.Parse(x.price) * int.Parse(x.quantity)).Sum().ToString()// Based on item prices by quantities
                    };

                    var amount = new Amount()
                    {
                        currency = "USD",
                        total    = itemList.items.Select(x => int.Parse(x.price) * int.Parse(x.quantity)).Sum().ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                        details  = details
                    };

                    var transactionList = new List <Transaction>();
                    transactionList.Add(new Transaction()
                    {
                        description    = "Transaction description.",
                        invoice_number = PaypalCommonTools.GetRandomInvoiceNumber(),
                        amount         = amount,
                        item_list      = itemList
                    });

                    var payment = new Payment()
                    {
                        intent        = "sale",
                        payer         = payer,
                        transactions  = transactionList,
                        redirect_urls = redirUrls
                    };
                    var createdPayment = payment.Create(apiContext);
                    var links          = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);
                    Session.Add("UserId", UserId);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This function exectues after receving all parameters for the payment

                    var guid             = Request.Params["guid"];
                    var paymentId        = Session[guid] as string;
                    var paymentExecution = new PaymentExecution()
                    {
                        payer_id = payerId
                    };
                    var payment = new Payment()
                    {
                        id = paymentId
                    };

                    var executedPayment = payment.Execute(apiContext, paymentExecution);

                    //If executed payment failed then we will show payment failure message to user
                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
                return(View("FailureView"));
            }



            //Get Email Of Logged in User
            string userid = Session["UserId"] as string;
            var    user   = db.Users.Where(x => x.Id == userid).FirstOrDefault();

            //Send Email With Painting On Success Payment to User Email
            //Get ids from decription and give them as a list of strings
            List <Item> CartList = Session["CartList"] as List <Item>;

            SendEmail(user.Email, CartList.Select(x => x.description).ToList());

            //Will use method below to return a sale and then the ServiceSale
            //will send this obj to WebApi project
            ServiceSale.CreateSale(CreateSaleObj(CartList));



            //Empty Session Storage From Cart Items On Success Payment
            Session["CartList"] = null;

            //on successful payment, show success page to user.
            return(View("Index"));
        }
示例#39
0
 public ItemListHoverEventArgs(int itemIndex, ItemList list) : base(list)
 {
     ItemIndex = itemIndex;
 }
示例#40
0
 public ItemListDeselectedEventArgs(int itemIndex, ItemList list) : base(list)
 {
     ItemIndex = itemIndex;
 }
示例#41
0
 public ItemListEventArgs(ItemList list)
 {
     ItemList = list;
 }
示例#42
0
 public void TestConstructor()
 {
     Assert.Equal(2, ItemList.Count());
 }
示例#43
0
        public async Task <IActionResult> ThanhToanPaypal()
        {
            var model = _context.loais.ToList();

            ViewBag.model = model;

            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            var environment = new SandboxEnvironment(_clientId, _secretKey);
            var client      = new PayPalHttpClient(environment);

            #region Create Paypal Order
            var cart     = SessionHelper.Get <List <Item> >(HttpContext.Session, "cart");
            var itemList = new ItemList()
            {
                Items = new List <item>()
            };
            //var total = Math.Round(cart.Sum(item => (item.Product.DonGia * item.Quantity) - ((item.Product.GiamGia) * (item.Product.DonGia)) / 100) / tyGiaUSD, 2);
            var total = cart.Sum(item => Math.Round(Math.Round(item.Product.DonGia / tyGiaUSD, 2) - Math.Round(Math.Round(item.Product.DonGia / tyGiaUSD, 2) * item.Product.GiamGia / 100, 2), 2) * item.Quantity);
            var giam  = Math.Round(cart.Sum(item => Math.Round(Math.Round(item.Product.DonGia / tyGiaUSD, 2) * item.Quantity * item.Product.GiamGia / 100, 2)), 2);
            //var total = Math.Round(sub - giam, 2);
            foreach (var item in cart)
            {
                itemList.Items.Add(new item()
                {
                    Name     = item.Product.TenHH,
                    Currency = "USD",
                    Price    = Math.Round(Math.Round(item.Product.DonGia / tyGiaUSD, 2) - Math.Round(Math.Round(item.Product.DonGia / tyGiaUSD, 2) * item.Product.GiamGia / 100, 2), 2).ToString(),
                    Quantity = item.Quantity.ToString(),
                    Sku      = "sku",
                    Tax      = "0"
                });
            }
            #endregion


            var paypalOrderId = DateTime.Now.Ticks;
            var hostname      = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
            var payment       = new Payment()
            {
                Intent       = "sale",
                Transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        Amount = new Amount()
                        {
                            Total    = total.ToString(),
                            Currency = "USD",
                            Details  = new AmountDetails
                            {
                                Tax      = "0",
                                Shipping = "0",
                                Subtotal = total.ToString()
                            }
                        },
                        ItemList      = itemList,
                        Description   = $"Invoice #{paypalOrderId}",
                        InvoiceNumber = paypalOrderId.ToString(),
                        Payee         = new Payee()
                        {
                            Email      = _email,
                            MerchantId = _merchantId
                        }
                    }
                },
                RedirectUrls = new RedirectUrls()
                {
                    CancelUrl = $"{hostname}/cart/that-bai",
                    ReturnUrl = $"{hostname}/cart/paypal-hoan-thanh"
                },
                Payer = new Payer()
                {
                    PaymentMethod = "paypal"
                }
            };

            #region Insert Order to Database
            var oder = new Oder();
            oder.ID           = paypalOrderId;
            oder.ShipAddress  = "Paypal User";
            oder.ShipName     = "Paypal User";
            oder.ShipMobile   = "Paypal User";
            oder.ShipEmail    = "Paypal User";
            oder.CheckOutType = "Paypal";
            oder.CustomerID   = user.Id;
            oder.CreatedDate  = DateTime.Now;

            var subTotal = cart.Sum(item => (item.Product.DonGia - item.Product.DonGia * item.Product.GiamGia / 100) * item.Quantity);

            oder.Total = Math.Round(subTotal, 0);

            _orderId = oder.ID;
            SessionHelper.Set(HttpContext.Session, "orderId", _orderId);

            try
            {
                var id = Insert(oder);
                foreach (var item in cart)
                {
                    var oderDetail = new OderDetail();
                    oderDetail.MaHH     = item.Product.MaHH;
                    oderDetail.OderID   = id;
                    oderDetail.Gia      = item.Product.DonGia;
                    oderDetail.Quantity = item.Quantity;
                    Insert1(oderDetail);

                    var hanghoas = _context.HangHoas.Where(x => x.MaHH == item.Product.MaHH).First();

                    hanghoas.DaMua += item.Quantity;
                    _context.Update(hanghoas);
                    _context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Console.Write(e);
                return(View("ThatBai"));
            }
            #endregion
            PaymentCreateRequest request = new PaymentCreateRequest();
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var     statusCode = response.StatusCode;
                Payment result     = response.Result <Payment>();

                var    links             = result.Links.GetEnumerator();
                string paypalRedirectUrl = null;
                while (links.MoveNext())
                {
                    LinkDescriptionObject lnk = links.Current;
                    if (lnk.Rel.ToLower().Trim().Equals("approval_url"))
                    {
                        paypalRedirectUrl = lnk.Href;
                    }
                }

                return(Redirect(paypalRedirectUrl));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();

                return(Redirect("/cart/that-bai"));
            }
        }
示例#44
0
 private void GetRank()
 {
     try
     {
         List <OpenLottery> openHistory = BoCaiManager.getInstance().GetNewOpenLottery10(this.BoCaiType);
         if (null != openHistory)
         {
             ReturnValue <List <KFBoCaoHistoryData> > msgData = TcpCall.KFBoCaiManager.GetWinHistory(this.BoCaiType);
             if (!msgData.IsReturn)
             {
                 LogManager.WriteLog(LogTypes.Error, "[ljl_caidaxiao_猜数字]猜数字获取排行 失败", null, true);
             }
             else
             {
                 List <KFBoCaoHistoryData> History = msgData.Value;
                 lock (this.mutex)
                 {
                     this.RankResult  = true;
                     this.OpenHistory = openHistory;
                     this.WinHistory.Clear();
                     if (null != History)
                     {
                         using (List <KFBoCaoHistoryData> .Enumerator enumerator = History.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 KFBoCaoHistoryData item = enumerator.Current;
                                 OpenLottery        data = this.OpenHistory.Find((OpenLottery x) => x.DataPeriods == item.DataPeriods);
                                 if (data != null && !string.IsNullOrEmpty(data.strWinNum))
                                 {
                                     item.OpenData = data.strWinNum;
                                     this.WinHistory.Add(item);
                                 }
                             }
                         }
                         List <long> DataPeriodsList  = new List <long>();
                         List <long> DataPeriodsList2 = new List <long>();
                         foreach (OpenLottery open in this.OpenHistory)
                         {
                             DataPeriodsList.Add(open.DataPeriods);
                         }
                         DataPeriodsList2 = this.BuyItemHistoryDict.Keys.ToList <long>();
                         using (List <long> .Enumerator enumerator3 = DataPeriodsList2.GetEnumerator())
                         {
                             while (enumerator3.MoveNext())
                             {
                                 long Periods = enumerator3.Current;
                                 if (DataPeriodsList.Find((long x) => x == Periods) < 1L)
                                 {
                                     this.BuyItemHistoryDict.Remove(Periods);
                                 }
                             }
                         }
                         foreach (long Periods2 in DataPeriodsList)
                         {
                             if (!this.BuyItemHistoryDict.ContainsKey(Periods2))
                             {
                                 List <BuyBoCai2SDB> ItemList;
                                 if (BoCaiManager.getInstance().GetBuyList2DB(this.BoCaiType, Periods2, out ItemList, 1))
                                 {
                                     List <RoleBuyHistory> roleBuyList = new List <RoleBuyHistory>();
                                     using (List <BuyBoCai2SDB> .Enumerator enumerator4 = ItemList.GetEnumerator())
                                     {
                                         while (enumerator4.MoveNext())
                                         {
                                             BuyBoCai2SDB   dbdata   = enumerator4.Current;
                                             RoleBuyHistory roledata = roleBuyList.Find((RoleBuyHistory x) => x.RoleID == dbdata.m_RoleID);
                                             if (null == roledata)
                                             {
                                                 roledata             = new RoleBuyHistory();
                                                 roledata.RoleID      = dbdata.m_RoleID;
                                                 roledata.BuyItemList = new List <BoCaiBuyItem>();
                                                 roleBuyList.Add(roledata);
                                             }
                                             roledata.BuyItemList.Add(new BoCaiBuyItem
                                             {
                                                 BuyNum      = dbdata.BuyNum,
                                                 strBuyValue = dbdata.strBuyValue,
                                                 DataPeriods = Periods2
                                             });
                                         }
                                     }
                                     this.BuyItemHistoryDict.Add(Periods2, roleBuyList);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         LogManager.WriteLog(LogTypes.Exception, string.Format("[ljl_caidaxiao_猜数字]{0}", ex.ToString()), null, true);
     }
 }
示例#45
0
 /// <summary>
 /// ITypicalItemStorage
 /// </summary>
 public Agent GetAgentByType(Type agentType)
 {
     return(ItemList.Find(ag => { return ag.GetType() == agentType; }));
 }
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, List <ChiTietHoaDon> listCthd)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            int?tong = 0;

            foreach (var sp in listCthd)
            {
                itemList.items.Add(new Item()
                {
                    name     = db.DongHoes.Find(sp.MaDH).TenDH,
                    currency = "USD",
                    price    = (db.DongHoes.Find(sp.MaDH).GiaBan / 23000).ToString(),
                    quantity = sp.SoLuong.ToString(),
                    sku      = "sku"
                });
                tong += (db.DongHoes.Find(sp.MaDH).GiaBan / 23000) * sp.SoLuong;
            }

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax      = "0",
                shipping = "1",
                subtotal = tong.ToString()
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total    = (tong + 1).ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            var transactionList = new List <Transaction>();

            transactionList.Add(new Transaction()
            {
                description    = "Transaction description.",
                invoice_number = new Random().Next(100000).ToString(),
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
 /// <summary>
 /// BrandOrOrganization as a Brand.
 /// </summary>
 /// <param name="itemList">BrandOrOrganization as a Brand.</param>
 public AnswerOrItemList(ItemList itemList)
 {
     AsItemList = itemList;
 }
示例#48
0
 /// <summary>
 /// ITypicalItemStorage
 /// </summary>
 public bool ExistsAgentByType(Type argType)
 {
     return(ItemList.Exists(ag => { return ag.GetType() == argType; }));
 }
        public override IOperation Apply()
        {
            IEnumerable <int> rows = GenerateRowsToEvaluate();

            if (!rows.Any())
            {
                return(base.Apply());
            }

            var results = ResultCollection;

            // create empty parameter and result values
            if (ValidationBestSolutions == null)
            {
                ValidationBestSolutions         = new ItemList <S>();
                ValidationBestSolutionQualities = new ItemList <DoubleArray>();
                results.Add(new Result(ValidationBestSolutionQualitiesParameter.Name, ValidationBestSolutionQualitiesParameter.Description, ValidationBestSolutionQualities));
                results.Add(new Result(ValidationBestSolutionsParameter.Name, ValidationBestSolutionsParameter.Description, ValidationBestSolutions));
            }

            //if the pareto front of best solutions shall be updated regardless of the quality, the list initialized empty to discard old solutions
            IList <double[]> trainingBestQualities;

            if (UpdateAlways.Value)
            {
                trainingBestQualities = new List <double[]>();
            }
            else
            {
                trainingBestQualities = ValidationBestSolutionQualities.Select(x => x.ToArray()).ToList();
            }

            #region find best trees
            IList <int> nonDominatedIndexes            = new List <int>();
            ISymbolicExpressionTree[] tree             = SymbolicExpressionTree.ToArray();
            bool[]            maximization             = Maximization.ToArray();
            List <double[]>   newNonDominatedQualities = new List <double[]>();
            var               evaluator    = EvaluatorParameter.ActualValue;
            var               problemData  = ProblemDataParameter.ActualValue;
            IExecutionContext childContext = (IExecutionContext)ExecutionContext.CreateChildOperation(evaluator);

            var qualities = tree
                            .Select(t => evaluator.Evaluate(childContext, t, problemData, rows))
                            .ToArray();
            for (int i = 0; i < tree.Length; i++)
            {
                if (IsNonDominated(qualities[i], trainingBestQualities, maximization) &&
                    IsNonDominated(qualities[i], qualities, maximization))
                {
                    if (!newNonDominatedQualities.Contains(qualities[i], new DoubleArrayComparer()))
                    {
                        newNonDominatedQualities.Add(qualities[i]);
                        nonDominatedIndexes.Add(i);
                    }
                }
            }
            #endregion
            #region update Pareto-optimal solution archive
            if (nonDominatedIndexes.Count > 0)
            {
                ItemList <DoubleArray> nonDominatedQualities = new ItemList <DoubleArray>();
                ItemList <S>           nonDominatedSolutions = new ItemList <S>();
                // add all new non-dominated solutions to the archive
                foreach (var index in nonDominatedIndexes)
                {
                    S solution = CreateSolution(tree[index], qualities[index]);
                    nonDominatedSolutions.Add(solution);
                    nonDominatedQualities.Add(new DoubleArray(qualities[index]));
                }
                // add old non-dominated solutions only if they are not dominated by one of the new solutions
                for (int i = 0; i < trainingBestQualities.Count; i++)
                {
                    if (IsNonDominated(trainingBestQualities[i], newNonDominatedQualities, maximization))
                    {
                        if (!newNonDominatedQualities.Contains(trainingBestQualities[i], new DoubleArrayComparer()))
                        {
                            nonDominatedSolutions.Add(ValidationBestSolutions[i]);
                            nonDominatedQualities.Add(ValidationBestSolutionQualities[i]);
                        }
                    }
                }

                results[ValidationBestSolutionsParameter.Name].Value         = nonDominatedSolutions;
                results[ValidationBestSolutionQualitiesParameter.Name].Value = nonDominatedQualities;
            }
            #endregion
            return(base.Apply());
        }
示例#50
0
 /// <summary>
 /// ITypicalItemStorage
 /// </summary>
 public Agent PopAgentByType(Type argType)
 {
     return(PopAgent(ItemList.Find(ag => { return ag.GetType() == argType; })));
 }
示例#51
0
 public Resource(int index)
     : base()
 {
     Index = index;
     Tasks = new ItemList <ScheduledTask>();
 }
 private void ItemList_Loaded(object sender, System.Windows.RoutedEventArgs e)
 {
     ItemList.Focus();
 }
        public ActionResult PaymentWithCreditCard()
        {
            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object
            Item item = new Item();

            item.name     = "Demo Item";
            item.currency = "USD";
            item.price    = "5";
            item.quantity = "1";
            item.sku      = "sku";

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List <Item> itms = new List <Item>();

            itms.Add(item);
            ItemList itemList = new ItemList();

            itemList.items = itms;

            //Address for the payment
            Address billingAddress = new Address();

            billingAddress.city         = "NewYork";
            billingAddress.country_code = "US";
            billingAddress.line1        = "23rd street kew gardens";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "NY";


            //Now Create an object of credit card and add above details to it
            //Please replace your credit card details over here which you got from paypal
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = "874"; //card cvv2 number
            crdtCard.expire_month    = 1;     //card expire date
            crdtCard.expire_year     = 2020;  //card expire year
            crdtCard.first_name      = "Aman";
            crdtCard.last_name       = "Thakur";
            crdtCard.number          = "1234567890123456"; //enter your credit card number here
            crdtCard.type            = "visa";             //credit card type here paypal allows 4 types

            // Specify details of your payment amount.
            Details details = new Details();

            details.shipping = "1";
            details.subtotal = "5";
            details.tax      = "1";

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total = shipping tax + subtotal.
            amnt.total   = "7";
            amnt.details = details;

            // Now make a transaction object and assign the Amount object
            Transaction tran = new Transaction();

            tran.amount         = amnt;
            tran.description    = "Description about the payment amount.";
            tran.item_list      = itemList;
            tran.invoice_number = "your invoice number which you are generating";

            // Now, we have to make a list of transaction and add the transactions object
            // to this list. You can create one or more object as per your requirements

            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

            // Now we need to specify the FundingInstrument of the Payer
            // for credit card payments, set the CreditCard which we made above

            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();

            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method      = "credit_card";

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment();

            pymnt.intent       = "sale";
            pymnt.payer        = payr;
            pymnt.transactions = transactions;

            try
            {
                //getting context from the paypal
                //basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment
                //for which we have created the object above.

                //Basically, apiContext object has a accesstoken which is sent by the paypal
                //to authenticate the payment to facilitator account.
                //An access token could be an alphanumeric string

                APIContext apiContext = Configuration.GetAPIContext();

                //Create is a Payment class function which actually sends the payment details
                //to the paypal API for the payment. The function is passed with the ApiContext
                //which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.state is "approved" it means the payment was successful else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return(View("FailureView"));
                }
            }
            catch (PayPal.PayPalException ex)
            {
                //Logger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
示例#54
0
        /// <summary>
        /// Code example for creating a future payment object.
        /// </summary>
        /// <param name="correlationId"></param>
        /// <param name="authorizationCode"></param>
        private Payment CreateFuturePayment(string correlationId, string authorizationCode, string redirectUrl)
        {
            // ###Payer
            // A resource representing a Payer that funds a payment
            // Payment Method
            // as `paypal`
            Payer payer = new Payer()
            {
                payment_method = "paypal"
            };

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details()
            {
                tax      = "15",
                shipping = "10",
                subtotal = "75"
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = "USD",
                total    = "100", // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            // # Redirect URLS
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // ###Items
            // Items within a transaction.
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            itemList.items.Add(new Item()
            {
                name     = "Item Name",
                currency = "USD",
                price    = "15",
                quantity = "5",
                sku      = "sku"
            });

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            var transactionList = new List <Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount      = amount,
                item_list   = itemList
            });

            var authorizationCodeParameters = new CreateFromAuthorizationCodeParameters();

            authorizationCodeParameters.setClientId(Configuration.ClientId);
            authorizationCodeParameters.setClientSecret(Configuration.ClientSecret);
            authorizationCodeParameters.SetCode(authorizationCode);

            var apiContext = new APIContext();

            apiContext.Config = Configuration.GetConfig();

            var tokenInfo   = Tokeninfo.CreateFromAuthorizationCodeForFuturePayments(apiContext, authorizationCodeParameters);
            var accessToken = string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token);

            // ###Payment
            // A FuturePayment Resource
            this.futurePayment = new FuturePayment()
            {
                intent        = "authorize",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            return(this.futurePayment.Create(accessToken, correlationId));
        }
 private void CancelButton_Click(object sender, System.EventArgs e)
 {
     selectedUsersAndGroups = lightweightUserGroupSelectionView.GetSelectedItems();
     this.DialogResult      = System.Windows.Forms.DialogResult.Cancel;
     Close();
 }
示例#56
0
 // Start is called before the first frame update
 void Start()
 {
     gold = 0;
     list = ItemList.instance;
 }
 public CovarianceProduct()
     : base()
 {
     this.factors = new ItemList <ICovarianceFunction>();
 }
示例#58
0
 protected void ItemList_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
 {
     ItemList.PageIndex = e.NewPageIndex;
     ItemList.DataBind();
 }
示例#59
0
        // Create a payment using an APIContext
        private Payment CreatePayment(APIContext apiContext, string redirectUrl, Models.Order order) // OM: add order
        {
            // similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            // OM: find price of each item exclusively, and of each item * quantity in order to find the total price
            var            carts       = db.Carts.Where(x => x.CartID == User.Identity.Name).ToList();
            List <decimal> price       = new List <decimal>();
            List <decimal> totalPrices = new List <decimal>();
            int            count       = 0;

            foreach (var item in carts)
            {
                price.Add(item.Product.Price);
                itemList.items.Add(new Item()
                {
                    name     = item.Product.Name,
                    price    = price[count].ToString(),
                    quantity = item.Quantity.ToString(),
                    currency = "EUR",
                    sku      = item.ProductID.ToString()
                });
                totalPrices.Add(price[count] * item.Quantity);
                count++;
            }

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // OM: get total price of items in cart
            var total = totalPrices.Sum();
            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                //tax = "1",
                //shipping = "1",
                subtotal = total.ToString()
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "EUR",
                total    = total.ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            // OM: invoice number must be unique. Unique to the paypal sandbox account that is
            // so let's give it a huge random string and hope for the best
            var invoice = GetInvoice();

            var transactionList = new List <Transaction>();

            transactionList.Add(new Transaction()
            {
                description    = "sales",
                invoice_number = order.ID.ToString() + invoice,
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using an APIContext
            return(this.payment.Create(apiContext));
        }
示例#60
0
 protected Resource(Resource original, Cloner cloner)
     : base(original, cloner)
 {
     this.Index = original.Index;
     this.Tasks = cloner.Clone(original.Tasks);
 }