// DisplayHeadline // The raw message from the platform is interrogated to pull out the headline. The 'pubStatus' indicator determines // if the headline is 'usable'. A non-usable headline (canceled or withdrawn) will not carry any headline title to display. private static void DisplayHeadline(IQueueResponse response) { try { if (response.IsMessageAvailable) { var msg = response.Data.Raw; // Determine if the headline is usable, i.e. if we want to display it var pubStatus = msg["payload"]?["newsItem"]?["itemMeta"]?["pubStatus"]?["_qcode"]?.ToString(); if (pubStatus is string && pubStatus.Contains("usable")) { DateTime local = DateTime.Parse(msg["distributionTimestamp"].ToString()).ToLocalTime(); // Determine if this is an actual headline JArray headline = msg["payload"]?["newsItem"]?["contentMeta"]?["headline"] as JArray; if (headline?.Count > 0 && headline[0]["$"] is JToken) { Console.WriteLine($"{local}: {headline[0]["$"]}".Indent(110)); } } } } catch (Exception e) { Console.WriteLine("*************************************************"); Console.WriteLine(e); Console.WriteLine(response.Data.Raw); Console.WriteLine("*************************************************"); } }
// Display Story // The news msg is a very rich, complex data structure containing news metadata and other elements related to // a news story. This routine simply pulls out content that can be easily displayed on the console. private static void DisplayStory(IQueueResponse response) { try { if (response.IsSuccess) { var msg = response.Data.Raw; // Determine if the headline is usable, i.e. if we want to display it var pubStatus = msg["payload"]?["newsItem"]?["itemMeta"]?["pubStatus"]?["_qcode"]?.ToString(); if (pubStatus is string && pubStatus.Contains("usable")) { DateTime local = DateTime.Parse(msg["distributionTimestamp"].ToString()).ToLocalTime(); // Pull out the headline var headline = msg["payload"]?["newsItem"]?["contentMeta"]?["headline"] as JArray; if (headline?.Count > 0 && headline[0]["$"] is JToken) { Console.WriteLine($"Headline: {local} => {headline[0]["$"]}"); } // Pull out the story var story = msg["payload"]?["newsItem"]?["contentSet"]?["inlineData"] as JArray; if (story?.Count > 0 && story[0]["$"] is JToken) { var type = story[0]["_contenttype"]; if (type != null && type.ToString().Equals("text/plain")) { JToken lang = story[0]["_xml:lang"]; var text = story[0]["$"].ToString(); var max = text.Length >= 40 ? 40 : text.Length; Console.WriteLine($"\tContent Type: [{type}]\tLang: [{lang ?? "No language"}]. Story: {text.Substring(0, max)}..."); } } } } else { Console.WriteLine($"Response failed: {response.Error}"); } } catch (Exception e) { Console.WriteLine("*************************************************"); Console.WriteLine(e); Console.WriteLine($"Response: [{response}]"); Console.WriteLine(response.Data?.Raw); Console.WriteLine("*************************************************"); Environment.FailFast("Exiting with exception"); } }
private static void DisplayResearch(IQueueResponse response) { try { if (response.IsMessageAvailable) { var msg = response.Data.Raw; DateTime distributed = DateTime.Parse(msg["distributionTimestamp"].ToString()).ToLocalTime(); Console.WriteLine($"\nDocument distributed: {distributed}"); // Headline var headline = msg["payload"]?["Headline"]?["DocumentHeadlineValue"]?.ToString(); if (headline != null) { Console.WriteLine($"\tHeadline:\t{headline}"); } // Synopsis var synopsis = msg["payload"]?["Synopsis"]?["DocumentSynopsisValue"]?.ToString(); if (synopsis != null) { Console.WriteLine($"\tSynopsis:\t{synopsis}"); } // Document name var document = msg["payload"]?["DocumentFileName"]?.ToString(); if (document != null) { Console.WriteLine($"\tDocument:\t{document} ({msg["payload"]?["DocumentFileType"]})"); } } } catch (Exception e) { Console.WriteLine("*************************************************"); Console.WriteLine(e); Console.WriteLine(response.Data.Raw); Console.WriteLine("*************************************************"); } }
private async Task <IQueueResponse> ProcessQueueItem(IQueueRequest queueItem) { using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled)) { var stopwatch = GetStopwatch(); try { IQueueResponse queueResponse = null; using (var connection = new SqlConnection(ConnectionString.DefaultConnection)) { switch (queueItem) { case SubmitPixelRequest request: queueResponse = await ProcessSubmitPixelRequest(connection, request); break; case SubmitClickRequest request: queueResponse = await ProcessSubmitClickRequest(connection, request); break; } transactionScope.Complete(); } return(queueResponse); } catch (QueueException tex) { Log.Message(LogLevel.Error, $"[QueueException] - Exception: {tex.Message}"); return(new QueueErrorResponse(tex.Message)); } catch (Exception ex) { Log.Exception($"[ProcessServiceRequest] - An unknown exception occurred during processing", ex); return(new QueueErrorResponse("Unknown Error")); } } }
static void Main(string[] _) { const string newsHeadlinesEndpoint = "https://api.refinitiv.com/message-services/v1/news-headlines/subscriptions"; try { // Create the platform session. using (ISession session = Configuration.Sessions.GetSession()) { // Open the session session.Open(); // Create a QueueManager to actively manage our queues IQueueManager manager = DeliveryFactory.CreateQueueManager(new QueueManager.Params().Session(session) .Endpoint(newsHeadlinesEndpoint) .OnError((qm, err) => Console.WriteLine(err))); // First, check to see if we have any news headline queues active in the cloud... List <IQueue> queues = manager.GetAllQueues(); // Check the error property to determine the result of the last request if (manager.Error == null) { // Determine if we retrieved an active headline queue...create one if not. IQueue queue; if (queues.Count > 0) { queue = queues[0]; } else { queue = CreateQueue(manager, "AA"); // Create a Queue with the new query expression ("AA" - alerts only) } // Ensure our queue is created if (queue != null) { Console.WriteLine($"{Environment.NewLine}{(queues.Count > 0 ? "Using existing" : "Created a new")} queue. Waiting for headlines..."); // Subscribe to the queue. // Note: The subscriber interface has 2 mechanisms to retrieve data from the queue. The first mechanism is to selectively // poll the queue for new messages. The second mechanism is to define a callback/lambda expression and notify the // the subscriber to poll for messages as they come in - this mechansim provides a near realtime result. // // The following example demonstrates the first mechanism. IQueueSubscriber subscriber = DeliveryFactory.CreateQueueSubscriber(new AWSQueueSubscriber.Params().Queue(queue)); // Poll the queue until we hit any key on the keyboard. // Each poll will timeout after 5 seconds. while (!Console.KeyAvailable) { IQueueResponse result = subscriber.GetNextMessage(5); if (result.IsSuccess) { DisplayHeadline(result); } else { Console.WriteLine(result.Status); } } Console.ReadKey(); // Prompt the user to delete the queue Console.Write("\nDelete the queue (Y/N) [N]: "); var delete = Console.ReadLine(); if (delete?.ToUpper() == "Y") { if (manager.DeleteQueue(queue)) { Console.WriteLine("Successfully deleted queue."); } else { Console.WriteLine($"Issues deleting queue {manager.Error}"); } } } } } } catch (Exception e) { Console.WriteLine($"\n**************\nFailed to execute: {e.Message}\n{e.InnerException}\n***************"); } }
static void Main(string[] _) { const string researchEndpoint = "https://api.refinitiv.com/message-services/v1/research/subscriptions"; try { using (ISession session = Configuration.Sessions.GetSession()) { if (session.Open() == Session.State.Opened) { // Create a QueueManager to actively manage our queues IQueueManager manager = DeliveryFactory.CreateQueueManager(new QueueManager.Params().Session(session) .Endpoint(researchEndpoint) .OnError((qm, err) => Console.WriteLine(err))); // First, check to see if we have any news headline queues active in the cloud... List <IQueue> queues = manager.GetAllQueues(); // Check the error property to determine the result of the last request if (manager.Error == null) { // Prepare Research criteria if we plan to create a new AWS queue - we must supply a research ID. JObject criteria = new JObject() { ["transport"] = new JObject() { ["transportType"] = "AWS-SQS" }, ["payloadVersion"] = "2.0", ["userID"] = Configuration.Credentials.ResearchID }; // If no existing queue exists, create one. IQueue queue = (queues.Count > 0 ? queues[0] : manager.CreateQueue(criteria)); if (queue != null) { Console.WriteLine($"{Environment.NewLine}{(queues.Count > 0 ? "Using existing" : "Created a new")} queue..."); // Subscribe to the queue. // Note: The subscriber interface has 2 mechanisms to retrieve data from the queue. The first mechanism is to selectively // poll the queue for new messages. The second mechanism is to define a callback/lambda expression and notify the // the subscriber to poll for messages as they come in - this mechansim provides a near realtime result. // // The following example demonstrates the first mechanism. IQueueSubscriber subscriber = DeliveryFactory.CreateQueueSubscriber(new AWSQueueSubscriber.Params().Queue(queue)); Console.WriteLine("Attempt to retrieve research messages. Hit any key to interrupt fetching..."); // Instead of defining a lambda callback, we manually poll the queue until we hit any key on the keyboard. // Each poll will timeout after 5 seconds. bool noMsgAvailable = false; while (!Console.KeyAvailable) { IQueueResponse result = subscriber.GetNextMessage(5); if (result.IsSuccess) { if (result.IsMessageAvailable) { DisplayResearch(result); } else { Console.Write(noMsgAvailable ? "." : "No Message available from GetNextMessage"); } noMsgAvailable = !result.IsMessageAvailable; } else { Console.WriteLine(result.Status); } } Console.ReadKey(); // Prompt the user to delete the queue Console.Write("\nDelete the queue (Y/N) [N]: "); var delete = Console.ReadLine(); if (delete?.ToUpper() == "Y") { if (manager.DeleteQueue(queue)) { Console.WriteLine("Successfully deleted queue."); } else { Console.WriteLine($"Issues deleting queue {manager.Error}"); } } } } } } } catch (Exception e) { Console.WriteLine($"\n**************\nFailed to execute: {e.Message}\n{e.InnerException}\n***************"); } }