async public Task MigrateCatolgItems(string sourceTitleID, string targetTitleID) { //TODO: Make this support multiple catalogs var console = new ConsoleTaskWriter("# Migrating Catalog Items. Main Catalog only"); console.LogProcess("Fetching data"); var catalogItems = await PlayFabService.GetCatalogData(sourceTitleID); if (catalogItems == null) { console.LogError("Error Fetching CloudScript Data, skipping"); return; } if (catalogItems.Count == 0) { console.LogSuccess("Found no catalog items to update"); return; } console.LogProcess("Migrating"); var success = await PlayFabService.UpdateCatalogData(targetTitleID, catalogItems[0].CatalogVersion, true, catalogItems); if (!success) { console.LogError("Save Catalog Failed, skipping."); return; } console.LogSuccess("Completed migration of catalog items"); }
/// <summary> /// Set State and settings based on line input /// </summary> /// <param name="line"></param> /// <returns></returns> public bool SetState(string line) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Setting Store List"); var argsList = line.Split(' '); var storeIdList = argsList.ToList().FindAll(s => !s.ToLower().Contains("setstores") && !string.IsNullOrEmpty(s)).ToList(); PlayFabService.StoreList = storeIdList; PlayFabService.Save(); Console.ForegroundColor = ConsoleColor.White; return(false); }
async public Task MigrateTitleData(string sourceTitleID, string targetTitleID) { var console = new ConsoleTaskWriter("# Migrating TitlData"); // - FETCH console.LogProcess("Fetching data for comparison"); PlayFab.ServerModels.GetTitleDataResult[] results = await Task.WhenAll( PlayFabService.GetTitleData(sourceTitleID), PlayFabService.GetTitleData(targetTitleID) ); Dictionary <string, string> sourceTitleData = results[0].Data ?? new Dictionary <string, string>(); Dictionary <string, string> targetTitleData = results[1].Data ?? new Dictionary <string, string>(); if (sourceTitleData == null && targetTitleData == null) { console.LogError("Failed to retrieve title data, continuing..."); } // - UPDATE Dictionary <string, string> itemsNeedingUpdate = FilterTitleDataToUpdate(sourceTitleData, targetTitleData); if (itemsNeedingUpdate.Count == 0) { console.LogSuccess("Found no title data items to update."); return; } int totalItems = itemsNeedingUpdate.Count; int updatItemCounter = 0; while (itemsNeedingUpdate.Count > 0) { updatItemCounter++; console.LogProcess("Updating " + updatItemCounter + " out of " + totalItems + " items."); var kvp = itemsNeedingUpdate.FirstOrDefault(); itemsNeedingUpdate.Remove(kvp.Key); bool success = await PlayFabService.UpdateTitleData(targetTitleID, kvp); if (!success) { console.LogError("Save Title Data Failed, skipping"); } } console.LogSuccess("TitleData Migration completed, Updated " + totalItems + " items"); }
async public Task MigrateStores(string sourceTitleID, string targetTitleID, List <String> storeList) { var console = new ConsoleTaskWriter("# Migrating stores from settings. StoreIDs=" + string.Join(",", storeList.ToArray())); if (storeList.Count == 0) { console.LogError("No stores have been set with SetStores. Skipping migration."); return; } // TODO: Remove any prevoius stores that has been deleted. var storeListBufffer = storeList.ToList <string>(); while (storeListBufffer.Count > 0) { console.LogProcess("Migrating store"); var currentStoreId = storeListBufffer[0]; storeListBufffer.Remove(currentStoreId); var result = await PlayFabService.GetStoreData(sourceTitleID, currentStoreId); if (result == null) { console.LogError("Error Fetching Store Data, trying next store."); continue; } bool success = await PlayFabService.UpdateStoreData(targetTitleID, currentStoreId, result.CatalogVersion, result.MarketingData, result.Store); if (!success) { console.LogError("Save Store Failed, trying next store."); continue; } console.LogProcess("store migrated"); } console.LogSuccess("Completed migration of stores."); }
async public Task MigrateCloudScriptAsync(string sourceTitleID, string targetTitleID) { var console = new ConsoleTaskWriter("# Migrating CloudScript Data"); var lists = await PlayFabService.GetCloudScript(sourceTitleID); if (lists == null) { console.LogError("Failed to fetch CloudScript Data."); return; } console.LogProcess("Migrating script"); bool success = await PlayFabService.UpdateCloudScript(targetTitleID, lists); if (!success) { console.LogError("Save CloudScript Failed."); return; } console.LogSuccess("Completed cloud script migration."); }
private void CloudSyncOrUpload(JSONObject json, string reason) { m_cloudSave = null; BigDouble a = -1L; if (json != null && json.HasField("Base")) { json = json.GetField("Base"); if (json != null && json.HasField("Value")) { string val = PlayFabService.JSONUnescape(json.asString("Value", () => string.Empty)); m_cloudSave = JSONObject.Create(val); a = m_cloudSave.asBigDouble("LifetimeCoins", () => - 1L); } } if (m_cloudSave != null && ShouldForceUpdate(m_cloudSave)) { Debug.LogError("Show Force Update"); // ForceUpdateService.ShowForceUpdateDialog(); } else if (m_cloudSave != null && IsCloudNewer(m_cloudSave, PlayerData.Instance)) { LocalProgress.Value = PlayerData.Instance.LifetimeCoins.Value; CloudProgress.Value = BigDouble.Max(a, 0L); Observable.Return(value: true).Delay(TimeSpan.FromSeconds(3.0)).Take(1) .Subscribe(delegate { BindingManager.Instance.CloudSyncPopup.SetActive(value: true); }) .AddTo(SceneLoader.Instance); } else { UploadSaveToCloud(PlayerData.Instance, reason, null, null); } }
private void Execute() { switch (_state) { case States.TitleData: #region Update Title Data Keys if (!_titleData.FromProcessed) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Getting Title Data from: " + _commandArgs.FromTitleId); PlayFabService.GetTitleData(_commandArgs.FromTitleId, (success, result) => { if (!success || result.Data.Count == 0) { Console.WriteLine("No Title Data found, skipping"); SetNextState(); } else { Console.WriteLine("Title Data Keys Found: " + result.Data.Count.ToString()); _titleData.Data = result.Data; _titleData.FromProcessed = true; } }); } if (!_titleData.ToProcessed && _titleData.FromProcessed) { if (_titleData.Data.Count == 0) { _titleData.ToProcessed = true; SetNextState(); break; } var kvp = _titleData.Pop(); Console.WriteLine("Saving Title Data from: " + _commandArgs.FromTitleId + " To: " + _commandArgs.ToTitleId); PlayFabService.UpdateTitleData(_commandArgs.ToTitleId, kvp, (success) => { if (!success) { Console.WriteLine("Save Title Data Failed, skipping"); SetNextState(); } }); } #endregion break; case States.TitleInternalData: #region Update Title Internal Data Keys if (!_titleInternalData.FromProcessed) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Getting Title Interal Data from: " + _commandArgs.FromTitleId); PlayFabService.GetTitleInternalData(_commandArgs.FromTitleId, (success, result) => { if (!success || result.Data.Count == 0) { Console.WriteLine("No Title Internal Data found, skipping"); SetNextState(); } else { Console.WriteLine("Title Internal Data Keys Found: " + result.Data.Count.ToString()); _titleInternalData.Data = result.Data; _titleInternalData.FromProcessed = true; } }); } if (!_titleInternalData.ToProcessed && _titleInternalData.FromProcessed) { if (_titleInternalData.Data.Count == 0) { _titleInternalData.ToProcessed = true; SetNextState(); break; } var kvp = _titleInternalData.Pop(); Console.WriteLine("Saving Title Interal Data from: " + _commandArgs.FromTitleId + " To: " + _commandArgs.ToTitleId); PlayFabService.UpdateTitleInternalData(_commandArgs.ToTitleId, kvp, (success) => { if (!success) { Console.WriteLine("Save Title Interal Data Failed, skipping"); SetNextState(); } }); } #endregion break; case States.Currency: #region Update Currency Types if (!_currencyData.FromProcessed) { Console.WriteLine("Getting Currency Types Data from: " + _commandArgs.FromTitleId); PlayFabService.GetCurrencyData(_commandArgs.FromTitleId, (success, vcData) => { if (!success || vcData.Count == 0) { Console.WriteLine("Error Fetching Currency Type Data, skipping"); SetNextState(); return; } _currencyData.Data = vcData; _currencyData.FromProcessed = true; }); } if (!_currencyData.ToProcessed && _currencyData.FromProcessed) { if (_currencyData.Data == null) { _currencyData.ToProcessed = true; SetNextState(); break; } PlayFabService.UpdateCurrencyData(_commandArgs.ToTitleId, _currencyData.Data, (success) => { if (!success) { Console.WriteLine("Save Title Data Failed."); _cts.Cancel(); } _currencyData.Data = null; }); } #endregion break; case States.CloudScript: #region Update CloudScript File if (!_cloudScriptData.FromProcessed) { Console.WriteLine("Getting CloudScript Data from: " + _commandArgs.FromTitleId); PlayFabService.GetCloudScript(_commandArgs.FromTitleId, (success, data) => { if (!success || data.Count == 0) { Console.WriteLine("Error Fetching CloudScript Data, skipping."); SetNextState(); return; } _cloudScriptData.Data = data; _cloudScriptData.FromProcessed = true; }); } if (!_cloudScriptData.ToProcessed && _cloudScriptData.FromProcessed) { if (_cloudScriptData.Data == null) { _cloudScriptData.ToProcessed = true; SetNextState(); break; } Console.WriteLine("Updating CloudScript on Title: " + _commandArgs.ToTitleId); PlayFabService.UpdateCloudScript(_commandArgs.ToTitleId, _cloudScriptData.Data, (success) => { //if (!success) //{ // Console.WriteLine("Save CloudScript Failed."); // _cts.Cancel(); //} _cloudScriptData.Data = null; }); } #endregion break; case States.Files: #region Update Content Files //Start by creating a temp directory var path = AppDomain.CurrentDomain.BaseDirectory + "temp"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!_cdnData.FromProcessed) { PlayFabService.GetContentList(_commandArgs.FromTitleId, (success, data) => { if (!success) { Console.WriteLine("Error Fetching CloudScript Data, skipping"); SetNextState(); return; } _cdnData.Data = data; _cdnData.FromProcessed = true; }); } if (!_cdnData.ToProcessed && _cdnData.FromProcessed) { if (_cdnData.Data.Count == 0 && _cdnData.FileList.Count == 0) { _cdnData.ToProcessed = true; _cdnData.Data = null; _cdnData.FileList = null; Directory.Delete(path, true); SetNextState(); break; } if (_cdnData.Data.Count > 0) { var isDone = false; PlayFabService.DownloadFile(_commandArgs.FromTitleId, path, _cdnData.popData(), (success, filePath, data) => { if (success) { _cdnData.FileList.Add(new CdnFileDataMigration.UploadFile() { Data = data, FilePath = filePath }); } isDone = true; }); do { //block until done. } while (!isDone); break; } if (_cdnData.Data.Count == 0 && _cdnData.FileList.Count > 0) { var isUploadDone = false; PlayFabService.UploadFile(_commandArgs.ToTitleId, _cdnData.popFileList(), (success) => { isUploadDone = true; }); do { //Block until this file upload is done. } while (!isUploadDone); } } #endregion break; case States.Catalogs: #region Update Catalog if (_catalogData.FromProcessed && _catalogData.ToProcessed) { SetNextState(); break; } if (!_catalogData.FromProcessed) { //TODO: Make this support multiple catalogs Console.WriteLine("Getting Catalog Data for Main Catalog only"); PlayFabService.GetCatalogData(_commandArgs.FromTitleId, (success, catalogVersion, catalog) => { if (!success) { Console.WriteLine("Error Fetching CloudScript Data, skipping"); SetNextState(); } _catalogData.Data = catalog; _catalogData.CatalogVersion = catalogVersion; _catalogData.FromProcessed = true; }); } if (!_catalogData.ToProcessed && _catalogData.FromProcessed) { Console.WriteLine("Updating Catalog on Title: " + _commandArgs.ToTitleId); PlayFabService.UpdateCatalogData(_commandArgs.ToTitleId, _catalogData.CatalogVersion, true, _catalogData.Data, (success) => { if (!success) { Console.WriteLine("Save Catalog Failed, skipping."); SetNextState(); } _catalogData.Data = null; _catalogData.CatalogVersion = null; _catalogData.ToProcessed = true; }); } #endregion break; case States.Stores: #region Update Stores if (_storeData.IsComplete) { _storeData.Data = null; _storeData.MarketingModel = null; _storeData.StoreId = null; _storeData.CatalogVersion = null; SetNextState(); break; } if (!_storeData.FromProcessed) { if (_storeData.StoreList.Count == 0) { SetNextState(); break; } var currentStoreId = _storeData.popStoreId(); Console.WriteLine("Getting Store Data for StoreID: " + currentStoreId); PlayFabService.GetStoreData(_commandArgs.FromTitleId, currentStoreId, (success, catalogVersion, storeId, marketingModel, store) => { if (!success) { Console.WriteLine("Error Fetching Store Data, Skipping."); SetNextState(); } _storeData.FromProcessed = true; _storeData.Data = store; _storeData.CatalogVersion = catalogVersion; _storeData.StoreId = storeId; _storeData.MarketingModel = marketingModel; }); } if (!_storeData.ToProcessed && _storeData.FromProcessed) { var currentStoreId = _storeData.StoreId; PlayFabService.UpdateStoreData(_commandArgs.ToTitleId, _storeData.StoreId, _storeData.CatalogVersion, _storeData.MarketingModel, _storeData.Data, (success) => { if (!success) { Console.WriteLine("Save Store Failed, Skipping."); SetNextState(); } _storeData.Data = null; _storeData.CatalogVersion = null; if (_storeData.StoreList.Count == 0) { _storeData.ToProcessed = true; _storeData.IsComplete = true; } else { _storeData.ToProcessed = false; _storeData.FromProcessed = false; } }); } #endregion break; case States.DropTables: #region Update Drop Tables if (_droptableData.FromProcessed && _droptableData.ToProcessed) { SetNextState(); break; } if (!_droptableData.FromProcessed) { //TODO: Make this support multiple catalogs Console.WriteLine("Getting Drop Table Data for Main Catalog only"); PlayFabService.GetDropTableData(_commandArgs.FromTitleId, (success, catalog) => { if (!success) { Console.WriteLine("Error Fetching CloudScript Data, skipping"); SetNextState(); } _droptableData.Data = new Queue <List <RandomResultTable> >(); Dictionary <string, RandomResultTableListing> listing = new Dictionary <string, RandomResultTableListing>(catalog); List <RandomResultTable> thisList = new List <RandomResultTable>(); foreach (var v in listing) { bool referencesDropTable = false; foreach (var item in v.Value.Nodes) { if (item.ResultItemType == ResultTableNodeType.TableId) { referencesDropTable = true; break; } } if (!referencesDropTable) { RandomResultTable table = new RandomResultTable(); table.TableId = v.Value.TableId; table.Nodes = v.Value.Nodes; thisList.Add(table); } } if (thisList.Count != 0) { while (true) { _droptableData.Data.Enqueue(thisList); foreach (var item in thisList) //remove from pending list { listing.Remove(item.TableId); } //Add any references List <RandomResultTable> nextList = new List <RandomResultTable>(); foreach (var item in listing) { bool referencesCurrent = false; foreach (var node in item.Value.Nodes) { if (node.ResultItemType == ResultTableNodeType.TableId && thisList.Any(x => x.TableId == node.ResultItem)) { referencesCurrent = true; break; } } if (referencesCurrent) { RandomResultTable table = new RandomResultTable(); table.TableId = item.Value.TableId; table.Nodes = item.Value.Nodes; nextList.Add(table); } } if (nextList.Count == 0) { break; } thisList = nextList; } } _droptableData.FromProcessed = true; }); } if (!_droptableData.ToProcessed && _droptableData.FromProcessed) { Console.WriteLine("Updating Drop Tables on Title: " + _commandArgs.ToTitleId); PlayFabService.UpdateDropTableData(_commandArgs.ToTitleId, _droptableData.Data.Dequeue(), (success) => { if (!success) { Console.WriteLine("Save Catalog Failed, skipping."); SetNextState(); } //_catalogData.Data = null; //_catalogData.CatalogVersion = null; if (_droptableData.Data.Count == 0) { _droptableData.Data = null; _droptableData.ToProcessed = true; } }); } #endregion break; case States.Complete: Console.WriteLine("Migration Complete."); Console.ForegroundColor = ConsoleColor.White; PackageManagerService.SetState(MainPackageStates.Idle); _cts.Cancel(); break; } }
// Overwrites any table with the same id. // NOTE: Could not find a way to delete the table that have been created // TODO: Make this support multiple catalogs async public Task MigrateDropTables(string sourceTitleID, string targetTitleID) { var console = new ConsoleTaskWriter("# Migrating Drop Table Data, Main Catalog only"); console.LogProcess("Fetching data"); Dictionary <string, RandomResultTableListing>[] results = await Task.WhenAll( PlayFabService.GetDropTableData(sourceTitleID), PlayFabService.GetDropTableData(targetTitleID) ); Dictionary <string, RandomResultTableListing> sourceCatalog = results[0]; Dictionary <string, RandomResultTableListing> targetCatalog = results[1]; if (sourceCatalog == null) { console.LogError("Error Fetching CloudScript Data, skipping"); return; } // Find out if the targetTitle has drop tables that the source dosent have // at the time of writing there where no PlayFAbAPI methods for deletion // The user has to manually go in in the dashboard and delet any unwanted droptables. string divergentMessage = ""; List <string> deletionKeys = new List <string>(); foreach (KeyValuePair <string, RandomResultTableListing> targetTableItem in targetCatalog) { if (!sourceCatalog.ContainsKey(targetTableItem.Key)) { deletionKeys.Add(targetTableItem.Key); } } if (deletionKeys.Count > 0) { divergentMessage = "The target title contains " + deletionKeys.Count + " items that the source doesnt have. TableIds: " + string.Join(",", deletionKeys.ToArray()) + "." + " \n If you you want to delete these, you have to do it through the dashboard."; } if (sourceCatalog.Count <= 0) { console.LogProcess("Found no drop table to migrate, skipping. "); console.ReportError(divergentMessage); return; } List <RandomResultTable> dropTables = new List <RandomResultTable>(); foreach (RandomResultTableListing item in sourceCatalog.Values) { RandomResultTable dropTable = new RandomResultTable(); dropTable.TableId = item.TableId; dropTable.Nodes = item.Nodes; dropTables.Add(dropTable); } console.LogProcess("Migrating data"); bool success = await PlayFabService.UpdateDropTableData(targetTitleID, dropTables); if (!success) { console.LogError("Error Fetching CloudScript Data, skipping"); console.ReportError(divergentMessage); return; } console.LogSuccess("Completed Drop Table migration. "); console.ReportError(divergentMessage); }
async public Task MigrateCurrencyAsync(string sourceTitleID, string targetTitleID, bool forceOverWrite = true) { var console = new ConsoleTaskWriter("# Migrating currency data"); // - FETCH // Get data from both titles for comparison ListVirtualCurrencyTypesResult[] results = await Task.WhenAll( PlayFabService.GetCurrencyData(sourceTitleID), PlayFabService.GetCurrencyData(targetTitleID) ); List <VirtualCurrencyData> sourceData = results[0].VirtualCurrencies ?? new List <VirtualCurrencyData>(); List <VirtualCurrencyData> targetData = results[1].VirtualCurrencies ?? new List <VirtualCurrencyData>(); // - DELETE // Find all items in the target that don't exist in the source List <VirtualCurrencyData> dataToBeDeleted = targetData.FindAll((PlayFab.AdminModels.VirtualCurrencyData targetCurrency) => { var delete = true; foreach (VirtualCurrencyData sourceCurrency in sourceData) { if (sourceCurrency.CurrencyCode == targetCurrency.CurrencyCode) { delete = false; } } return(delete); }); // Delete data if (dataToBeDeleted.Count > 0) { console.LogProcess("Deleting " + dataToBeDeleted.Count + " items"); var deletedResult = await PlayFabService.DeleteCurrencyData(targetTitleID, dataToBeDeleted); if (deletedResult == null) { console.LogError("Deleting currency data failed."); return; } } // - UPDATE // Find all items in the source data that don't match target or doesn't exist List <VirtualCurrencyData> dataThatNeedsUpdate = sourceData.FindAll((PlayFab.AdminModels.VirtualCurrencyData sourceCurrency) => { var needsUpdate = true; foreach (VirtualCurrencyData targetCurrency in targetData) { if (targetCurrency.CurrencyCode == sourceCurrency.CurrencyCode && targetCurrency.Equals(sourceCurrency)) { needsUpdate = false; } } return(needsUpdate); }); if (dataThatNeedsUpdate.Count == 0) { console.LogSuccess("Found no data to be updated"); return; } // Update data if (dataThatNeedsUpdate.Count > 0 || forceOverWrite) { console.LogProcess("Updating " + dataThatNeedsUpdate.Count + " items"); var updatedResult = await PlayFabService.UpdateCurrencyData(targetTitleID, dataThatNeedsUpdate); if (updatedResult == null) { console.LogError("Updating currency data failed."); return; } } console.LogSuccess("Completed Migration of currency data"); }
public bool Loop() { var waitForLogin = false; switch (_state) { case States.WaitForUsername: Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(""); Console.WriteLine("Username:"******""); Console.WriteLine("Password:"******""); Console.WriteLine("2FA Token:"); break; case States.Login: waitForLogin = true; PlayFabService.Login(_username, _password, _2faToken, (success, devKey) => { if (!success) { PackageManagerService.SetState(MainPackageStates.Idle); _state = States.Idle; waitForLogin = false; return; } _DeveloperClientToken = devKey; Console.ForegroundColor = ConsoleColor.White; _state = States.GetStudios; Loop(); waitForLogin = false; }); break; case States.GetStudios: waitForLogin = true; PlayFabService.GetStudios(_DeveloperClientToken, (success) => { PackageManagerService.SetState(MainPackageStates.Idle); _state = States.Idle; waitForLogin = false; }); break; case States.Idle: default: break; } //TODO: Paul Help? do { //Block util login call is done. } while (waitForLogin); return(false); }
private bool CheckIfSameDevice() { return(PlayerData.Instance.TournamentEnteringDevice.Value == PlayFabService.GetSystemUniqueIdentifier()); }
private bool CheckIfDifferentDevice() { return(PlayerData.Instance.TournamentEnteringDevice.Value != string.Empty && PlayerData.Instance.TournamentEnteringDevice.Value != PlayFabService.GetSystemUniqueIdentifier()); }
private void SetTournamentValues() { PlayerData.Instance.TournamentEnteringDevice.Value = PlayFabService.GetSystemUniqueIdentifier(); PlayerData.Instance.TournamentIdCurrent.Value = 1; PlayerData.Instance.TournamentTimeStamp.Value = ServerTimeService.NowTicks() - TimeSpan.FromSeconds(UnityEngine.Random.Range(0, PersistentSingleton <GameSettings> .Instance.TournamentVariationSeconds)).Ticks; }
static void Main(string[] args) { _args = args; _lineSb = new StringBuilder(); //Parse Args and determine if this is a CLI or Console mode. if (args.Length > 0 && !_argsRead) { _isCLI = true; foreach (var a in args) { _lineSb.Append(a + " "); } _line = _lineSb.ToString(); _argsRead = true; _args = new string[0]; } else { _readLine = true; _argsRead = true; } //Init PlayFab Service Settings PlayFabService.Init(); //Load Settings File PlayFabService.Load(); //Out put to screen some fancy playfab jazz Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Green; Console.Write(".oO={ "); Console.ForegroundColor = ConsoleColor.White; Console.Write("PlayFab Power Tools CLI"); Console.ForegroundColor = ConsoleColor.Green; Console.Write(" }=Oo."); Console.ForegroundColor = ConsoleColor.White; //if this is a console app then we want to show them how to get help. if (!_isCLI) { Console.WriteLine(""); Console.WriteLine("Type: 'Help' for a list of commands"); Console.WriteLine(""); Console.Write(">"); } else { Console.WriteLine(""); Console.WriteLine(""); } //Load all the packages that process commands var type = typeof(iStatePackage); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && p.Name != "iStatePackage"); //foreach package we need to register with Package Manager foreach (var t in types) { var packageType = (iStatePackage)Activator.CreateInstance(t); packageType.RegisterMainPackageStates(packageType); } //get the correct package for the state we are in _currentPackage = PackageManagerService.GetPackage(); //This is the main program loop. do { //if we are a console app, read the command that is entered. if (_args.Length == 0 && _readLine) { if (!_isTypedTextHidden) { //Read the line input from the console. _line = Console.ReadLine(); } else { //Read the line in a different way. ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Enter) { var s = string.Format("{0}", key.KeyChar); _lineSb.Append(s); } } while (key.Key != ConsoleKey.Enter); _line = _lineSb.ToString(); } } //Set read line to true, not it will only be false if we came from a CLI. _readLine = true; var loopReturn = false; if (PackageManagerService.IsIdle()) { //If we are idle then we want to check for commands. PackageManagerService.SetState(_line); _currentPackage = PackageManagerService.GetPackage(); _isTypedTextHidden = _currentPackage.SetState(_line); loopReturn = _currentPackage.Loop(); } else { //If we are not idle, then we want to process the _line for arguments. //get the correct package for the state we are in _currentPackage = PackageManagerService.GetPackage(); //process the package state _isTypedTextHidden = _currentPackage.SetState(_line); //do package loop, which contains logic to do stuff. loopReturn = _currentPackage.Loop(); } //if this is a CLI then we just want to exit. if (!_isCLI) { //Prompt or exit. if (!loopReturn) { Console.Write(">"); } else { _line = null; } } else { _line = null; } } while (_line != null); //Always save before we completely exit. PlayFabService.Save(); }
///PlayFabServive() /// <summary> /// A constructor for PlayFabService class. /// </summary> /// Pre-Condition: None. /// Post-Condition: The PlayFabService object will be created public PlayFabService() { _instance = this; }
public static async Task FakeDataAsync() { #region Fake Console.Write("Mocking data... "); var futbolPlayerFaker = new FutbolPlayerFakerService(dataSeederConfig.TournamentConfig); var futbolPlayers = futbolPlayerFaker.GenerateFutbolPlayers(); var tournamentFaker = new TournamentFakerService(dataSeederConfig.TournamentConfig, futbolPlayers); tournamentFaker.GenerateTournaments(); var tournament = tournamentFaker.Tournament; var matches = tournamentFaker.Matches; var teams = tournament.FutbolTeams; var playersForTeam = dataSeederConfig.TournamentConfig.TeamStartersAmount + dataSeederConfig.TournamentConfig.TeamSubsAmount; var teamId = 1; var countPlayers = 0; foreach (var player in futbolPlayers) { player.FutbolTeamID = teamId.ToString(); countPlayers++; if (countPlayers == playersForTeam) { countPlayers = 0; teamId++; } } var userDataFaker = new UserDataFakerService(dataSeederConfig.UserDataConfig, futbolPlayers); var userTeamData = userDataFaker.GenerateUserTeams(); var userTransactionData = userDataFaker.GenerateUserTransactions(); Console.WriteLine("Mocking data... Done"); #endregion #region Populate CosmosDB Console.Write("Connecting to PlayFab and Cosmos DB... "); const int batchSize = 50; var playFabClient = new PlayFabService(dataSeederConfig.ConfigPlayFab, new MemoryCache(new MemoryCacheOptions())); var cosmosClient = new FantasySoccerDataSeeder.Services.CosmosDBService(dataSeederConfig.ConfigCosmosDB); await cosmosClient.CreateDatabaseIfNotExistsAsync(CosmosDBConstants.DatabaseName); Console.WriteLine("Done"); Console.Write("Inserting Tornament into CosmosDB... "); try { await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.TournamentContainerName, CosmosDBConstants.PartitionKey); var tournamentContainer = cosmosClient.GetContainer(CosmosDBConstants.DatabaseName, CosmosDBConstants.TournamentContainerName); var tournamentString = JsonConvert.SerializeObject(tournament); var stream = new MemoryStream(Encoding.ASCII.GetBytes(tournamentString)); await cosmosClient.AddItemStreamAsync(tournamentContainer, stream, tournament.ID); Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting Tournament: {ex.Message}"); } try { Console.Write("Inserting FutbolPlayers into CosmosDB... "); //-CosmosDB await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.FutbolPlayerContainer, CosmosDBConstants.PartitionKey); var futbolPlayersContainer = cosmosClient.GetContainer(CosmosDBConstants.DatabaseName, CosmosDBConstants.FutbolPlayerContainer); var totalPlayers = futbolPlayers.Count; var iPlayers = 0; var batchPlayers = batchSize; while (iPlayers < totalPlayers) { var playersToSend = futbolPlayers.Skip(iPlayers).Take(batchPlayers).ToList(); await cosmosClient.AddBulkItemsAsync(futbolPlayersContainer, playersToSend); iPlayers += batchPlayers; } Console.WriteLine("Done"); Console.Write("Inserting FutbolPlayers into PlayFab... "); //-PlayFab await playFabClient.SetCatalogItems(futbolPlayers); await playFabClient.SetStoreItems(futbolPlayers); Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting Futbol Players: {ex.Message}"); } try { Console.Write("Inserting FutbolTeams into CosmosDB... "); await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.FutbolTeamContainer, CosmosDBConstants.PartitionKey); var futbolTeamsContainer = cosmosClient.GetContainer(CosmosDBConstants.DatabaseName, CosmosDBConstants.FutbolTeamContainer); var totalTeams = teams.Count; var iTeams = 0; var batchTeams = batchSize; while (iTeams < totalTeams) { var teamsToSend = teams.Skip(iTeams).Take(batchTeams).ToList(); await cosmosClient.AddBulkItemsAsync(futbolTeamsContainer, teamsToSend); iTeams += batchTeams; } Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting Futbol Teams: {ex.Message}"); } try { Console.Write("Inserting Matches into CosmosDB... "); await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.MatchContainer, CosmosDBConstants.PartitionKey); var matchesContainer = cosmosClient.GetContainer(CosmosDBConstants.DatabaseName, CosmosDBConstants.MatchContainer); var totalMatches = matches.Count; var iMatches = 0; var batchMatches = batchSize; while (iMatches < totalMatches) { var matchesToSend = matches.Skip(iMatches).Take(batchMatches).ToList(); await cosmosClient.AddBulkItemsAsync(matchesContainer, matchesToSend); iMatches += batchMatches; } Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting Matches: {ex.Message}"); } #endregion #region Populate PlayFab Title try { Console.Write("Inserting UserTeam into PlayFab... "); //-PlayFab //Clean inventory var inventory = await playFabClient.GetUserInventoryUsingAdminAPI(dataSeederConfig.PlayFabId); await playFabClient.RevokeInventoryItems(dataSeederConfig.PlayFabId, inventory); var userTeam = userTeamData.FirstOrDefault(); var starters = userTeam.Players.Take(dataSeederConfig.TournamentConfig.TeamStartersAmount).ToList(); var subs = userTeam.Players.Skip(dataSeederConfig.TournamentConfig.TeamStartersAmount).Take(dataSeederConfig.TournamentConfig.TeamSubsAmount).ToList(); //Starters var grantedStarters = await playFabClient.GrantItemstoUser(dataSeederConfig.PlayFabId, starters); var starterData = new Dictionary <string, string> { { "IsStarter", "true" } }; foreach (var item in grantedStarters) { await playFabClient.UpdateUserInventoryItemCustomData(dataSeederConfig.PlayFabId, item.ItemInstanceId, starterData); } //Substitutes var grantedSubstitutes = await playFabClient.GrantItemstoUser(dataSeederConfig.PlayFabId, subs); var substituteData = new Dictionary <string, string> { { "IsStarter", "false" } }; foreach (var item in grantedSubstitutes) { await playFabClient.UpdateUserInventoryItemCustomData(dataSeederConfig.PlayFabId, item.ItemInstanceId, substituteData); } //User statistics var statistics = new Dictionary <string, int> { { "TournamentScore", 2100 } }; await playFabClient.UpdatePlayerStatistics(dataSeederConfig.PlayFabId, statistics); Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting User Teams: {ex.Message}"); } try { Console.Write("Inserting UserTransactions into Cosmos DB... "); await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.UserTransactionContainer, CosmosDBConstants.PartitionKey); var userTransactionC = cosmosClient.GetContainer(CosmosDBConstants.DatabaseName, CosmosDBConstants.UserTransactionContainer); var totalUserTransactions = userTransactionData.Count; var iUserTransactions = 0; var batchUserTransactions = batchSize; while (iUserTransactions < totalUserTransactions) { var userTransactionsToSend = userTransactionData.Skip(iUserTransactions).Take(batchUserTransactions).ToList(); await cosmosClient.AddBulkItemsAsync(userTransactionC, userTransactionsToSend); iUserTransactions += batchUserTransactions; } Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when inserting User Transactions: {ex.Message}"); } try { Console.Write("Generating MatchPlayerPerformance container into Cosmos DB... "); await cosmosClient.CreateContainerAsync(CosmosDBConstants.DatabaseName, CosmosDBConstants.MatchPlayerPerformanceContainerId, CosmosDBConstants.PartitionKey); Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine($"EXCEPTION when generating MatchPlayerPerformance Container: {ex.Message}"); } #endregion }