Exemple #1
0
        public void AddPlayerPurchase(List <MarketList> PublicMarketItems, MarketList Item, ulong ID)
        {
            Dictionary <ulong, int> Players = Item.PlayerPurchases;

            //Added player to list
            if (Players.TryGetValue(ID, out int value))
            {
                Players[ID] = value + 1;
            }
            else
            {
                //No value for player. Add
                Players.Add(ID, 1);
            }



            for (int i = 0; i < PublicMarketItems.Count(); i++)
            {
                if (PublicMarketItems[i].Name == Item.Name)
                {
                    //Re-apply new dictionary
                    PublicMarketItems[i].PlayerPurchases = Players;
                    return;
                }
            }
        }
Exemple #2
0
 private void btnCreateMarket_Click(object sender, EventArgs e)
 {
     try
     {
         var markets = db.MarketList.Any(w => w.DeletedDate == null && w.UserId == activeUser.Id && w.MarketName == txtMarketName.Text);
         if (string.IsNullOrWhiteSpace(txtMarketName.Text))
         {
             MessageBox.Show("Zəhmət olmasa Market adı daxil edin!!");
             return;
         }
         if (markets)
         {
             MessageBox.Show("Bu adda market mövcuddur!!");
             return;
         }
         var        marketName = txtMarketName.Text.ToUpper();
         MarketList newMarket  = new MarketList();
         newMarket.MarketName  = marketName;
         newMarket.UserId      = activeUser.Id;
         newMarket.CreatedDate = DateTime.Now;
         db.MarketList.Add(newMarket);
         db.SaveChanges();
         dgvMarket(activeUser);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Please, check again after some minutes!! ");
         File.AppendAllText(pathTxt, "\n" + ex + ":" + DateTime.Now);
     }
 }
Exemple #3
0
 /// <summary>
 /// Adds the products.
 /// </summary>
 /// <param name="index">The index.</param>
 /// <param name="count">The count.</param>
 private void AddProducts(int index, int count)
 {
     for (int i = index; i < index + count; i++)
     {
         MarketList.Add(tempMarketList[i]);
     }
 }
Exemple #4
0
    public new static MarketList ot_dynamic_cast(Storable pObject)
    {
        IntPtr     cPtr = otapiPINVOKE.MarketList_ot_dynamic_cast(Storable.getCPtr(pObject));
        MarketList ret  = (cPtr == IntPtr.Zero) ? null : new MarketList(cPtr, false);

        return(ret);
    }
        public OrdersVM(OrderManagerModel model)
        {
            this.model = model;
            model.OrderUpdateSuccess += this.UpdateResultsSuccess;
            model.OrderUpdateFailed  += this.UpdateResultsFailed;
            updaterVM = new UpdaterVM(model.UpdaterModel);


            States = new ObservableCollection <OrderState>()
            {
                new OrderState(OrderStates.Open),
                new OrderState(OrderStates.Export),
                new OrderState(OrderStates.Archive),
                new OrderState(OrderStates.ShipReady),
                new OrderState(OrderStates.Shipped),
                new OrderState(OrderStates.Service),
                new OrderState(OrderStates.OnHold),
                new OrderState(OrderStates.ASAP),
                new OrderState(OrderStates.Cancelled),
                new OrderState(OrderStates.Reorders)
            };

            StatesList = new ObservableCollection <string>(model.StringStates);

            MarketList.Add("Amazon US");
            MarketList.Add("Amazon CA");
            MarketList.Add("Amazon UK");
            MarketList.Add("Website");
            MarketList.Add("eBay");

            SelectedState         = States[(int)OrderStates.Open];
            this.PropertyChanged += OrdersVM_PropertyChanged;
        }
Exemple #6
0
 private void Awake()
 {
     PlayerPrefs.SetInt("MarketListStep", 0);
     ShoppingList   = GameObject.Find("ShoppingList");
     instance       = this;
     marketStands   = GameObject.FindGameObjectsWithTag("Selection");
     cameraPosition = Camera.main.transform.position;
 }
