public BulkQueryRequest(ParsedItem item, IStaticDataService staticDataService) { Exchange.Status.Option = StatusType.Online; Exchange.Want.Add(staticDataService.GetId(item.Name ?? item.TypeLine)); Exchange.Have.Add("chaos"); // TODO: Add support for other currency types? }
public async Task <FetchResult <string> > SearchBulk(ParsedItem item) { try { logger.Information("Querying Exchange API."); var uri = $"{languageProvider.Language.PoeTradeApiBaseUrl}exchange/{configuration.LeagueId}"; var json = JsonSerializer.Serialize(new BulkQueryRequest(item, staticDataService), poeTradeClient.Options); var body = new StringContent(json, Encoding.UTF8, "application/json"); var response = await httpClientProvider.HttpClient.PostAsync(uri, body); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync <FetchResult <string> >(content, poeTradeClient.Options); result.Uri = new Uri($"{languageProvider.Language.PoeTradeSearchBaseUrl}{configuration.LeagueId}/{result.Id}"); return(result); } else { var responseMessage = await response?.Content?.ReadAsStringAsync(); logger.Error("Querying failed: {responseCode} {responseMessage}", response.StatusCode, responseMessage); } } catch (Exception ex) { logger.Error(ex, "Exception thrown while querying trade api."); } return(null); }
public ParsedItem FindItem(string s) { ParsedItem result = new ParsedItem(); int start = s.IndexOf('<') + 1; if (s[start] == '?') { result.types = ItemTypes.ToSkip; } else if (s[start] == '/') { result.types = ItemTypes.CloseTag; } else { result.types = ItemTypes.OpenTag; int closingBPos = s.IndexOf('>'); int end = s.Substring(start, closingBPos - start + 1).IndexOf(' '); if (end < 0) { end = closingBPos - 1; } result.tag = s.Substring(start, end - start + 1).Trim(); string rest = s.Substring(closingBPos + 1).Trim(); int nextStart = rest.IndexOf('<'); if (nextStart > 0) { result.element = rest.Substring(0, nextStart); } } return(result); }
public void TestParserSql() { string sql1 = @"SELECT (SELECT top 1 sklad FROM lcs.sk_hlavicka h WHERE h.cislo_subjektu = s.cislo_subjektu) ,s.* FROM lcs. [subjekty] s with (updlock, holdlock) /* podmnožina hlaviček pro pořadač 15307 a sklady s referencí 6%, a doklady s referencí obsahující 3 */ inner join (select * from lcs.sk_hlavicka where cislo_poradace = 15307) x on x.cislo_subjektu = s.cislo_subjektu and (x.sklad in (select sk.cislo_subjektu from lcs.sk_sklad sk join lcs.subjekty su on su.cislo_subjektu = sk.cislo_subjektu where su.reference_subjektu like '6%')) where s.reference_subjektu like '%3%' or s.nazev_subjektu = 'Kontra''A'; DECLARE @cislo INT; SET @cislo = 15307; "; ParsedItem result = Parser.ParseString(sql1, DefaultSettings.MsSql); string sql2 = result.Text; string sql3 = ((IParsedItemExtended)result).TextEdit; string rtf = ((IParsedItemExtended)result).RtfText; string segmentName = DefaultSettings.SQL_CODE; string tables = ""; result.ScanItems( null, f => (f.SegmentName == segmentName), t => { if (t.ItemType == Data.Parsing.ItemType.Text) { tables += t.Text + "; "; } return(null); }); }
public void Parse() { StreamReader streamReader = new StreamReader(fileName); string xmlLines = streamReader.ReadToEnd(); InformationElements currentNode = rootElementt; while (xmlLines.Length > 0) { ParsedItem parsedItem = FindItem(xmlLines); switch (parsedItem.types) { case ItemTypes.OpenTag: currentNode = currentNode.AddChild(parsedItem.tag, parsedItem.element); break; case ItemTypes.CloseTag: currentNode = currentNode.GetParent(); break; case ItemTypes.ToSkip: break; } int nextTag = xmlLines.IndexOf('<', 1); if (nextTag < 0) { break; } xmlLines = xmlLines.Substring(nextTag); } }
/// <summary> /// Takes an instance and reduces it to an integer, or throws an exception if this is not possible /// </summary> /// <param name="source">The source line, used to give indicative error messags</param> /// <param name="instance">The instance to reduce</param> /// <param name="scope">The scope to use</param> /// <returns>An integer</returns> public int ResolveToInteger(ParsedItem source, IInstance instance, ScopeState scope) { if (instance is Instance.ConstantReference constDecl) { var dt = ResolveTypeName(constDecl.Source.DataType, scope); if (dt == null) { throw new ParserException($"Failed to resolve data type: {constDecl.Source.DataType}", source); } if (!dt.IsInteger) { throw new ParserException($"Cannot use item of type {constDecl.Source.DataType} as an integer is required", source); } return(((AST.IntegerConstant)((AST.LiteralExpression)constDecl.Source.Expression).Value).ToInt32); } else if (instance is Instance.Literal lit) { if (!(lit.Source is AST.IntegerConstant intConst)) { throw new ParserException($"Cannot use literal of type {lit.Source} as an integer is required", source); } return(intConst.ToInt32); } throw new ParserException($"Must use a constant or literal integer value, got {instance}", source); }
// This function reads the whole file into a list of "ParsedItem" objects private static List <ParsedItem> ParseTextFile(TextReader reader) { var items = new List <ParsedItem>(); using (reader) { Section section = Section.None; string str; while ((str = reader.ReadLine()) != null) { str = str.Trim(); // Skip blank lines if (str.Length == 0) { continue; } // Skip comments if (str[0] == ';') { continue; } // Section definition if (str[0] == '.') { section = ParseSection(str.Substring(1)); continue; } // Item name if (str[0] == '[') { string itemName = str.Substring(1, str.Length - 2); var item = new ParsedItem(section, itemName); items.Add(item); continue; } // The rest is in the form <keyword or number>=<string> if (items.Count == 0) { throw new InvalidDataException("Entry outside of section/item in .INS file: " + str); } var split = str.Split('='); if (split.Length != 2) { throw new InvalidDataException("Malformed entry in .INS file: " + str); } items[items.Count - 1].AddValue(split[0], split[1]); } } return(items); }
public void Test_Parse_Price() { string s = "G 75901 20 106 160 M M L L L L XXS XS XS XS XS S S S S M M M M"; ParsedItem p = _gjExcelParser.ParseLine(s); Assert.AreEqual(106m, p.Price, "Price is not good"); }
public void Test_Only_Code_Is_Present() { string s = "488160-203 57 49 7 7 7 7 8 8"; ParsedItem pi = _gjExcelParser.ParseLine(s); Assert.AreEqual("488160-203", pi.InternalCode, "Expected InternalCode to be 488160-203"); }
/// <summary> /// Performs the conversion /// </summary> /// <param name="parsedItem">The input object</param> /// <returns>The output object, or null if the object could not be converted</returns> public IInventoryItem Convert(ParsedItem parsedItem) { if (parsedItem == null) { return(null); } return(_itemFactory.Create(parsedItem.Name, parsedItem.SellBy, parsedItem.Quality)); }
/// <summary> /// Creates and returns a URI link for the given item in a format matching that of the poe gamepedia website /// Only works with items that are not rare or magic /// </summary> private Uri CreateItemWikiLink(ParsedItem item) { // determine search link, so wiki can be opened for any item var searchLink = item.Name ?? item.TypeLine; // replace space encodes with '_' to match the link layout of the poe wiki and then url encode it var itemLink = System.Net.WebUtility.UrlEncode(searchLink.Replace(" ", "_")); return(new Uri(WIKI_BASE_URI + itemLink)); }
public PoeNinjaItem GetItem(ParsedItem item) { // TODO: Ensure cached items are from the currently selected league (league change needs a few sec to update) //if(!IsInitialized) //{ // throw new Exception("Cache not yet initialized. Call Refresh() before trying to get an item."); //} return(Items.FirstOrDefault(x => x.Name == item.Name)); }
public static string GetColor(this ParsedItem item) { return(item?.Rarity switch { Rarity.Normal => "#c8c8c8", Rarity.Magic => "#8888ff", Rarity.Rare => "#ffff77", Rarity.Unique => "#af6025", _ => "#aa9e82", });
public async Task OpenWebpage(ParsedItem item) { if (item.Rarity == Rarity.Currency) { nativeBrowser.Open((await SearchBulk(item)).Uri); } else { nativeBrowser.Open((await Search(item)).Uri); } }
public static Item ItemFromParse(ParsedItem parse) { var item = new Item(); item.Name = parse.Name; item.Category = parse.Category; item.MarketCategory = parse.MarketCategory; item.VendorCost = parse.VendorCost; item.VendorSells = parse.VendorSells; return(item); }
public void Test_Product_Sizes() { string s = "plimcana clean D65623 31 152 41 41 42 42 43 43 43 43 43 43 44 44 44 44 44,5 44,5 40,5 240 44,5 44,,5 44;5 45 45 45 45 46 46 46;5 46;5 47 48 48,5 48,5 "; ParsedItem pi = _gjExcelParser.ParseLine(s); Assert.AreEqual(32, pi.CalculateTotalQuantity(), "Expected 32 sizes, got: " + pi.CalculateTotalQuantity()); ItemSizeQuantity size = pi.Sizes.First(x => x.Size == "43"); Assert.AreEqual(6, size.Quantity, "Expected to 6 products with size 43. Got: " + size.Quantity); }
public void Test_Parse_ProductName_And_Code_Together() { string s = "super skate G 05415 3 133 44 44,5 41 42 43 220 "; ParsedItem pi = _gjExcelParser.ParseLine(s); string expectedName = "super skate"; Assert.AreEqual(expectedName, pi.ProductName, "Name is `" + pi.ProductName + "`expected to be: " + expectedName); expectedName = "G 05415"; Assert.AreEqual(expectedName, pi.InternalCode, "Internal code is `" + pi.InternalCode + "`expected to be: " + expectedName); }
private Uri CreateUri(ParsedItem item) { var subUrl = item.Rarity switch { Rarity.Unique => SubUrlUnique, Rarity.Gem => SubUrlGem, _ => SubUrlItem }; var searchLink = item.Name ?? item.TypeLine; var wikiLink = subUrl + searchLink.Replace(" ", "+"); return(new Uri(PoeDbBaseUri + wikiLink)); } }
private static ParsedItem ExtractParsedItemBySection(List <ParsedItem> items, Section section) { ParsedItem result = null; foreach (var pi in items) { if (pi.Section == section) { items.Remove(pi); result = pi; break; } } return(result); }
public ParsedItem FindItem(string s) { ParsedItem result = new ParsedItem(); int startTag = s.IndexOf('<') + 1; if (s[startTag] == '?') { result.types = ItemTypes.ToSkip; } else if (s[startTag] == '/') { result.types = ItemTypes.CloseTag; } else { result.types = ItemTypes.OpenTag; int closingBPos = s.IndexOf('>'); int endTag = s.IndexOf(' ', startTag, closingBPos - startTag + 1); if (endTag < 0) { endTag = closingBPos - 1; } else { string attrStr = s.Substring(endTag + 1, closingBPos - 1 - endTag); string[] attributes = attrStr.Split(" ".ToCharArray()); if (attributes.Length > 0) { result.attr = new List <string>(); foreach (string a in attributes) { result.attr.Add(a.Replace('=', '-')); } } } result.tag = s.Substring(startTag, endTag - startTag + 1).Trim(); string rest = s.Substring(closingBPos + 1).Trim(); int startNextTag = rest.IndexOf('<'); if (startNextTag > 0) { result.element = rest.Substring(0, startNextTag); } } return(result); }
protected virtual ParsedItem ExtractInternalCodeFromName(ParsedItem pi) { if (pi.ProductName == null) { throw new ArgumentNullException("ProductName", "Could not extract Code from ProductName, ProductName is null"); } // super skate G 05415 // cc a.t. Q 23572 Match m = _rxNameAndCode.Match(pi.ProductName); if (m.Success) { pi.InternalCode = string.Concat(m.Groups[2].Value.ToUpper(), " ", m.Groups[4].Value.Trim()); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return(pi); } // NK 429716-104 m = _rxNameCodeDashed.Match(pi.ProductName); if (m.Success) { pi.InternalCode = string.Concat(m.Groups[2].Value.Trim(), "-", m.Groups[4].Value.Trim()); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return(pi); } // terex 043980 m = _rxNameCodeDigits.Match(pi.ProductName); if (m.Success) { pi.InternalCode = m.Groups[2].Value.Trim(); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return(pi); } // Just code instead of name m = _rxCodeWithDash.Match(pi.ProductName); if (m.Success) { pi.InternalCode = pi.ProductName; pi.ProductName = ""; return(pi); } return(pi); }
public void Test_InternalCode_Is_Dash_Digits() { string s = "NK 429716-104 1 144,49 42,5 48,5 260 "; ParsedItem pi = _gjExcelParser.ParseLine(s); string expS; decimal expD; expS = "NK"; Assert.AreEqual(expS, pi.ProductName, "Expected name: " + expS + ", got: " + pi.ProductName); expS = "429716-104"; Assert.AreEqual(expS, pi.InternalCode, "Expected internal code: " + expS + ", got: " + pi.InternalCode); expD = 144.49m; Assert.AreEqual(expD, pi.Price, "Expected price: " + expD + ", got: " + pi.Price); expD = 260; Assert.AreEqual(expD, pi.PriceOfRelease, "Expected price of release: " + expD + ", got: " + pi.PriceOfRelease); }
public void Test_InternalCode_Is_Only_Digits() { string s = "terex 043980 1 170 36,5 38 240 "; ParsedItem pi = _gjExcelParser.ParseLine(s); string expS; decimal expD; expS = "terex"; Assert.AreEqual(expS, pi.ProductName, "Expected name: " + expS + ", got: " + pi.ProductName); expS = "043980"; Assert.AreEqual(expS, pi.InternalCode, "Expected internal code: " + expS + ", got: " + pi.InternalCode); expD = 170m; Assert.AreEqual(expD, pi.Price, "Expected price: " + expD + ", got: " + pi.Price); expD = 240; Assert.AreEqual(expD, pi.PriceOfRelease, "Expected price of release: " + expD + ", got: " + pi.PriceOfRelease); }
public void Open(ParsedItem item) { if (item == null) { return; } if (languageProvider.Current.Name != languageProvider.DefaultLanguage) // Only English for now { return; } if (string.IsNullOrEmpty(item.Name)) { logger.Warning("Unable to open PoeDB for specified item as it has no name! {@item}", item); return; } nativeBrowser.Open(CreateUri(item)); }
/// <summary> /// Attempts to generate and open the wiki link for the given item /// </summary> public void Open(ParsedItem item) { if (item == null) { return; } // only available for english portal if (!languageProvider.IsEnglish) { return; } // Most items will open the basetype wiki link. // Does not work for unique items that are not identified. if (string.IsNullOrEmpty(item.Name)) { logger.Warning("Unable to open POE Wiki for specified item as it has no name! {@item}", item); return; } nativeBrowser.Open(CreateItemWikiLink(item)); }
private void PushToCodeExplorerAsParameter(ParsedItem pars) { // To code explorer, program parameters if (_isBaseFile && pars.Scope is ParsedFile) { string subText = null; var parsDefine = pars as ParsedDefine; if (parsDefine != null) { subText = parsDefine.PrimitiveType == ParsedPrimitiveType.Unknow ? parsDefine.Type.ToString() : parsDefine.PrimitiveType.ToString(); } PushToCodeExplorer( GetExplorerListNode("Program parameters", CodeExplorerIconType.ProgramParameter), new ParameterCodeItem { DisplayText = pars.Name, Flags = pars.Flags, SubText = subText, DocumentOwner = pars.FilePath, GoToLine = pars.Line, GoToColumn = pars.Column }); } }
/// <summary> /// Call this method instead of adding the items directly in the list, /// updates the scope and file name /// </summary> private void AddParsedItem(ParsedItem item, ushort ownerNumber) { // add external flag + include line if needed if (ownerNumber > 0 && ownerNumber < _parsedIncludes.Count) { item.FilePath = _parsedIncludes[ownerNumber].FullFilePath; item.IncludeLine = _parsedIncludes[ownerNumber].Line; item.Flags |= ParseFlag.FromInclude; } else { item.FilePath = _filePathBeingParsed; } item.Scope = GetCurrentBlock <ParsedScopeBlock>(); // add the item name's to the known temp tables? if (!_knownWords.ContainsKey(item.Name) && item is ParsedTable) { _knownWords.Add(item.Name, CompletionType.Table); } _parsedItemList.Add(item); }
public ParsedItem ParseLine(string[] cells) { try { ParsedItem pi = new ParsedItem(); string sizeName; _logger.Debug("Parsing:"); for (int i = 0; i < cells.Length; i++) { _logger.DebugFormat(" cells[{0}]: {1}", i, cells[i]); if (IsCodeAndProductNameField(i)) { if (string.IsNullOrEmpty(cells[i])) { throw new ArgumentNullException("Product code/name field is empty"); //// Let's try to extract name from next cell (code) //if ((i + 1 < cells.Length) && String.IsNullOrWhiteSpace(cells[i + 1])) //{ // throw new ArgumentNullException("Product code/name field is empty"); //} } pi.ProductName = cells[i].Trim(); } else if (IsCodeField(i)) { // If code cell is empty - extract from product name "super skate G 05415" if (string.IsNullOrEmpty(cells[i])) { pi = ExtractInternalCodeFromName(pi); } else { pi.InternalCode = cells[i].Trim(); } } else if (IsQuantityField(i)) { if (String.IsNullOrEmpty(cells[i].Trim())) { _logger.WarnFormat(" quantity at index {0} is empty!", i); } else { pi.Quantity = ParseInt(cells[i], "Quantity"); } } else if (IsPriceField(i)) { pi.Price = ParsePrice(cells[i], "Price"); //pi.Price = ParseDecimal(cells[i], "Price"); } else if (IsPriceOfReleaseField(i)) { if (string.IsNullOrWhiteSpace(cells[i])) { _logger.WarnFormat(" price of release at index {0} is empty!", i); } else { pi.PriceOfRelease = ParsePrice(cells[i].Trim(), "Price of release"); //pi.PriceOfRelease = ParseDecimal(cells[i].Trim(), "Price of release"); } } else { sizeName = cells[i].Trim(); if (string.IsNullOrEmpty(sizeName) == false) { Console.WriteLine("Index: {0} = {1}", i, cells[i]); pi.AddSize(sizeName); } } } return(pi); } catch (Exception ex) { throw; } }
public ParsedItem ParseLine(string[] cells) { try { ParsedItem pi = new ParsedItem(); string sizeName; _logger.Debug("Parsing:"); for (int i = 0; i < cells.Length; i++) { _logger.DebugFormat(" cells[{0}]: {1}", i, cells[i]); if (IsCodeAndProductNameField(i)) { if (string.IsNullOrEmpty(cells[i])) { throw new ArgumentNullException("Product code/name field is empty"); //// Let's try to extract name from next cell (code) //if ((i + 1 < cells.Length) && String.IsNullOrWhiteSpace(cells[i + 1])) //{ // throw new ArgumentNullException("Product code/name field is empty"); //} } pi.ProductName = cells[i].Trim(); } else if (IsCodeField(i)) { // If code cell is empty - extract from product name "super skate G 05415" if (string.IsNullOrEmpty(cells[i])) { pi = ExtractInternalCodeFromName(pi); }else { pi.InternalCode = cells[i].Trim(); } } else if (IsQuantityField(i)) { if (String.IsNullOrEmpty(cells[i].Trim())) { _logger.WarnFormat(" quantity at index {0} is empty!", i); } else { pi.Quantity = ParseInt(cells[i], "Quantity"); } } else if (IsPriceField(i)) { pi.Price = ParsePrice(cells[i], "Price"); //pi.Price = ParseDecimal(cells[i], "Price"); } else if (IsPriceOfReleaseField(i)) { if (string.IsNullOrWhiteSpace(cells[i])) { _logger.WarnFormat(" price of release at index {0} is empty!", i); } else { pi.PriceOfRelease = ParsePrice(cells[i].Trim(), "Price of release"); //pi.PriceOfRelease = ParseDecimal(cells[i].Trim(), "Price of release"); } } else { sizeName = cells[i].Trim(); if (string.IsNullOrEmpty(sizeName) == false) { Console.WriteLine("Index: {0} = {1}", i, cells[i]); pi.AddSize(sizeName); } } } return pi; } catch (Exception ex) { throw; } }
protected virtual ParsedItem ExtractInternalCodeFromName(ParsedItem pi) { if (pi.ProductName == null) { throw new ArgumentNullException("ProductName", "Could not extract Code from ProductName, ProductName is null"); } // super skate G 05415 // cc a.t. Q 23572 Match m = _rxNameAndCode.Match(pi.ProductName); if (m.Success) { pi.InternalCode = string.Concat(m.Groups[2].Value.ToUpper(), " ", m.Groups[4].Value.Trim()); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return pi; } // NK 429716-104 m = _rxNameCodeDashed.Match(pi.ProductName); if (m.Success) { pi.InternalCode = string.Concat(m.Groups[2].Value.Trim(), "-", m.Groups[4].Value.Trim()); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return pi; } // terex 043980 m = _rxNameCodeDigits.Match(pi.ProductName); if (m.Success) { pi.InternalCode = m.Groups[2].Value.Trim(); pi.ProductName = pi.ProductName.Substring(0, m.Index).Trim(); return pi; } // Just code instead of name m = _rxCodeWithDash.Match(pi.ProductName); if (m.Success) { pi.InternalCode = pi.ProductName; pi.ProductName = ""; return pi; } return pi; }
public void Open(ParsedItem item) { GetCurrentProvider().Open(item); }
public async Task <FetchResult <string> > Search(ParsedItem item, SearchFilters filters = null, List <StatFilter> stats = null) { try { logger.Information("Querying Trade API."); if (filters == null) { filters = new SearchFilters(); } var request = new QueryRequest(); request.Query.Filters = filters; // Auto Search 5+ Links var highestCount = item.Sockets .GroupBy(x => x.Group) .Select(x => x.Count()) .OrderByDescending(x => x) .FirstOrDefault(); if (highestCount >= 5) { request.Query.Filters.SocketFilters.Filters.Links = new SocketFilterOption() { Min = highestCount, }; } if (item.Rarity == Rarity.Unique) { request.Query.Name = item.Name; request.Query.Filters.TypeFilters.Filters.Rarity = new SearchFilterOption() { Option = "Unique", }; } else if (item.Rarity == Rarity.Prophecy) { request.Query.Name = item.Name; } else { request.Query.Type = item.TypeLine; request.Query.Filters.TypeFilters.Filters.Rarity = new SearchFilterOption() { Option = "nonunique", }; } if (item.MapTier > 0) { request.Query.Filters.MapFilters.Filters.MapTier = new SearchFilterValue() { Min = item.MapTier, Max = item.MapTier, }; } if (stats != null && stats.Count > 0) { request.Query.Stats = new List <StatFilterGroup>() { new StatFilterGroup() { Type = StatType.And, Filters = stats } }; } var uri = $"{languageProvider.Language.PoeTradeApiBaseUrl}search/{configuration.LeagueId}"; var json = JsonSerializer.Serialize(request, poeTradeClient.Options); var body = new StringContent(json, Encoding.UTF8, "application/json"); var response = await httpClientProvider.HttpClient.PostAsync(uri, body); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync <FetchResult <string> >(content, poeTradeClient.Options); result.Uri = new Uri($"{languageProvider.Language.PoeTradeSearchBaseUrl}{configuration.LeagueId}/{result.Id}"); return(result); } else { var responseMessage = await response?.Content?.ReadAsStringAsync(); logger.Error("Querying failed: {responseCode} {responseMessage}", response.StatusCode, responseMessage); } } catch (Exception ex) { logger.Error(ex, "Exception thrown while querying trade api."); } return(null); }