IEnumerator FakeGetInfo(string sku) { yield return(StartCoroutine(Latency())); var r = new InfoResponse(); r.ok = Random.value > 0.1; if (r.ok) { r.productTitle = "Title"; r.productPrice = ""; r.productDescription = "Desc"; r.productSku = sku; } else { if (debug) { Debug.Log("FakeStore.GetInfo simulating fail"); } r.code = CODE_FAILED; } if (debug) { Debug.Log("FakeStore.GetInfo"); } listener.OnInfo(r); }
private bool HandleObjectMessage(string msg) { var response = BitmexJsonSerializer.Deserialize <JObject>(msg); // ******************** // ADD OBJECT HANDLERS BELOW // ******************** return (TradeResponse.TryHandle(response, Streams.TradesSubject) || TradeBinResponse.TryHandle(response, Streams.TradeBinSubject) || BookResponse.TryHandle(response, Streams.BookSubject) || QuoteResponse.TryHandle(response, Streams.QuoteSubject) || LiquidationResponse.TryHandle(response, Streams.LiquidationSubject) || PositionResponse.TryHandle(response, Streams.PositionSubject) || OrderResponse.TryHandle(response, Streams.OrderSubject) || WalletResponse.TryHandle(response, Streams.WalletSubject) || ErrorResponse.TryHandle(response, Streams.ErrorSubject) || SubscribeResponse.TryHandle(response, Streams.SubscribeSubject) || InfoResponse.TryHandle(response, Streams.InfoSubject) || AuthenticationResponse.TryHandle(response, Streams.AuthenticationSubject)); }
/// <summary> /// Example code to call Rosette API to get information such as version and build. /// Requires Nuget Package: /// rosette_api /// </summary> static void Main(string[] args) { //To use the C# API, you must provide an API key string apikey = "Your API key"; string alturl = string.Empty; //You may set the API key via command line argument: //info yourapikeyhere if (args.Length != 0) { apikey = args[0]; alturl = args.Length > 1 ? args[1] : string.Empty; } try { CAPI InfoCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl); //The results of the API call will come back in the form of a Dictionary InfoResponse response = InfoCAPI.Info(); foreach (KeyValuePair <string, string> h in response.Headers) { Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value)); } Console.WriteLine(response.ToString()); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } }
/// <summary> /// Handles object messages sent by bitmex. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="streams">The streams.</param> /// <returns></returns> public static bool HandleObjectMessage(string msg, BitmexClientStreams streams) { var response = BitmexJsonSerializer.Deserialize <JObject>(msg); // ******************** // ADD OBJECT HANDLERS BELOW // ******************** return (TradeResponse.TryHandle(response, streams.TradesSubject) || TradeBinResponse.TryHandle(response, streams.TradeBinSubject) || BookResponse.TryHandle(response, streams.BookSubject) || QuoteResponse.TryHandle(response, streams.QuoteSubject) || LiquidationResponse.TryHandle(response, streams.LiquidationSubject) || PositionResponse.TryHandle(response, streams.PositionSubject) || MarginResponse.TryHandle(response, streams.MarginSubject) || OrderResponse.TryHandle(response, streams.OrderSubject) || WalletResponse.TryHandle(response, streams.WalletSubject) || InstrumentResponse.TryHandle(response, streams.InstrumentSubject) || ExecutionResponse.TryHandle(response, streams.ExecutionSubject) || FundingResponse.TryHandle(response, streams.FundingsSubject) || ErrorResponse.TryHandle(response, streams.ErrorSubject) || SubscribeResponse.TryHandle(response, streams.SubscribeSubject) || InfoResponse.TryHandle(response, streams.InfoSubject) || AuthenticationResponse.TryHandle(response, streams.AuthenticationSubject)); }
private bool HandleObjectMessage(string msg) { // ******************** // ADD OBJECT HANDLERS BELOW // ******************** return (ErrorResponse.TryHandle(msg, Streams.ErrorSubject) || SubscribeResponse.TryHandle(msg, Streams.SubscribeSubject) || BookResponse.TryHandle(msg, Streams.BookSubject) || TradeResponse.TryHandle(msg, Streams.TradesSubject) || QuoteResponse.TryHandle(msg, Streams.QuoteSubject) || LiquidationResponse.TryHandle(msg, Streams.LiquidationSubject) || PositionResponse.TryHandle(msg, Streams.PositionSubject) || MarginResponse.TryHandle(msg, Streams.MarginSubject) || OrderResponse.TryHandle(msg, Streams.OrderSubject) || WalletResponse.TryHandle(msg, Streams.WalletSubject) || ExecutionResponse.TryHandle(msg, Streams.ExecutionSubject) || FundingResponse.TryHandle(msg, Streams.FundingsSubject) || InstrumentResponse.TryHandle(msg, Streams.InstrumentSubject) || TradeBinResponse.TryHandle(msg, Streams.TradeBinSubject) || InfoResponse.TryHandle(msg, Streams.InfoSubject) || AuthenticationResponse.TryHandle(msg, Streams.AuthenticationSubject)); }
public async Task <InfoResponse> GetVideoAsync(string id) { var response = new InfoResponse(); try { if (string.IsNullOrEmpty(id)) { response.Error = "Required parameter 'id' missing"; } if (string.IsNullOrEmpty(response.Error)) { var request = _youtubeService.Videos.List(new List <string> { "snippet", "statistics", "contentDetails" }); request.Id = id; var results = await request.ExecuteAsync(HttpContext.RequestAborted); var video = results.Items.FirstOrDefault(x => x.Id == id); if (video == null) { response.Error = $"Could not find id {id}, does it exist?"; } else { _logger.LogInformation($"Got video for id {id}: {video.Snippet.Title}"); response.Title = video.Snippet.Title; response.Id = video.Id; response.Duration = Convert.ToInt32(XmlConvert.ToTimeSpan(video.ContentDetails.Duration).TotalSeconds); response.LikeCount = video.Statistics.LikeCount; response.DislikeCount = video.Statistics.DislikeCount; response.Description = video.Snippet.Description; response.Uploader = video.Snippet.ChannelTitle; } } if (string.IsNullOrEmpty(response.Error)) { var streamInfo = await GetStreamInfo(id); if (streamInfo == null) { response.Error = $"Could not find suitable audio stream for id {id}"; } } if (string.IsNullOrEmpty(response.Error)) { response.Success = true; } } catch (Exception e) { _logger.LogError(e, $"Failed to get video for id '{id}'"); response.Error = e.Message; } return(response); }
protected virtual void OnNewInfoMessage(InfoResponse e) { var handler = NewInfoMessage; if (handler != null) { handler(this, e); } }
private void MessageReceived(object sender, MessageEventArgs e) { dynamic jsonData = JsonConvert.DeserializeObject(e.Data); if (jsonData.action != null && jsonData.action == "partial") { return; } ResponseBase response; if (jsonData.info != null) { response = new InfoResponse { Info = jsonData.info, Version = jsonData.version, Timestamp = jsonData.time }; OnNewInfoMessage((InfoResponse)response); } else if (jsonData.table == "trade") { response = JsonConvert.DeserializeObject <TradeResponse>(jsonData.ToString()); OnNewTradeMessage((TradeResponse)response); } else if (jsonData.table == "order") { var orderResponse = JsonConvert.DeserializeObject <OrderResponse>(jsonData.ToString()); foreach (Order order in orderResponse.Data) { if (order.OrdStatus == "New") { if (!_orders.ContainsKey(order.OrderId)) { _orders.Add(order.OrderId, order); } } else { var oldOrder = _orders[order.OrderId]; UpdateObject(oldOrder, order); } if (order.OrdStatus == "Filled") { if (_orders.ContainsKey(order.OrderId)) { _orders.Remove(order.OrderId); } } OnNewOrderMessage(order); } } }
public string GetInfo(string text) { if (Json.TryDeserialize(text, out InfoRequest request) && request.IsValid() && IsValidIdAndHash(request.GetId(), request.Hash)) { var result = new InfoResponse(); if (Database.TryGetBalance(request.GetId(), out ulong balance) && Database.TryGetName(request.GetId(), out string name) && Database.TryGetEmail(request.GetId(), out string email) && Database.TryGetPhone(request.GetId(), out string phone) && Database.TryGetAddress(request.GetId(), out string address) && Database.TryGetEnterprise(request.GetId(), out bool enterprise) && Database.TryGetTransactions(request.GetId(), out Transaction[] transactions))
public IActionResult Post(IFormFile file) { if (file == null && HttpContext.Request.Form.Files.Count > 0) { file = HttpContext.Request.Form.Files[0]; } if (file == null) { Log.Error("File is missing"); return(StatusCode(StatusCodes.Status400BadRequest, "Load file, please...")); } InfoResponse response = new InfoResponse(); MusicResponse music = new MusicResponse(); if (!file.FileName.EndsWith(".mp3")) { Log.Error("Failed format file, file not mp3"); return(StatusCode(StatusCodes.Status400BadRequest, music)); } using (Stream stream = file.OpenReadStream()) { Log.Information($"Get info on file"); response = _cloud.GetInfo(stream); Log.Information($"Return info on file"); music.Title = response.Title; music.Artist = response.Artist; Log.Information("Write info on music"); } switch (response.Status) { case ResponseStatus.OK: return(StatusCode(StatusCodes.Status200OK, music)); case ResponseStatus.NotFound: return(StatusCode(StatusCodes.Status404NotFound, music)); case ResponseStatus.FileLarge: return(StatusCode(StatusCodes.Status413RequestEntityTooLarge, music)); case ResponseStatus.FileSmall: return(StatusCode(StatusCodes.Status411LengthRequired, music)); } return(StatusCode(StatusCodes.Status200OK, music)); }
private InfoResponse ParseInfo(string json) { Hashtable map = (Hashtable)JSON.JsonDecode(json); InfoResponse r = new InfoResponse(); Parse(r, map); if (r.data != null) { r.productSku = (string)r.data["productId"]; r.productPrice = (string)r.data["price"]; r.productTitle = (string)r.data["title"]; r.productDescription = (string)r.data["description"]; } return(r); }
private void ChessEngineController_DataReceived(object sender, ChessCommandReceivedEventArgs e) { var data = e.Data; if (ResponseIsNotNullOrEmpty(data)) { if (data.StartsWith("bestmove")) { BestMove = data; CommandResponseReceived = true; return; } InfoResponse.AppendLine(data); } }
protected InfoResponse BuildInfoResponse() { // TODO complete info InfoResponse infoResponse = null; Container container = GetContainer(); if (container == null) { infoResponse = new InfoResponse(); } else { var infoBuilder = new InfoBuilder(container); infoResponse = infoBuilder.GetInfoResponse(); } return infoResponse; }
public ApiResult <InfoResponse> Info(string imUserId) { var response = new InfoResponse(); var entity = _imUserInfoService.Find(imUserId.ToGuid()); if (entity == null) { return(Error <InfoResponse>("1", "用户不存在")); } response.ImUserId = entity.ImUserId; response.ImUserName = entity.ImUserName; response.UserHeadimg = entity.UserHeadimg; response.Gender = entity.Gender; response.UserId = entity.UserId; response.UserType = entity.UserType; response.Remark = entity.Remark; return(Success(response)); }
protected InfoResponse BuildInfoResponse() { // TODO complete info InfoResponse infoResponse = null; Container container = GetContainer(); if (container == null) { infoResponse = new InfoResponse(); } else { var infoBuilder = new InfoBuilder(container); infoResponse = infoBuilder.GetInfoResponse(); } return(infoResponse); }
public static byte[] FormPacket(Header header, InfoResponse infoResponse, DataResponse dataResponse) { byte[] packet = new byte[HeaderLength + InfoResponseLength + DataResponseLength]; header.crc32 = 0; byte[] headerBytes = StructToByteArray(header); byte[] infoResponseBytes = StructToByteArray(infoResponse); byte[] dataResponseBytes = StructToByteArray(dataResponse); Buffer.BlockCopy(headerBytes, 0, packet, 0, headerBytes.Length); Buffer.BlockCopy(infoResponseBytes, 0, packet, headerBytes.Length, infoResponseBytes.Length); Buffer.BlockCopy(dataResponseBytes, 0, packet, headerBytes.Length + infoResponseBytes.Length, dataResponseBytes.Length); header.crc32 = Crc32.Compute(packet); headerBytes = StructToByteArray(header); Buffer.BlockCopy(headerBytes, 0, packet, 0, headerBytes.Length); return(packet); }
public void OnObjectMessage(string msg) { var parsed = BitfinexSerialization.Deserialize <MessageBase>(msg); switch (parsed.Event) { case MessageType.Pong: PongResponse.Handle(msg, _streams.PongSubject); break; case MessageType.Error: ErrorResponse.Handle(msg, _streams.ErrorSubject); break; case MessageType.Info: InfoResponse.Handle(msg, _streams.InfoSubject); break; case MessageType.Auth: AuthenticationResponse.Handle(msg, _streams.AuthenticationSubject); break; case MessageType.Conf: ConfigurationResponse.Handle(msg, _streams.ConfigurationSubject); break; case MessageType.Subscribed: OnSubscription(BitfinexSerialization.Deserialize <SubscribedResponse>(msg)); break; case MessageType.Unsubscribed: UnsubscribedResponse.Handle(msg, _streams.UnsubscriptionSubject); break; //default: // Log.Warning($"Missing handler for public stream, data: '{msg}'"); // break; } }
protected async Task <InfoResponse> BuildInfoResponseAsync() { var container = GetContainer(); if (container == null) { return(new InfoResponse()); } var info = await container.GetInfoAsync(); var response = new InfoResponse { HostIp = info.HostIPAddress, ContainerIp = info.ContainerIPAddress, ContainerPath = info.ContainerPath, State = info.State.ToString(), MemoryStatInfo = new InfoResponse.MemoryStat { // RSS is defined as memory + swap. This is the equivalent of "private memory" on Windows. TotalRss = (ulong)info.MemoryStat.PrivateBytes, // DEA uses the following fields when calculating memory usage. // Make sure they at least have a default value. TotalCache = 0, TotalInactiveFile = 0, }, CpuStatInfo = new InfoResponse.CpuStat { // Convert TimeSpan to nanoseconds Usage = (ulong)info.CpuStat.TotalProcessorTime.Ticks * 100, }, }; response.Events.AddRange(info.Events); return(response); }
static void WebSocketInfoMessage(object sender, InfoResponse e) { System.Console.WriteLine("[Web socket Info] {0}", e.Info); }
/// <summary> /// Gets the servers general informations /// </summary> /// <returns>InfoResponse containing all Infos</returns> /// <exception cref="SourceQueryException"></exception> public InfoResponse GetInfo(int maxRetries = 10) { try { var byteReader = RequestDataFromServer(Constants.A2S_INFO_REQUEST, out byte header, maxRetries); if (header != Constants.A2S_INFO_RESPONSE) { throw new ArgumentException("The fetched Response is no A2S_INFO Response."); } InfoResponse res = new InfoResponse(); res.Header = header; res.Protocol = byteReader.GetByte(); res.Name = byteReader.GetString(); res.Map = byteReader.GetString(); res.Folder = byteReader.GetString(); res.Game = byteReader.GetString(); res.ID = byteReader.GetShort(); res.Players = byteReader.GetByte(); res.MaxPlayers = byteReader.GetByte(); res.Bots = byteReader.GetByte(); res.ServerType = byteReader.GetByte().ToServerType(); res.Environment = byteReader.GetByte().ToEnvironment(); res.Visibility = byteReader.GetByte().ToVisibility(); res.VAC = byteReader.GetByte() == 0x01; //Check for TheShip if (res.ID == 2400) { res.Mode = byteReader.GetByte().ToTheShipMode(); res.Witnesses = byteReader.GetByte(); res.Duration = TimeSpan.FromSeconds(byteReader.GetByte()); } res.Version = byteReader.GetString(); //IF Has EDF Flag if (byteReader.Remaining > 0) { res.EDF = byteReader.GetByte(); if ((res.EDF & 0x80) == 1) { res.Port = byteReader.GetShort(); } if ((res.EDF & 0x10) == 1) { res.SteamID = byteReader.GetLong(); } if ((res.EDF & 0x40) == 1) { res.SourceTvPort = byteReader.GetShort(); res.SourceTvName = byteReader.GetString(); } if ((res.EDF & 0x20) == 1) { res.KeyWords = byteReader.GetString(); } if ((res.EDF & 0x01) == 1) { res.GameID = byteReader.GetLong(); } } return(res); } catch (Exception ex) { throw new SourceQueryException("Could not gather Info", ex); } }
public void RegisterDomainTest() { string domainName = string.Format("ahanarolen{0}.com", (new Random()).Next(Int32.MaxValue)); // check it is available DomainForCheck[] domains = new DomainForCheck[] { new DomainForCheck(domainName) }; CheckResponse.CheckedDomain[] result = target.CheckDomains(domains); Assert.AreEqual(1, result.Length); Assert.AreEqual(result[0].Name.ToLower(), domainName); Assert.IsTrue(result[0].Avail); // we need to create contact first for domain registration Contact contact = new Contact("Rajesh", "Rolen", "Microlen Inc", "*****@*****.**", "delhi", "delhi", "India", new Contact.PhoneType() { cc = "7", ext = "", phone = "9764584199" }); string id = target.CreateContact(contact); // register domain DomainForRegister domain = new DomainForRegister(domainName, 12, false, id, new string[] { "NS1.101DOMAIN.COM", "NS2.101DOMAIN.COM" }); domain.Contacts.Admin = new ContactId() { id = id }; domain.UserAccount = new DomainForRegister.UserAccountType() { create = false, Email = "*****@*****.**" }; domain.Fields = new DomainForRegister.Field[] { new DomainForRegister.Field("org-type", "org") }; RegisterResponse response = target.RegisterDomain(domain); // check it was registered fine Assert.AreEqual(response.Domain.ToLower(), domainName); Assert.AreEqual(response.Expiration, DateTime.MinValue); Assert.AreEqual(response.Contacts.Admin, id); Assert.AreEqual(response.Contacts.Billing, id); Assert.AreEqual(response.Contacts.Registrant, id); Assert.AreEqual(response.Contacts.Technical, id); Assert.AreEqual(response.NameServers.Length, domain.NameServers.Length); for (int i = 0; i < response.NameServers.Length; ++i) { Assert.AreEqual(response.NameServers[i], domain.NameServers[i]); } Assert.AreEqual(response.StatusFlags.Length, 1); Assert.AreEqual(response.StatusFlags[0], "pendingCreate"); DomainForCheck domainInfo = new DomainForCheck(domainName); InfoResponse infoResponse = target.InfoDomain(domainInfo); // check info is still the same Assert.AreEqual(infoResponse.Domain.ToLower(), domainName); Assert.AreEqual(infoResponse.Expiration, DateTime.MinValue); Assert.AreEqual(infoResponse.Contacts.Admin, id); Assert.AreEqual(infoResponse.Contacts.Billing, id); Assert.AreEqual(infoResponse.Contacts.Registrant, id); Assert.AreEqual(infoResponse.Contacts.Technical, id); Assert.AreEqual(response.NameServers.Length, domain.NameServers.Length); for (int i = 0; i < infoResponse.NameServers.Length; ++i) { Assert.AreEqual(infoResponse.NameServers[i], domain.NameServers[i]); } Assert.AreEqual(infoResponse.StatusFlags.Length, 1); Assert.AreEqual(infoResponse.StatusFlags[0], "pendingCreate"); // we need to create another contact for domain update Contact contact2 = new Contact("Rajesh", "Rolen", "Microlen Inc", "*****@*****.**", "delhi", "delhi", "India", new Contact.PhoneType() { cc = "7", ext = "", phone = "9764584199" }); string id2 = target.CreateContact(contact); DomainForUpdate domainUpdate = new DomainForUpdate(domainName, new string[] { "NS1.101DOMAIN.COM", "NS2.101DOMAIN.COM" }); domainUpdate.Contacts.Admin = new ContactId() { id = id2 }; domainUpdate.Contacts.Billing = new ContactId() { id = id2 }; domainUpdate.Contacts.Registrant = new ContactId() { id = id2 }; domainUpdate.Contacts.Technical = new ContactId() { id = id2 }; target.UpdateDomain(domainUpdate); //if no exception - it should be updated fine. //Delete old contact target.DeleteContact(id); domainInfo = new DomainForCheck(domainName); infoResponse = target.InfoDomain(domainInfo); // check info again Assert.AreEqual(infoResponse.Domain.ToLower(), domainName); Assert.AreEqual(infoResponse.Expiration, DateTime.MinValue); Assert.AreEqual(infoResponse.Contacts.Admin, id2); Assert.AreEqual(infoResponse.Contacts.Billing, id2); Assert.AreEqual(infoResponse.Contacts.Registrant, id2); Assert.AreEqual(infoResponse.Contacts.Technical, id2); Assert.AreEqual(response.NameServers.Length, domain.NameServers.Length); for (int i = 0; i < infoResponse.NameServers.Length; ++i) { Assert.AreEqual(infoResponse.NameServers[i], domain.NameServers[i]); } Assert.AreEqual(infoResponse.StatusFlags.Length, 1); Assert.AreEqual(infoResponse.StatusFlags[0], "pendingCreate"); try { DomainForRenew domainRenew = new DomainForRenew(domainName, 12); target.RenewDomain(domainRenew); Assert.Fail("Domain can't be renewed"); } catch (Exception ex) { //Expected exception Assert.AreEqual("Object status prohibits operation", ex.Message); } }
/// <summary> /// Clears InfoResponse before sending. /// </summary> public override async Task SendAsync() { InfoResponse.Clear(); await base.SendAsync(); }
internal void Raise(InfoResponse response) { _infoSubject.OnNext(response); }
private async Task HandleResponse(InfoResponse response) { await Log.WriteInfoAsync(nameof(HandleResponse), "Connecting to Bitfinex", $"{response.Event} Version {response.Version}"); }
void InfoResponse(InfoResponse status) { //fire the event InfoReceived?.Invoke(this, new DataEventArg <InfoResponse>(status)); }
void Info(InfoResponse i) { logger.Debug ("Got {0}", i); }
private async Task <bool> HandleResponse(InfoResponse info) { await Log.WriteInfoAsync("Connecting to Bitfinex", "Connected", $"Protocol version {info.Version}"); return(false); }
/// <summary> /// Retrieves a book's description, image URL, and rating from the Amazon document /// </summary> public InfoResponse ParseAmazonDocument(HtmlDocument bookDoc) { var response = new InfoResponse(); CheckCaptcha(bookDoc); #region Image URL var bookImageLoc = bookDoc.DocumentNode.SelectSingleNode("//*[@id='imgBlkFront']") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@id='imageBlock']") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@class='series-detail-product-image']") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@id='ebooksImgBlkFront']") //co.uk seems to use this id sometimes // for more generic matching, such as on audiobooks (which apparently have BXXXXXXXX asins also) ?? bookDoc.DocumentNode.SelectSingleNode("//*[@id='main-image']"); if (bookImageLoc == null) { _logger.Log("Error finding book image."); } else { var imageUrl = Regex.Replace(bookImageLoc.GetAttributeValue("src", ""), @"_.*?_\.", string.Empty); if (imageUrl.Contains("base64")) { imageUrl = bookImageLoc.GetAttributeValue("data-a-dynamic-image", ""); var match = Regex.Match(imageUrl, @"(https://.*?_\.(jpg|jpeg|gif|png))"); if (match.Success) { imageUrl = match.Groups[1].Value; if (!imageUrl.EndsWith(".png")) { imageUrl = Regex.Replace(imageUrl, @"_.*?_\.", string.Empty); } } } // cleanup to match retail file image links if (imageUrl.Contains(@"https://images-na.ssl-images-amazon")) { imageUrl = imageUrl.Replace(@"https://images-na.ssl-images-amazon", @"http://ecx.images-amazon"); } // Use no image URL if (string.IsNullOrEmpty(imageUrl)) { imageUrl = "http://ecx.images-amazon.com/images/G/01/x-site/icons/no-img-sm.gif"; } response.ImageUrl = imageUrl; } #endregion #region Description var descNode = bookDoc.DocumentNode.SelectSingleNode("//*[@id='bookDescription_feature_div']/noscript") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@class='a-size-medium series-detail-description-text']"); if (descNode != null && descNode.InnerText != "") { var description = descNode.InnerText.Trim(); // Following the example of Amazon, cut off desc around 1000 characters. // If conveniently trimmed at the end of the sentence, let it end with the punctuation. // If the sentence continues, cut it off and replace the space with an ellipsis if (description.Length > 1000) { description = description.Substring(0, 1000); var lastPunc = description.LastIndexOfAny(new[] { '.', '!', '?' }); var lastSpace = description.LastIndexOf(' '); if (lastPunc > lastSpace) { description = description.Substring(0, lastPunc + 1); } else { description = description.Substring(0, lastSpace) + '\u2026'; } } description = System.Net.WebUtility.HtmlDecode(description); response.Description = description.Clean(); } #endregion #region Reviews try { var ratingNode = bookDoc.DocumentNode.SelectSingleNode("//*[@id='acrPopover']") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@class='fl acrStars']/span"); if (ratingNode != null) { var aRating = ratingNode.GetAttributeValue("title", "0"); response.Rating = float.Parse(ratingNode.GetAttributeValue("title", "0").Substring(0, aRating.IndexOf(' '))); var reviewsNode = bookDoc.DocumentNode.SelectSingleNode("//*[@id='acrCustomerReviewText']") ?? bookDoc.DocumentNode.SelectSingleNode("//*[@class='a-link-normal']"); if (reviewsNode != null) { var match = Regex.Match(reviewsNode.InnerText, @"(\d+|\d{1,3}([,\.]\d{3})*)(?=\s)"); if (match.Success) { response.Reviews = int.Parse(match.Value.Replace(".", "").Replace(",", "")); } } } } catch (Exception ex) { throw new AggregateException("Error finding book ratings. If you want, you can report the book's Amazon URL to help with parsing.\r\n" + "Error: " + ex.Message + "\r\n" + ex.StackTrace, ex); } #endregion return(response); }
public static byte[] FormPacket(Header header, InfoResponse infoResponse) { return(FormPacketGeneric(header, infoResponse)); }