Exemple #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         // Get all markets and bind to repeater.
         var listMarket = _marketService.GetAllMarkets().Where(m => m.IsEnabled);
         MarketList.DataSource = listMarket;
         MarketList.DataBind();
     }
 }
        [AllowAnonymous] //TODO: Verificar autorizacao
        public async Task <ActionResult <MarketList> > Post([FromServices] DataContext context,
                                                            [FromBody] MarketList model)
        {
            if (ModelState.IsValid)
            {
                context.MarketLists.Add(model);
                await context.SaveChangesAsync();

                return(model);
            }

            return(BadRequest());
        }
Exemple #9
0
        public void Init()
        {
            Accounts.Init();

            // Open websocket connection to get Market lists for all accounts
            Task.Run(() => Bws.Connect()).Wait();
            Task.Run(() => Bws.SendRequest("{\"trading_times\":\"2015-09-14\"}")).Wait();
            var jsonTradingTimesResponse = Task.Run(() => Bws.StartListen()).Result;
            var tradingTime = JsonConvert.DeserializeObject <TradingTimesResponse>(jsonTradingTimesResponse);

            foreach (var market in tradingTime.trading_times.markets)
            {
                MarketList.Add(new MarketSubmarket(market));
                foreach (var submarket in market.submarkets)
                {
                    MarketList.Add(new MarketSubmarket(submarket));
                }
            }
            SelectedMarket = MarketList[0];
        }
Exemple #10
0
        static string market(SNode start)
        {
            StringBuilder     sb = new StringBuilder();
            MarketOrderParser mp = new MarketOrderParser(start);

            try
            {
                mp.Parse();
            }
            catch (ParseException e)
            {
                sb.Append("Not a valid orders file due to " + e.Message);
                return(null);
            }
            MarketList list = mp.List;

            DateTime t = list.TimeStamp;

            string timeString = t.ToString("yyyy-MM-dd HH:mm:ss");

            sb.Append("MarketList for region " + list.Region + " and type " + list.Type +
                      " at time " + timeString + "\n");

            sb.Append("price,volRemaining,typeID,range,orderID,volEntered,minVolume,bid,issued,duration,stationID,regionID,solarSystemID,jumps,\n");

            List <MarketOrder> buy  = list.BuyOrders;
            List <MarketOrder> sell = list.SellOrders;

            foreach (MarketOrder o in sell)
            {
                sb.Append(o.ToCsv() + "\n");
            }
            foreach (MarketOrder o in buy)
            {
                sb.Append(o.ToCsv() + "\n");
            }
            return(sb.ToString());
        }
