protected void ReinitializeTotals() { totalsLast = ReinitializeTotal(); totalsCorrection = ReinitializeTotal(); totalsDeltas = ReinitializeTotal(); totalsResult = ReinitializeTotal(); }
public async Task <InventorySet> PostMaterialsSheet(InventorySet totals) { // Invalidate the Cache MaterialsCache = null; var postData = new Dictionary <string, string>(); await GetMaterialsSheet(); foreach (var mat in totals.Keys) { if (!MaterialInaraIDLookup.Keys.Contains(mat)) { throw new Exception("Material '" + mat + "' does not exist on Inara"); } postData.Add("playerinv[" + MaterialInaraIDLookup[mat] + "]", totals[mat].ToString()); } postData.Add(LocField, PostLocation); postData.Add(ActField, PostAction); // POST the form var response = await FormPost(MatsSheetURL + GetEliteSheet(), postData); // Parse the DOM return(await parseMaterialsSheet(response)); }
private void AddToTotal(InventorySet totes, string key, int delta) { var t = MaterialTypeLookup[key]; totes["Grand"] += delta; totes[t] += delta; }
private DataGridView GetDGV(InventorySet pouch) { // Add DataGrid var dgv = GetBaseDataGrid(pouch); // Get Columns var item = GetItemColumn(ColumnItem = 0); var count = GetCountColumn(ColumnCount = 1); var use = GetUseColumn(ColumnUse = 2); var flag1 = GetFlagColumn(ColumnFlag1 = 3, nameof(Item.Flags0)); var flag2 = GetFlagColumn(ColumnFlag2 = 4, nameof(Item.Flags1)); var flag3 = GetFlagColumn(ColumnFlag3 = 5, nameof(Item.Flags2)); dgv.Columns.Add(item); dgv.Columns.Add(count); dgv.Columns.Add(use); dgv.Columns.Add(flag1); dgv.Columns.Add(flag2); dgv.Columns.Add(flag3); // Populate with rows var itemarr = items; item.Items.AddRange(itemarr); dgv.Rows.Add(pouch.Items.Count); dgv.CancelEdit(); return(dgv); }
public void ApplyUpdates(InventorySet result) { var dm = DataMangler.GetInstance(); var cshk = CurrentState.History.Keys; InventorySet patch = CurrentState.History[cshk.Max()]; foreach (var update in dm.GetUpdates(result, CurrentState.DataVersion)) { if (!result.ContainsKey(update)) { result[update] = 0; } if (!patch.ContainsKey(update)) { patch[update] = 0; } } if (patch.Count == 0) { return; } CurrentState.DataVersion = dm.DataVersion; }
private void SetList(DataGridView dgv, InventorySet pouch) { for (int i = 0; i < dgv.Rows.Count; i++) { var cells = dgv.Rows[i].Cells; var str = cells[ColumnItem].Value.ToString(); var itemindex = Array.IndexOf(items, str); int.TryParse(cells[ColumnCount].Value?.ToString(), out int itemcnt); int.TryParse(cells[ColumnUse].Value?.ToString(), out int uses); int.TryParse(cells[ColumnFlag1].Value?.ToString(), out int flags1); int.TryParse(cells[ColumnFlag2].Value?.ToString(), out int flags2); int.TryParse(cells[ColumnFlag3].Value?.ToString(), out int flags3); var item = pouch.Items[i]; // Undo our handling of NONE if (itemindex <= 0) { itemindex = Item.NONE; } item.ItemId = (ushort)itemindex; item.Count = (byte)itemcnt; item.UseCount = (ushort)uses; item.Flags0 = (byte)flags1; item.Flags1 = (byte)flags2; item.Flags1 = (byte)flags3; } }
protected async void OnFirstLoadMats(object sender, EventArgs e) { form.SetLoadingState(); InitialMats = await api.GetMaterialsSheet(); UpdateMaterialsList(); form.SetReadyState(); }
public override async Task <List <NearestStoreLocation> > Run(GetNearestStoreDetailsByLocationArgument locationInfo, CommercePipelineExecutionContext context) { List <InventorySet> inventorySets = new List <InventorySet>(); GetNearestStoreDetailsByLocationBlock getNearestStoreDetailsByLocationBlock = this; FindEntitiesInListArgument entitiesInListArgument = await getNearestStoreDetailsByLocationBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(InventorySet), string.Format("{0}", (object)CommerceEntity.ListName <InventorySet>()), 0, int.MaxValue), context); if (entitiesInListArgument != null) { CommerceList <CommerceEntity> list = entitiesInListArgument.List; if (list != null) { list.Items.ForEach((Action <CommerceEntity>)(item => { InventorySet inventorySet = (InventorySet)item; inventorySets.Add(inventorySet); })); } } var storeComponents = inventorySets.Select(x => x.GetComponent <StoreDetailsComponent>()); storeComponents = storeComponents.Where(x => x.Lat != null).ToList(); List <Locations> locations = new List <Locations>(); locations.AddRange(storeComponents.Select(x => x != null ? new Locations() { City = x.City, Latitude = Convert.ToDouble(x.Lat), Longitude = Convert.ToDouble(x.Long) } : new Locations())); var coord = new GeoCoordinate(locationInfo.Latitude, locationInfo.Longitude); var nearestStoresinOrder = locations.Select(x => new GeoCoordinate(x.Latitude, x.Longitude)) .OrderBy(x => x.GetDistanceTo(coord)).Select(z => new Locations { Distance = z.GetDistanceTo(coord), Latitude = z.Latitude, Longitude = z.Longitude }).ToList(); List <NearestStoreLocation> stores = new List <NearestStoreLocation>(); stores.AddRange(nearestStoresinOrder.Select(x => new NearestStoreLocation() { Distance = x.Distance, InventoryStoreId = GetStoreId(x.Latitude, x.Longitude, inventorySets), Address = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().Address, Longitude = x.Longitude, Latitude = x.Latitude, Name = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().Name, City = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().City, Zip = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().ZipCode, StateCode = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().StateCode, CountryCode = GetStoreDetails(x.Latitude, x.Longitude, inventorySets).GetComponent <StoreDetailsComponent>().CountryCode })); return(stores); }
protected void AddMats( InventorySet mats, EliteJournalEntry entry) { foreach (var mat in mats) { NotifyInventory(mat.Key, mat.Value, entry); } }
protected InventorySet ReinitializeTotal() { var totals = new InventorySet(); foreach (var type in MaterialTypes) { totals[type] = 0; } return(totals); }
/// <summary> /// Handle user-requested reload /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> protected async void OnReloadMats(object sender, EventArgs e) { // Get Materials, potentially cached from login form.SetLoadingState(); api.ClearMaterialsCache(); InitialMats = await api.GetMaterialsSheet(); UpdateMaterialsList(); form.SetReadyState(); }
/// <summary> /// Gets the current inventory from the perspective of the Picard state file /// </summary> /// <returns> /// A dictionary of all the materials and changes that have been recorded /// in the Picard state file /// </returns> public InventorySet CalculateCurrentInventory() { InventorySet result = new InventorySet(); foreach (var time in CurrentState.History) { result = result + time.Value; } return(result); }
/// <summary> /// Adds a set of materials to the history /// </summary> /// <param name="d"> /// The current set of materials from this run /// </param> public void AddHistory(InventorySet d) { var now = DateTime.UtcNow; if (CurrentState.History.ContainsKey(now)) { CurrentState.History[now] += d; } else { CurrentState.History.Add(DateTime.UtcNow, d); } }
public void AddIgnore(InventorySet inv) { using (StreamWriter w = File.AppendText(IgnoreFile)) { foreach (var i in inv.Keys) { if (!IgnoreCommodities.Contains(i)) { IgnoreCommodities.Add(i); } w.WriteLine(i); } } }
public FirstRunController(InaraApi api, PersistentState state) { this.api = api; this.state = state; // Set up main form and event handlers form = new MatInitialVerifyForm(); form.ReloadMats += OnReloadMats; form.FirstLoadMats += OnFirstLoadMats; form.CloseWithoutSaving += OnCloseWithoutSaving; form.CloseAndSave += OnCloseAndSave; form.Activated += OnReloadMats; InitialMats = null; }
/// <summary> /// Filters only known material names in EliteMatsLookup /// and also translates them into a localized material name /// </summary> /// <param name="deltas">The dict to filter and translate</param> /// <param name="removed">Will add removed materials to this /// dictionary if they are not in the IgnoreCommdoties list</param> /// <returns>The filtered and translated dict</returns> public InventorySet FilterAndTranslateMats(InventorySet deltas, InventorySet removed) { // TODO: This should really be looking at the data just pulled // from Inara var ret = new InventorySet(); foreach (var mat in deltas) { if (EliteMatsLookup.ContainsKey(mat.Key.ToLower())) { ret.AddMat(EliteMatsLookup[mat.Key.ToLower()], mat.Value); } else if (!IgnoreCommodities.Contains(mat.Key.ToLower())) { removed.AddMat(mat.Key.ToLower(), mat.Value); } } return(ret); }
private static DataGridView GetBaseDataGrid(InventorySet pouch) { return(new DataGridView { Dock = DockStyle.Fill, Text = pouch.Type.ToString(), Name = "DGV_" + pouch.Type, AllowUserToAddRows = false, AllowUserToDeleteRows = false, AllowUserToResizeRows = false, AllowUserToResizeColumns = false, RowHeadersVisible = false, MultiSelect = false, ShowEditingIcon = false, EditMode = DataGridViewEditMode.EditOnEnter, ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single, ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize, SelectionMode = DataGridViewSelectionMode.CellSelect, CellBorderStyle = DataGridViewCellBorderStyle.None, }); }
private void GetList(DataGridView dgv, InventorySet pouch) { for (int i = 0; i < dgv.Rows.Count; i++) { var cells = dgv.Rows[i].Cells; var item = pouch.Items[i]; // Treat NONE as 0 var id = item.ItemId; if (id == Item.NONE) { id = 0; } cells[ColumnItem].Value = items[id]; cells[ColumnCount].Value = item.Count; cells[ColumnUse].Value = item.UseCount; cells[ColumnFlag1].Value = item.Flags0; cells[ColumnFlag2].Value = item.Flags1; cells[ColumnFlag3].Value = item.Flags2; } }
protected async Task <InventorySet> parseMaterialsSheet(HttpResponseMessage response) { var found = new InventorySet(); var dom = await ParseHtml(response); // Look for all nodes with class inventorymaterial foreach (var node in findAllNodeByAttributeValue(dom, "class", "inventorymaterial")) { // The name is in the span var mat = node.Descendants("span").First().InnerText; // If we have already found this, ignore if (found.ContainsKey(mat)) { continue; } // The count is in a form input var value = node.Descendants("input").First().GetAttributeValue("value", 0); // Add the material to be returned found.Add(mat, value); try { // Add the material and its ID to the Material ID lookup for later use // We do this on every page load because no reason not to, and if they // change their IDs for some reason, shouldn't hurt us var inputName = node.Descendants("input").First().GetAttributeValue("name", "playerinv[-1]"); if (!inputName.StartsWith("playerinv[")) { Console.WriteLine("DOM Error: " + inputName); continue; } var match = Regex.Match(inputName, @"playerinv\[(\w+)\]", RegexOptions.IgnoreCase); if (match.Groups.Count < 2) { Console.WriteLine("Regex Error:"); Console.WriteLine(match.ToString()); continue; } var num = int.Parse(match.Groups[1].Captures[0].ToString()); if (MaterialInaraIDLookup.ContainsKey(mat)) { MaterialInaraIDLookup[mat] = num; } else { MaterialInaraIDLookup.Add(mat, num); } } catch (Exception e) { Console.WriteLine(e.ToString()); throw e; } } MaterialsCache = found; return(found); }
protected async void OnReloadMats(object sender, EventArgs e) { LastMTime = logs.GetMostRecentLogWrite(); // Indicate that we are loading something form.SetLoadingState(); // Initialize empty InventorySet of unknown "materials" unknown = new InventorySet(); // Initialize empty InventorySet of deltas from log files deltas = new InventorySet(); // Get last run materials from Picard State last = state.CalculateCurrentInventory(); // Apply and store any updates to the data format state.ApplyUpdates(last); // Get Inara corrections, if any inaraCorrection = await FigureOutInaraCorrection(); var lastUpdate = state.GetLastUpdateTimestamp(); // Parse logs and get the changes to material counts // The filtering function adds unrecognized materials to unknown list var MatHandler = new InventoryHandler(dm.EngineerCostLookup); MatHandler.InventoryChanged += (object invSender, InventoryEventArgs ie) => { if (ie.JournalEntry.Timestamp < lastUpdate) { return; } // If it's not for the Picard commander, ignore if (MatHandler.CurrentCmdr != state.CurrentState.EliteCmdrName) { return; } var mat = ie.Name.ToLower(); if (dm.EliteMatsLookup.ContainsKey(mat)) { deltas.AddMat(dm.EliteMatsLookup[mat], ie.Delta); } else if (!dm.IgnoreCommodities.Contains(mat)) { unknown.AddMat(mat, ie.Delta); } }; var ChHandler = new CharacterHandler(); ChHandler.CharacterDied += (object chSender, DeathEventArgs de) => { if (de.JournalEntry.Timestamp < lastUpdate) { return; } foreach (var comm in dm.MaterialTypeLookup) { if (comm.Value != "Commodities") { continue; } var c = comm.Key; if (last.ContainsKey(c)) { deltas[c] = -last[c]; } else if (deltas.ContainsKey(c)) { deltas[c] = 0; } } }; foreach (var entry in logs.GetLogEntries()) { entry.Accept(ChHandler); entry.Accept(MatHandler); } // Apply changes to material counts result = last + deltas; // If there is a correction, also add that to the mat counts if (inaraCorrection != null) { result = result + inaraCorrection; } // Add all of the data we found above to the form UpdateFormWithCurrentMats(); // Hand control back to the user // If deltas are not empty or there is a corretion, we have stuff to save form.SetReadyState( !deltas.IsZero || inaraCorrection != null); // If there are unknown materials, tell the user the // bad news, and prevent the window close. if (unknown.Count > 0) { var ackForm = new UnrecognizedMaterials(unknown); ackForm.ShowDialog(); dm.AddIgnore(unknown); OnReloadMats(sender, e); } }
/// <summary> /// Clear the materials cache so that on the next call to /// GetMaterialsSheet, it will go fetch from Inara /// </summary> public void ClearMaterialsCache() { MaterialsCache = null; }
public IEnumerable <string> GetUpdates(InventorySet data, int ver) { return(from version in VersionAdded where version.Value > ver select version.Key); }
public async Task <List <InventorySet> > Process(CommerceContext commerceContext, List <CreateStoreInventorySetArgument> inputArgumentList, List <string> productsToAssociate, string catalogName) { CreateStoreInventoryCommand createStoreInventoryCommand = this; List <InventorySet> sets = new List <InventorySet>(); using (CommandActivity.Start(commerceContext, createStoreInventoryCommand)) { await createStoreInventoryCommand.PerformTransaction(commerceContext, async() => { CommercePipelineExecutionContextOptions pipelineContextOptions = commerceContext.PipelineContextOptions; foreach (CreateStoreInventorySetArgument arg in inputArgumentList) { InventorySet inventorySet2 = await this._createStoreInventorySetPipeline.Run(arg, pipelineContextOptions).ConfigureAwait(false); if (inventorySet2 != null) { sets.Add(inventorySet2); } else { // find the entity set id and add - for further processng in associate sets.Add(new InventorySet() { Id = CommerceEntity.IdPrefix <InventorySet>() + arg.Name }); } } }); } // Update all products if no input passed if (productsToAssociate.Count == 0) { var products = await this._getProductsToUpdateInventoryPipeline.Run(catalogName, commerceContext.PipelineContextOptions).ConfigureAwait(false); productsToAssociate = products; if (productsToAssociate == null) { return(null); } } // Once Done.. then assign inventory to products in the sets // Associate Sellable Item to Inventory Set foreach (var product in productsToAssociate) { using (CommandActivity.Start(commerceContext, createStoreInventoryCommand)) { var productIds = product.Split('|'); string variantId = null; var productId = product.Split('|').FirstOrDefault(); if (productIds.Count() > 1) { variantId = product.Split('|').Skip(1).FirstOrDefault(); } SellableItemInventorySetsArgument args = new SellableItemInventorySetsArgument() { InventorySetIds = sets.Select(x => x.Id).ToList(), SellableItemId = productId, VariationId = variantId }; bool result = await this._associateStoreInventoryToSellableItem.Run(args, commerceContext.PipelineContextOptions).ConfigureAwait(false); } } return(sets); }
private DataMangler() { MaterialTypes = new List <string>(); MaterialOrder = new List <string>(); IgnoreCommodities = new List <string>(); EliteMatsLookup = new Dictionary <string, string>(); MaterialTypeLookup = new Dictionary <string, string>(); EngineerCostLookup = new Dictionary <string, InventorySet>(); VersionAdded = new Dictionary <string, int>(); // Possible Material Types MaterialTypes.Add("Materials"); MaterialTypes.Add("Data"); MaterialTypes.Add("Commodities"); // Load from Confirmed Types using (StringReader r = new StringReader( Properties.Resources.EliteInaraLookups)) { // Current Line will be stored here string line = ""; // Beginnings of columns, marked by ; character int[] begins = { -1, -1, -1, -1 }; // Lengths of columns int[] lengths = { -1, -1, -1 }; // Column Values string name, type, journal; int version; while ((line = r.ReadLine()) != null) { // Comment Line if (line[0] == '#' || line.Trim().Length == 0) { continue; } // Heading Line if (line[0] == ';') { int i = 0, prev = 0, next = 1; while (i < 3) { begins[i] = prev; next = line.IndexOf(';', next); lengths[i] = next - prev - 1; prev = next; next++; i++; } begins[i] = prev; continue; } // Data Line if (begins[0] == -1) { throw new Exception("Data Manglement Exception - Lookup Table Corrupted"); } // Parse the Column Values name = line.Substring(begins[0], lengths[0]).Trim(); type = line.Substring(begins[1], lengths[1]).Trim(); journal = line.Substring(begins[2], lengths[2]).Trim(); version = int.Parse(line.Substring(begins[3]).Trim()); // Store the Column Values if (type == "Irrelevant Commodity") { IgnoreCommodities.Add(name); } else { MaterialOrder.Add(name); EliteMatsLookup.Add(journal, name); MaterialTypeLookup.Add(name, type); VersionAdded.Add(name, version); } } DataVersion = VersionAdded.Values.Max(); } // Load from Local Ignore File string local = Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData); string path = @"TickleSoft"; string file = @"ignore"; IgnoreFile = Path.Combine(local, path, file); if (File.Exists(IgnoreFile)) { string[] ignores = File.ReadAllLines(IgnoreFile); foreach (var i in ignores) { if (!IgnoreCommodities.Contains(i)) { IgnoreCommodities.Add(i); } } } InventorySet mats; // Logs do not reflect the cost of unlocking an engineer, // so we look them up mats = new InventorySet(); EngineerCostLookup.Add("Felicity Farseer", mats); mats = new InventorySet(); EngineerCostLookup.Add("Elvira Martuuk", mats); mats = new InventorySet(); EngineerCostLookup.Add("The Dweller", mats); mats = new InventorySet(); EngineerCostLookup.Add("Liz Ryder", mats); mats = new InventorySet(); EngineerCostLookup.Add("Tod McQuinn", mats); mats = new InventorySet(); EngineerCostLookup.Add("Zacariah Nemo", mats); mats = new InventorySet(); EngineerCostLookup.Add("Lei Cheung", mats); mats = new InventorySet(); EngineerCostLookup.Add("Hera Tani", mats); mats = new InventorySet(); EngineerCostLookup.Add("Juri Ishmaak", mats); mats = new InventorySet(); EngineerCostLookup.Add("Selene Jean", mats); mats = new InventorySet(); mats.AddMat("modularterminals", -25); EngineerCostLookup.Add("Marco Qwent", mats); mats = new InventorySet(); mats.AddMat("scandatabanks", -50); EngineerCostLookup.Add("Ram Tah", mats); mats = new InventorySet(); EngineerCostLookup.Add("Broo Tarquin", mats); mats = new InventorySet(); EngineerCostLookup.Add("Colonel Bris Dekker", mats); mats = new InventorySet(); EngineerCostLookup.Add("Didi Vatermann", mats); mats = new InventorySet(); mats.AddMat("unknownenergysource", -25); EngineerCostLookup.Add("Professor Palin", mats); mats = new InventorySet(); EngineerCostLookup.Add("Lori Jameson", mats); mats = new InventorySet(); mats.AddMat("decodedemissiondata", -50); EngineerCostLookup.Add("Tiana Fortune", mats); mats = new InventorySet(); mats.AddMat("shieldpatternanalysis", -50); EngineerCostLookup.Add("The Sarge", mats); mats = new InventorySet(); mats.AddMat("bromellite", -50); EngineerCostLookup.Add("Bill Turner", mats); }
static void Main(string[] args) { EliteJournalParser logs = new EliteJournalParser(""); DataMangler dm = DataMangler.GetInstance(); InventorySet Deltas = new InventorySet(); IDictionary <string, IList <EliteJournalEntry> > MatSeen = new Dictionary <string, IList <EliteJournalEntry> >(); EliteJournalDebugHandler dhandler = new EliteJournalDebugHandler(); InventoryHandler mhandler = new InventoryHandler(dm.EngineerCostLookup); mhandler.InventoryChanged += (object sender, InventoryEventArgs e) => { Deltas.AddMat(e.Name, e.Delta); if (!MatSeen.ContainsKey(e.Name)) { MatSeen[e.Name] = new List <EliteJournalEntry>(); } MatSeen[e.Name].Add(e.JournalEntry); }; var handlers = new List <EliteJournalHandler>() { dhandler, mhandler }; foreach (var entry in logs.GetLogEntries()) { entry.Accept(dhandler); entry.Accept(mhandler); } #region Show unknown log entries foreach (var evt in dhandler.UnknownEvents) { Console.WriteLine("Unknown Event: " + evt); } #endregion #region Show confirmed material names var deltas = new InventorySet(); var seen = new Dictionary <string, IList <EliteJournalEntry> >(); // Normalize the names to lowercase foreach (var mat in Deltas) { var name = mat.Key.ToLower(); deltas.AddMat(name, mat.Value); if (!seen.ContainsKey(name)) { seen[name] = new List <EliteJournalEntry>(); } // Insert seen events in the appropriate order var i = 0; foreach (var e in MatSeen[mat.Key]) { bool wasInserted = false; while (i < seen[name].Count) { if (seen[name][i].Timestamp > e.Timestamp) { seen[name].Insert(i, e); wasInserted = true; break; } i++; } if (!wasInserted) { seen[name].Add(e); } } } foreach (var mat in deltas) { if (dm.IgnoreCommodities.Contains(mat.Key)) { Console.WriteLine("\"Ignored Commodity\",\"{0}\",{1},\"{2}\"", mat.Key.ToLower(), mat.Value, seen[mat.Key][0].Timestamp); } } foreach (var mat in deltas) { if (!dm.IgnoreCommodities.Contains(mat.Key)) { Console.WriteLine("\"Confirmed Material\",\"{0}\",{1},\"{2}\"", mat.Key.ToLower(), mat.Value, seen[mat.Key][0].Timestamp); } } #endregion // Prevent the console from closing Console.ReadLine(); }