本文整理汇总了C#中BrokeredMessage.Complete方法的典型用法代码示例。如果您正苦于以下问题:C# BrokeredMessage.Complete方法的具体用法?C# BrokeredMessage.Complete怎么用?C# BrokeredMessage.Complete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BrokeredMessage
的用法示例。
在下文中一共展示了BrokeredMessage.Complete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnBrokerMessage
private void OnBrokerMessage(BrokeredMessage brokeredMessage)
{
try
{
//Ignore messages from self
if (brokeredMessage.Properties[SidAttributeName].ToString() == _sid)
{
brokeredMessage.Complete();
return;
}
var json = brokeredMessage.Properties[DataAttributeName].ToString();
var message = _jsonSerializer.DeserializeFromString<Message>(json);
var pipeline = Composable.GetExport<IXSocketPipeline>();
var controller = Composable.GetExports<IXSocketController>().First(p => p.Alias == message.Controller);
controller.ProtocolInstance = new XSocketInternalProtocol();
pipeline.OnIncomingMessage(controller, message);
brokeredMessage.Complete();
}
catch (Exception ex)
{
Composable.GetExport<IXLogger>().Error(ex.ToString());
// Indicates a problem
if (brokeredMessage.DeliveryCount > 3)
{
brokeredMessage.DeadLetter();
}
else
{
brokeredMessage.Abandon();
}
}
}
示例2: OnMessageReceived
private void OnMessageReceived(BrokeredMessage brokeredMsg)
{
var msg = JsonConvert.DeserializeObject<Message>(brokeredMsg.GetBody<string>());
if (_messageCallback(msg))
{
brokeredMsg.Complete();
}
}
示例3: ReceiveMessage
/// <summary>
/// Processes a message. Must perform error handling and also message completion or abandoning.
/// </summary>
/// <param name="message">The incoming Service Bus Message to process</param>
/// <param name="cancellationToken">When Set, indicates that processing should stop.</param>
public void ReceiveMessage(BrokeredMessage message, CancellationToken cancellationToken)
{
try
{
ReceiveMessageImpl(message, cancellationToken);
message.Complete();
}
catch
{
message.Abandon();
}
}
示例4: ProcessMessage
static void ProcessMessage(BrokeredMessage msg)
{
var app = new Application();
object filename = null;
WriteLine("queue received message");
var blobID = msg.GetBody<string>();
msg.Complete();
WriteLine($"getting blob {blobID}");
var latest = GetBlob(blobID);
WriteLine(latest);
WriteLine("opening word");
#if WORD
try
{
var doc = app.Documents.Open(ref docname);
WriteLine("filling in form");
var fields =
latest["fields"]
.Where(o => o.Value<string>("response") != null)
.ToDictionary(o => o.Value<string>("id"), o => o.Value<string>("response"));
FillForm(fields, doc);
/*WriteLine("exporting PDF");
var pdf = ExportPDF(doc);
WriteLine("opening PDF");
OpenPDF(pdf);*/
filename = Path.ChangeExtension(Path.GetTempFileName(), ".docx");
WriteLine($"saving to {filename}");
doc.SaveAs2(ref filename);
object saveChanges = false;
doc.Close(ref saveChanges);
}
catch (Exception e)
{
WriteLine(e.ToString());
}
finally
{
app.Quit();
}
if (filename != null)
Process.Start(new ProcessStartInfo((string)filename) { UseShellExecute = true });
#endif
}
示例5: OnMessageReceived
private void OnMessageReceived( BrokeredMessage message )
{
object payload;
using ( var stream = message.GetBody<Stream>() )
using ( var reader = new StreamReader( stream ) )
{
try
{
payload = this.serializer.Deserialize( reader );
}
catch ( SerializationException e )
{
message.DeadLetter( e.Message, e.ToString() );
return;
}
}
ProcessMessage( payload, message.MessageId, message.CorrelationId );
message.Complete();
}
示例6: OnMessage
private void OnMessage(BrokeredMessage message)
{
try
{
if (OnMessageReceived != null)
{
var headers = ResolveMessageHeaders(message);
var bodyStream = message.GetBody<Stream>();
var channelMessage = new ChannelMessage(bodyStream);
channelMessage.AddHeader(headers);
OnMessageReceived(this, new MessageReceivedEventArgs { Message = channelMessage });
}
message.Complete();
}
catch (Exception ex)
{
message.DeadLetter();
throw;
}
}
示例7: ProcessQueueMessage
//PROCESS A MESSAGE
private void ProcessQueueMessage(BrokeredMessage msg)
{
//CHECK: recognize the app id? fail- abandon this message
if (!isMessageFromWebApp(msg)) { return; }
//PROCESS: base on action value
//Delete all records in database
string act = msg.Properties["Action"].ToString();
if (act == "DeleteAll")
{
azureServiceProvider.DeleteAllBlobs();
msg.Complete();
return;
}
//Delete a record
else if (act == "Delete") {
string imageUrl = msg.Properties["ImageUrl"].ToString();
string thumbUrl = msg.Properties["ThumbURL"].ToString();
azureServiceProvider.DeleteMovieImageBlobs(imageUrl, thumbUrl);
msg.Complete();
return;
}
//GET MESSAGE CONTENT (Create)
string imdbId = msg.Properties["imdbId"].ToString();
string remoteFileUrl = msg.Properties["Poster"].ToString();
var movieId = int.Parse(msg.Properties["MovieId"].ToString());
//CHECK: no image URL?
if (remoteFileUrl == "" | remoteFileUrl == null){
msg.Complete();
return;
}
//CHECK: SQL record for the movieId exist?
if (dataProvider.Count(movieId) < 1) {
msg.Complete();
return;
}
//CHECK - if no imdbId found, , fail- delete this message
int imdbCount = dataProvider.Count(imdbId);
if (imdbCount < 1){
msg.Complete();
return;
}
//CHECK - if there is more than one imdbId found (ie duplicate movies info), delete duplicate records
else if (imdbCount > 1){
//remove duplicate item
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Duplicate movies detected");
dataProvider.RemoveDuplicate(movieId);
msg.Complete();
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Duplicate message was deleted.");
return;
} else if (imdbCount == 1) {
//DOWNLOAD IMAGE FILE
//HttpSevice provides service of download, save, convert image to stream
HttpServices httpHelper = new HttpServices();
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Downloads poster from remote web site");
var mStream = httpHelper.GetImageStream(remoteFileUrl);
//DEFINE BLOB NAME
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Creating thumbnail");
Uri blobUri = new Uri(remoteFileUrl);
string blobName = blobUri.Segments[blobUri.Segments.Length - 1];
var urls = azureServiceProvider.SaveImagesToContainer(mStream, blobName);
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Saved poster & thumbnail to Azure");
//UPDATE THE URL IN SQL DB
dataProvider.UpdateImageURL(urls, imdbId);
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Updated urls for poster & thumbnail.");
msg.Complete();
Trace.TraceInformation(TraceInfo.ShortTime + "WKR >>> Message process completed");
mStream.Dispose();
mStream = null;
}
}
示例8: ProcessUnderwritingRequest
private void ProcessUnderwritingRequest(BrokeredMessage requestMsg)
{
UnderwriteRequestDto dto = requestMsg.GetBody<UnderwriteRequestDto>(_requestSerializer);
//Trace.WriteLine("Processing Underwriting Request: " + requestMsg.SequenceNumber + " : " + dto.Name);
Trace.TraceError("Processing Underwriting Request (new): " + requestMsg.SequenceNumber + " : " + dto.Name);
var result = _underwriteRequest.ProcessMessage(dto);
/*
var response = new BrokeredMessage(result, _responseSerializer)
{
SessionId = requestMsg.ReplyToSessionId,
MessageId = requestMsg.MessageId,
ReplyToSessionId = requestMsg.SessionId
};
*/
requestMsg.Complete();
//_responseQueueUnderwrite.Send(response);
}
示例9: TestMessageHandler
static void TestMessageHandler( BrokeredMessage message )
{
Console.WriteLine( message.GetBody<string>() );
message.Complete();
}
示例10: SafeComplete
static bool SafeComplete(BrokeredMessage msg) {
try {
// Mark brokered message as complete.
msg.Complete();
// Return a result indicating that the message has been completed successfully.
return true;
}
catch (MessageLockLostException) {
// It's too late to compensate the loss of a message lock. We should just ignore it so that it does not break the receive loop.
// We should be prepared to receive the same message again.
}
catch (MessagingException) {
// There is nothing we can do as the connection may have been lost, or the underlying topic/subscription may have been removed.
// If Complete() fails with this exception, the only recourse is to prepare to receive another message (possibly the same one).
}
return false;
}
示例11: HandelingTransactions
private static void HandelingTransactions()
{
// http://geekswithblogs.net/asmith/archive/2012/04/02/149176.aspx
// Create a SB queue
QueueDescription queue = CreateQueue();
// Create a factory and client to talk to this queue
MessagingFactory factory = MessagingFactory.Create(ServiceUri, TokenProvider);
QueueClient client = factory.CreateQueueClient(queue.Path);
// Send a message to the queue
using (TransactionScope scope = new TransactionScope())
{
for (int i = 0; i < 10; i++)
{
// Send a message
BrokeredMessage msg = new BrokeredMessage("Message: " + i);
client.Send(msg);
Console.Write(".");
}
Console.WriteLine("Done!");
Console.WriteLine();
// Should we commit the transaction?
Console.WriteLine("Commit send 10 messages? (yes or no)");
string reply = Console.ReadLine();
if (reply.ToLower().Equals("yes"))
{
// Commit the transaction.
scope.Complete();
}
}
var check = true;
using (TransactionScope scope = new TransactionScope())
{
while (check)
{
var msg = client.Receive();
if (msg == null)
check = false;
Console.WriteLine("Received msg:" + msg.GetBody<string>());
msg.Complete();
}
Console.WriteLine("Commite receiving messages? (yes or no)");
string reply = Console.ReadLine();
if (reply.ToLower().Equals("yes"))
{
// Commit the transaction.
scope.Complete();
}
}
// Cleanup
client.Close();
factory.Close();
}
示例12: ExtractCommandResult
private bool ExtractCommandResult(BrokeredMessage p_receivedMessage, ref string p_commandResult, ref string p_diagnostics, ref string p_requestID)
{
try
{
p_receivedMessage.Complete(); // Remove message from queue. Only send Complete(), when we are confident that we could send at least 1 email/SMS/phonecall to the user. We have 5 minutes to do that, because BusQueue LockDuration is 5 minutes maximum. After that message goes back to the queue (or Dead?)
long highResReceivedTimeTick = System.Diagnostics.Stopwatch.GetTimestamp(); // this gives back UTC timestamp. Checked.
DateTime receivedTime = DateTime.UtcNow;
m_logger.LogDebug("BusQueue message was received."); // this logging could take 100msec, if it is blocking. However, nLog uses async
//string messageBody = receivedMessage.GetBody<string>(); we don't need to download Body, another 40msec,because Header contains the properties
//Service Bus Queue performance: from StorageQueue vs ServiceBusQueue vs. EventHub.txt
//string messageBody = receivedMessage.GetBody<string>(); we don't ask for the Body, because it is an extra round to the network
//> first message arrives after 650msec // +GetBody() takes 150msec
//> next messages arrives in 39, 45, 60 msec.Great ! because we don't poll it every 5 seconds. Great subscriber model.
DateTime sentTime = (DateTime)(p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertySendingTime]);
long highResSentTimeTick = (long)(p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertySendingTimeStopwatchTick]);
long elapsedTicks = highResReceivedTimeTick - highResSentTimeTick;
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
long totalNanoSeconds = elapsedTicks * nanosecPerTick;
long totalMiliseconds = totalNanoSeconds / 1000L / 1000L;
string command = p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertyCommand] as string;
object commandParams = p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertyCommandParams];
string commandResult = p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertyCommandResult] as string;
string requestID = p_receivedMessage.Properties[SQHealthMonitor.SharedConstants.MessagePropertyRequestID] as string;
if (!String.IsNullOrEmpty(commandResult))
{
m_logger.LogInformation("BusQueue message with commandResult '" + commandResult + "' was received in " + (receivedTime - sentTime).ToString() + " in highResTick as msec:" + totalMiliseconds);
p_requestID = requestID;
p_commandResult = commandResult;
p_diagnostics = @"ServiceBus one-way message-receiving delay: Using DateTime: " + (receivedTime - sentTime).ToString() + ". Using HighResTick: " + totalMiliseconds + "msec.";
return true;
}
else
{
m_logger.LogWarning("Warning! BusQueue message was received, but no commandResult Property was found.. ServiceBus one-way message-receiving delay: Using DateTime: " + (receivedTime - sentTime).ToString() + ". Using HighResTick: " + totalMiliseconds + "msec.");
return false;
}
}
catch (Exception ex)
{
m_logger.LogError("BusQueue message was received, but crash occured and was catched properly in CommandQueueHost loop handler. We tick message as Complete(), (not Abandon), and it will be not delivered 10x other times. It disappears now. Exception message: " + ex.Message, ex);
return false;
}
}
示例13: ProcessRecievedMessage
/// <summary>
/// Process the recieved messsage
/// </summary>
/// <param name="message">Message from the subscription</param>
protected virtual void ProcessRecievedMessage(BrokeredMessage message)
{
if (message == null)
return;
// Read the body of the message
var busItem = message.GetBody<EventBusMessage>();
HandleEventBusMessage(busItem);
message.Complete();
}
示例14: ProcessReceivedMessage
private void ProcessReceivedMessage(BrokeredMessage receivedMessage)
{
try
{
long highResReceivedTimeTick = System.Diagnostics.Stopwatch.GetTimestamp(); // this gives back UTC timestamp. Checked.
DateTime receivedTime = DateTime.UtcNow;
Utils.Logger.Debug("BusQueue message was received."); // this takes 100msec
//string messageBody = receivedMessage.GetBody<string>(); we don't need to download Body, another 40msec,because Header contains the properties
DateTime sentTime = (DateTime)(receivedMessage.Properties[SharedConstants.MessagePropertySendingTime]);
long highResSentTimeTick = (long)(receivedMessage.Properties[SharedConstants.MessagePropertySendingTimeStopwatchTick]);
long elapsedTicks = highResReceivedTimeTick - highResSentTimeTick;
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
long totalNanoSeconds = elapsedTicks * nanosecPerTick;
long totalMiliseconds = totalNanoSeconds / 1000L / 1000L;
string command = receivedMessage.Properties[SharedConstants.MessagePropertyCommand] as string;
object commandParams = receivedMessage.Properties[SharedConstants.MessagePropertyCommandParams];
string requestID = receivedMessage.Properties[SharedConstants.MessagePropertyRequestID] as string;
if (!String.IsNullOrEmpty(command))
{
Utils.Logger.Info("BusQueue message with command '" + command + "' was received in " + (receivedTime - sentTime).ToString() + " in highResTick as msec:" + totalMiliseconds);
ProcessReceivedCommand(command, commandParams, requestID);
}
else
{
Utils.Logger.Warn("Warning! BusQueue message was received, but no command Property was found. ServiceBus one-way message-receiving delay: Using DateTime: " + (receivedTime - sentTime).ToString() + ". Using HighResTick: " + totalMiliseconds + "msec.");
}
receivedMessage.Complete(); // Remove message from queue. Only send Complete(), when we are confident that we could send at least 1 email/SMS/phonecall to the user. We have 5 minutes to do that, because BusQueue LockDuration is 5 minutes maximum. After that message goes back to the queue (or Dead?)
}
catch (Exception ex)
{
receivedMessage.Complete();
Utils.Logger.Error(ex, "BusQueue message was received, but crash occured and was catched properly in CommandQueueHost loop handler. We tick message as Complete(), (not Abandon), and it will be not delivered 10x other times. It disappears now. Check the previous Info log item for the Command of the ReceivedMessage. Exception message: " + ex.Message);
//Utils.Logger.Error(ex, "BusQueue message was received, but crash occured and was catched properly in CommandQueueHost loop handler. We Abandon the message, which will be retried to deliver 10x, probably failing all 10x. Exception message: " + ex.Message);
//receivedMessage.Abandon(); // Indicates a problem, unlock message in queue. I
//CancellationTokenSrc.Cancel();
}
}
示例15: OnBrokerMessage
private void OnBrokerMessage(BrokeredMessage message)
{
try
{
Composable.GetExport<IXLogger>().Debug("Message Arrived {@m}", message);
var m = this.Serializer.DeserializeFromString<Message>(message.Properties["JSON"].ToString());
var pipe = Composable.GetExport<IXSocketPipeline>();
var ctrl = Composable.GetExports<IXSocketController>().First(p => p.Alias == m.Controller);
ctrl.ProtocolInstance = new XSocketInternalProtocol();
pipe.OnIncomingMessage(ctrl, m);
message.Complete();
}
catch (Exception)
{
// Indicates a problem, unlock message in subscription
if (message.DeliveryCount > 3)
message.DeadLetter();
else
message.Abandon();
}
}