Exemple #11
0
        private void UpdatePublicOffers()
        {
            //Update all public offer market items!
            if (!Hangar.IsRunning)
            {
                return;
            }

            //Need to remove existing ones

            string PublicOfferPath = Plugin.Market.ServerOffersDir;

            //Clear list
            GridMarket.PublicOfferseGridList.Clear();


            foreach (PublicOffers offer in Plugin.Config.PublicOffers)
            {
                if (offer.Forsale && (offer.Name != null || offer.Name != ""))
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");
                    Hangar.Debug("Blueprint Path: " + GridFilePath);

                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;


                    NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    NewList.NumberofBlocks   = stamp.NumberofBlocks;
                    NewList.SmallGrids       = stamp.SmallGrids;
                    NewList.LargeGrids       = stamp.LargeGrids;
                    NewList.BlockTypeCount   = stamp.BlockTypeCount;


                    //Need to setTotalBuys
                    GridMarket.PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }


            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = GridMarket.PublicOfferseGridList;

            //Write to file
            FileSaver.Save(Plugin.Market.ServerMarketFileDir, Data);
            //File.WriteAllText(Main.ServerMarketFileDir, JsonConvert.SerializeObject(Data));
            //This will force the market to update the market items
        }
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(MarketList obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemple #13
0
        public void PurchaseGrid(GridsForSale grid)
        {
            //Need to check hangar of the person who bought the grid

            if (!Config.GridMarketEnabled)
            {
                return;
            }
            //Get Item from market list for price
            MarketList Item = null;

            List <MarketList> Allitems = new List <MarketList>();

            //Incluse all offers!
            Allitems.AddRange(GridList);
            Allitems.AddRange(PublicOfferseGridList);


            try
            {
                Item = Allitems.First(x => x.Name == grid.name);
            }
            catch
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Grid has been removed from market!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }


            MyPlayer.PlayerId BuyPlayer = new MyPlayer.PlayerId(grid.BuyerSteamid);
            MySession.Static.Players.TryGetPlayerById(BuyPlayer, out MyPlayer Buyer);

            GridMethods BuyerMethods = new GridMethods(grid.BuyerSteamid, Config.FolderDirectory);

            //string BuyerPath = GridMethods.CreatePathForPlayer(Config.FolderDirectory, grid.BuyerSteamid);

            if (Buyer == null)
            {
                Hangar.Debug("Unable to get steamID. Glitched player?");
                return;
                //Some kind of error message directed to player.
            }

            //Debug("Seller SteamID: " + Item.Steamid);
            MyCharacter Player = Buyer.Character;

            Hangar.Debug("Player Buying grid: " + Player.DisplayName + " [" + grid.BuyerSteamid + "]");

            //Start transfer of grids!
            int MaxStorage = Config.NormalHangarAmount;

            if (Player.PromoteLevel >= MyPromoteLevel.Scripter)
            {
                MaxStorage = Config.ScripterHangarAmount;
            }

            PlayerInfo BuyerData = new PlayerInfo();

            //Get PlayerInfo from file
            try
            {
                BuyerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json")));
                if (BuyerData.Grids.Count >= MaxStorage)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! No room in hangar!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }
            }
            catch
            {
                Hangar.Debug("Buyer doesnt have anything stored in their hangar! THIS IS NOT AN ERROR!");
                //ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", MyFontEnum.Red, grid.BuyerSteamid);
                //Debug("Deserialization error! Make sure files exist! \n" + e);
                //New player. Go ahead and create new. Should not have a timer.
            }



            //Adjust player prices (We need to check if buyer has enough moneyies hehe)
            bool RetrieveSuccessful = Utils.TryGetPlayerBalance(grid.BuyerSteamid, out long BuyerBallance);

            if (!RetrieveSuccessful || BuyerBallance < Item.Price)
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! Not enough credits!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }



            string NewGridName    = Item.Name;
            bool   FileStilExists = true;
            int    i = 0;

            if (File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc")))
            {
                while (FileStilExists)
                {
                    i++;
                    if (!File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + "[" + i + "].sbc")))
                    {
                        FileStilExists = false;
                    }
                    //Turns out there is already a ship with that name in this players hangar!
                    if (i > 50)
                    {
                        _ChatManager.SendMessageAsOther("GridMarket", "Dude what the actual f**k do you need 50 of these for?", VRageMath.Color.Yellow, grid.BuyerSteamid);
                        Hangar.Debug("Dude what the actual f**k do you need 50 of these for? Will not continue due to... security reasons. @" + NewGridName);
                        return;
                    }
                }

                NewGridName = NewGridName + "[" + i + "]";
            }



            if (Item.Steamid == 0)
            {
                //Check to see if the item existis in the dir
                string PublicOfferPath = ServerOffersDir;
                string GridPath        = Path.Combine(PublicOfferPath, Item.Name + ".sbc");

                //Add counter just in case some idiot


                string BuyerGridPath = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                if (!File.Exists(GridPath))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Server Offer got manually deleted from folder! Blame admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Someone tried to buy a ship that doesnt exist! Did you delete it?? @" + GridPath);
                }

                //Need to check if player can buy
                PublicOffers Offer;
                int          Index;
                try
                {
                    Offer = Config.PublicOffers.First(x => x.Name == Item.Name);
                    Index = Config.PublicOffers.IndexOf(Offer);
                }
                catch (Exception e)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Unknown error! @" + GridPath, e, ErrorType.Fatal);
                    return;
                    //Something went wrong
                }



                if (Offer.TotalPerPlayer != 0 && !WithinPlayerLimits(Item.PlayerPurchases, grid.BuyerSteamid, Offer.TotalPerPlayer))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Youve reached your buy limit on this grid!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                //File check complete!
                Hangar.Debug("Old Buyers Balance: " + BuyerBallance);

                //Create PlayerAccount
                PlayerAccount BuyerAccount = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);


                //Need to figure out HOW to get the data in here
                GridStamp stamp = new GridStamp();
                stamp.GridForSale = false;
                stamp.GridName    = NewGridName;


                //Add it to buyers info
                File.Copy(GridPath, BuyerGridPath);
                BuyerData.Grids.Add(stamp);


                //Update ALL blocks
                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);


                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);

                MarketServers.Update(SendAccountUpdate);

                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);

                //Write all files!
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));

                Offer.NumberOfBuys++;

                if (Offer.TotalPerPlayer != 0)
                {
                    AddPlayerPurchase(PublicOfferseGridList, Item, grid.BuyerSteamid);
                }

                //Check Total Limit
                if (Offer.NumberOfBuys >= Offer.TotalAmount)
                {
                    Config.PublicOffers[Index].Forsale = false;
                    //Update offers and refresh
                    UpdatePublicOffers();
                }
            }
            else
            {
                //This is a player offer

                GridMethods SellerMethods = new GridMethods(Item.Steamid, Dir);
                //string SellerPath = GridMethods.CreatePathForPlayer(Dir, Item.Steamid);
                Debug("Seller SteamID: " + Item.Steamid);


                PlayerInfo SellerData = new PlayerInfo();


                try
                {
                    SellerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json")));
                }
                catch (Exception e)
                {
                    Hangar.Debug("Seller Hangar Playerinfo is missing! Did they get deleted by admin?", e, ErrorType.Warn);
                    _ChatManager.SendMessageAsOther("GridMarket", "Seller hangar info is missing! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RemoveItem;
                SendMessage.List.Add(Item);
                MarketServers.Update(SendMessage);


                PlayerAccount BuyerAccount  = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);
                PlayerAccount SellerAccount = new PlayerAccount(Item.Seller, Item.Steamid, Item.Price, true);



                //Get grids
                GridStamp gridsold = SellerData.Grids.FirstOrDefault(x => x.GridName == grid.name);
                //Reset grid for sale and remove it from the sellers hangarplayerinfo
                gridsold.GridForSale          = false;
                gridsold.ForceSpawnNearPlayer = true;
                SellerData.Grids.Remove(gridsold);
                gridsold.GridName = NewGridName;

                //Add it to buyers info
                BuyerData.Grids.Add(gridsold);

                //Move grid in folders!
                string SellerGridPath = Path.Combine(SellerMethods.FolderPath, grid.name + ".sbc");
                string BuyerGridPath  = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                File.Move(SellerGridPath, BuyerGridPath);

                //After move we need to update all block owners and authors! this meanings opening up the grid and deserializing it to iterate the grid! (we dont want the seller to still be the author)

                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);

                //byte[] Definition = MyAPIGateway.Utilities.SerializeToBinary(grid);

                //Get grid definition of removed grid. (May not even need to get this lol)
                //GridsForSale RemovedGrid = Main.GridDefinition.FirstOrDefault(x => x.name == Item.Name);


                //We need to send to all to remove the item from the list

                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);
                SendAccountUpdate.BalanceUpdate.Add(SellerAccount);

                MarketServers.Update(SendAccountUpdate);
                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);



                //Write all files!
                FileSaver.Save(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json"), SellerData);
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(SellerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(SellerData));
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));
            }
            //Transfer Grid and transfer Author/owner!
        }
Exemple #14
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(MarketList obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Exemple #15
0
        /// <summary>
        /// Extract the results of a Betfair GetAllMarketsResp.data string to a MarketList object
        /// </summary>
        /// <param name="marketData"></param>
        /// <returns></returns>
        public MarketList ConvertToObject(string marketData)
        {
            if (marketData != null)
            {
                //Step 1 - Create the response object
                var marketList = new MarketList();

                //Step 2 - Clean up the break characters
                marketData = HelperMethods.ProtectBreakChars(marketData);

                //Step 3 - Split the markets out
                string[] marketStringArray = marketData.Split(":".ToCharArray());

                //Step 4 - Loop through the markets and split out the market items
                for (int x = 0; x < marketStringArray.Length; x++)
                {
                    //Check that the array is not empty
                    if (marketStringArray[x].Length > 0)
                    {
                        //Create the market object
                        var market = new Market();

                        //Step 5 - Split out the markets component items
                        string[] marketItemsStringArray = marketStringArray[x].Split("~".ToCharArray());

                        //Step 6 - Check that the array is equal or greater than 15
                        if (marketItemsStringArray.Length >= 15)
                        {
                            //Step 7 - Restore the break characters
                            for (int y = 0; y < marketItemsStringArray.Length; y++)
                            {
                                marketItemsStringArray[y] = HelperMethods.RestoreBreakChars(marketItemsStringArray[y]);
                            }

                            //Step 8 - Update the market values
                            market.marketId  = Convert.ToInt32(marketItemsStringArray[0]);
                            market.name      = marketItemsStringArray[1];
                            market.type      = marketItemsStringArray[2];
                            market.status    = (MarketStatus)Enum.Parse(typeof(MarketStatus), marketItemsStringArray[3]);
                            market.eventDate =
                                new DateTimeCalculations().UnixTimeStampToDateTime(
                                    Convert.ToDouble(marketItemsStringArray[4]));
                            market.menuPath                 = marketItemsStringArray[5];
                            market.eventHierarchy           = HelperMethods.SplitToInt32Array("/", marketItemsStringArray[6]);
                            market.betDelay                 = Convert.ToInt32(marketItemsStringArray[7]);
                            market.exchangeId               = Convert.ToInt32(marketItemsStringArray[8]);
                            market.country                  = marketItemsStringArray[9];
                            market.apiMarketDataLastRefresh = Convert.ToInt64(marketItemsStringArray[10]);
                            market.numberOfRunners          = Convert.ToInt32(marketItemsStringArray[11]);
                            market.numberOfWinners          = Convert.ToInt32(marketItemsStringArray[12]);
                            market.totalAmountMatched       = Convert.ToDouble(marketItemsStringArray[13]);
                            if (marketItemsStringArray[14].ToLower() == "y")
                            {
                                market.bspMarket = true;
                            }
                            if (marketItemsStringArray[15].ToLower() == "y")
                            {
                                market.turningInPlay = true;
                            }

                            //Step 9 - Add the new market item to the response object
                            marketList.Add(market);
                        }
                    }
                }

                //Step 10 - Sort the list items
                marketList.Sort(new MarketDateComparer());

                //Step 11 - Done
                return(marketList);
            }
            return(null);
        }
Exemple #16
0
        //Forces refresh of all admin offered grids and syncs them to the blocks in the server
        public void UpdatePublicOffers()
        {
            //Update all public offer market items!


            //Need to remove existing ones
            for (int i = 0; i < GridList.Count; i++)
            {
                if (GridList[i].Steamid != 0)
                {
                    continue;
                }

                Hangar.Debug("Removing public offer: " + GridList[i].Name);
                GridList.RemoveAt(i);
            }

            string PublicOfferPath = ServerOffersDir;

            //Clear list
            PublicOfferseGridList.Clear();

            foreach (PublicOffers offer in Config.PublicOffers)
            {
                if (offer.Forsale)
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");


                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    //HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;
                    //NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    //NewList.NumberofBlocks = stamp.NumberofBlocks;
                    //NewList.SmallGrids = stamp.SmallGrids;
                    //NewList.LargeGrids = stamp.LargeGrids;
                    // NewList.BlockTypeCount = stamp.BlockTypeCount;

                    //Need to setTotalBuys
                    PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }

            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = PublicOfferseGridList;

            FileSaver.Save(ServerMarketFileDir, Data);
        }
Exemple #17
0
        private bool SellOnMarket(string IDPath, GridStamp Grid, PlayerInfo Data, MyIdentity Player, long NumPrice, string Description)
        {
            string path = Path.Combine(IDPath, Grid.GridName + ".sbc");

            if (!File.Exists(path))
            {
                //Context.Respond("Grid doesnt exist! Contact an admin!");
                return(false);
            }



            Parallel.Invoke(() =>
            {
                MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                var shipBlueprint             = myObjectBuilder_Definitions.ShipBlueprints;
                MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];



                byte[] Definition       = MyAPIGateway.Utilities.SerializeToBinary(grid);
                GridsForSale GridSell   = new GridsForSale();
                GridSell.name           = Grid.GridName;
                GridSell.GridDefinition = Definition;


                //Seller faction
                var fc = MyAPIGateway.Session.Factions.GetObjectBuilder();

                MyObjectBuilder_Faction factionBuilder;
                try
                {
                    factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                    if (factionBuilder != null || factionBuilder.Tag != "")
                    {
                        Grid.SellerFaction = factionBuilder.Tag;
                    }
                }
                catch
                {
                    try
                    {
                        Hangar.Debug("Player " + Player.DisplayName + " has a bugged faction model! Attempting to fix!");
                        factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                        MyObjectBuilder_FactionMember member = factionBuilder.Members.First(x => x.PlayerId == Player.IdentityId);

                        bool IsFounder;
                        bool IsLeader;

                        IsFounder = member.IsFounder;
                        IsLeader  = member.IsLeader;

                        factionBuilder.Members.Remove(member);
                        factionBuilder.Members.Add(member);
                    }
                    catch (Exception a)
                    {
                        Hangar.Debug("Welp tbh fix failed! Please why no fix. :(", a, Hangar.ErrorType.Trace);
                    }

                    //Bugged player!
                }



                MarketList List       = new MarketList();
                List.Name             = Grid.GridName;
                List.Description      = Description;
                List.Seller           = "Auction House";
                List.Price            = NumPrice;
                List.Steamid          = Convert.ToUInt64(IDPath);
                List.MarketValue      = Grid.MarketValue;
                List.SellerFaction    = Grid.SellerFaction;
                List.GridMass         = Grid.GridMass;
                List.SmallGrids       = Grid.SmallGrids;
                List.LargeGrids       = Grid.LargeGrids;
                List.NumberofBlocks   = Grid.NumberofBlocks;
                List.MaxPowerOutput   = Grid.MaxPowerOutput;
                List.GridBuiltPercent = Grid.GridBuiltPercent;
                List.JumpDistance     = Grid.JumpDistance;
                List.NumberOfGrids    = Grid.NumberOfGrids;
                List.BlockTypeCount   = Grid.BlockTypeCount;
                List.PCU = Grid.GridPCU;


                //List item as server offer
                List.ServerOffer = true;



                //We need to send to all to add one item to the list!
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.AddItem;
                SendMessage.GridDefinition.Add(GridSell);
                SendMessage.List.Add(List);


                Servers.Update(SendMessage);
            });

            return(true);
        }
 internal static HandleRef getCPtr(MarketList obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Exemple #19
0
 void Start()
 {
     instance = this;
     CheckStep();
 }
Exemple #20
0
        public IActionResult List()
        {
            MarketList mrktList = new MarketList();

            return(View(mrktList.MarketLists().ToList()));
        }
Exemple #21
0
 public MarketController()
 {
     _marketList = new MarketList();
 }
Exemple #22
0
        /// <summary>
        /// Loads the markets.
        /// </summary>
        private void LoadMarkets()
        {
            if (marketsLoaded == null)
            {
                marketsLoaded = new Dictionary <String, Market>();
            }
            if (marketList == null)
            {
                marketList = new MarketList();
            }
            if (!IsRunning)
            {
                return;
            }
            IsRunning = false;

            try
            {
                // Remove markets that have expired
                marketsLoaded = (Dictionary <String, Market>)CleanUpMarketsLoadedList(marketsLoaded);

                // Notify the user
                SendMessage("AutoMarketLoader: Market loader looking for new markets.");

                foreach (var exchangeId in getAllMarkets.ExchangeIds)
                {
                    marketList = null;
                    marketList = Core.betfairAPI.GetAllMarketsObject(exchangeId, getAllMarkets.Countries,
                                                                     getAllMarkets.EventIds,
                                                                     Convert.ToInt32(getAllMarkets.EventDateTo),
                                                                     Convert.ToInt32(getAllMarkets.EventDateFrom));

                    if (marketList == null)
                    {
                        continue;
                    }

                    SendMessage("AutoMarketLoader: " + marketList.Count + " potensial markets found.");

                    foreach (Market market in marketList)
                    {
                        if (marketsLoaded.ContainsKey((market.exchangeId + ":" + market.marketId)) ||
                            market.status != MarketStatus.ACTIVE)
                        {
                            continue;
                        }

                        var marketProperties = GetObjectValues(market);

                        foreach (var strategy in strategies)
                        {
                            if (strategy.FilterGetAllMarketsResults == null)
                            {
                                continue;
                            }

                            var loadMarket = new bool[strategy.FilterGetAllMarketsResults.Length];

                            for (var x = 0; x < strategy.FilterGetAllMarketsResults.Length; x++)
                            {
                                var endReached = false;
                                loadMarket[x] = true;
                                var query = strategy.FilterGetAllMarketsResults[x];

                                while (!endReached)
                                {
                                    string propertyValue;
                                    if (!marketProperties.ContainsKey(query.Field.ToLower()))
                                    {
                                        loadMarket[x] = false;
                                    }
                                    else
                                    {
                                        propertyValue =
                                            (marketProperties[query.Field.ToLower()].ToString()).ToLower
                                                ();

                                        switch (query.Operator)
                                        {
                                        case QueryOperator.CONTAINS:
                                            if (!propertyValue.Contains(query.Value.ToLower()))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.NOT_CONTAINS:
                                            if (propertyValue.Contains(query.Value.ToLower()))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.EQUAL:
                                            if (propertyValue != query.Value.ToLower())
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.NOT_EQUAL:
                                            if (propertyValue == query.Value.ToLower())
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.GREATER_THAN:
                                            if (Convert.ToDouble(propertyValue) >
                                                Convert.ToDouble(query.Value))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.LESS_THAN:
                                            if (Convert.ToDouble(propertyValue) <
                                                Convert.ToDouble(query.Value))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.REGEX_IS_MATCH:
                                            if (
                                                !Regex.IsMatch(
                                                    (marketProperties[query.Field.ToLower()].ToString()),
                                                    query.Value))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;

                                        case QueryOperator.REGEX_NOT_MATCH:
                                            if (
                                                Regex.IsMatch(
                                                    (marketProperties[query.Field.ToLower()].ToString()),
                                                    query.Value))
                                            {
                                                loadMarket[x] = false;
                                            }
                                            break;
                                        }
                                    }

                                    if (query.And != null)
                                    {
                                        query = query.And;
                                    }
                                    else
                                    {
                                        endReached = true;
                                    }
                                }
                            }

                            for (var x = 0; x < loadMarket.Length; x++)
                            {
                                if (!loadMarket[x])
                                {
                                    continue;
                                }

                                marketsLoaded.Add((market.exchangeId + ":" + market.marketId),
                                                  market);
                                Broker.Execute(EventNames.LoadNewMarketAction, this,
                                               new NewMarketEventArgs(exchangeId, market.marketId,
                                                                      strategy));
                                continue;
                            }
                        }
                    }
                }

                wakeUpTime = DateTime.Now.AddMilliseconds(getAllMarkets.RunMarketsQueryEvery);
                SendMessage("AutoMarketLoader: Going to sleep until " + wakeUpTime);
            }
            catch (Exception ex)
            {
                SendMessage("EXCEPTION: AutoMarketLoader: Message:" + ex.Message);
                SendMessage("EXCEPTION: AutoMarketLoader: Stack Trace:" + ex);
            }

            IsRunning = true;
        }
Exemple #23
0
 internal static HandleRef getCPtr(MarketList obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }