public object Handle(IPipelineContext ctx, Object payload) { Pair<ConsumerContext, List<IConsumerMessage>> pair = (Pair<ConsumerContext, List<IConsumerMessage>>)payload; IMessageListener consumer = pair.Key.Consumer; List<IConsumerMessage> msgs = pair.Value; SetOnMessageStartTime(msgs); try { consumer.OnMessage(msgs); } catch (Exception e) { log.Error("Uncaught exception occurred while calling MessageListener's onMessage method, will nack all messages which handled by this call.", e); foreach (IConsumerMessage msg in msgs) { msg.Nack(); } } finally { foreach (IConsumerMessage msg in msgs) { // ensure every message is acked or nacked, ack it if not msg.Ack(); } } return null; }
async Task ConcreteMessage(IPipelineContext context) { #region InstancePublish MyEvent message = new MyEvent { SomeProperty = "Hello world" }; await context.Publish(message); #endregion }
public void SetUp() { graph = MockRepository.GenerateMock<IObjectGraph>(); context = MockRepository.GenerateMock<IPipelineContext>(); arguments = new Arguments(graph, context); }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } var cu = new CompressionUtil(); for (var i = 0; i < pInMsg.PartCount; i++) { string partName; var part = pInMsg.GetPartByIndex(i, out partName); var fileName = GetFileName(part); cu.AddMessage(part.GetOriginalDataStream(), fileName); } var outMsg = pContext.GetMessageFactory().CreateMessage(); outMsg.Context = pInMsg.Context; var bodyPart = pContext.GetMessageFactory().CreateMessagePart(); bodyPart.Data = cu.GetZip(); bodyPart.Charset = "utf-8"; bodyPart.ContentType = "application/zip"; outMsg.AddPart("Body",bodyPart,true); return outMsg; }
public IBaseMessage GetNext(IPipelineContext pContext) { if (_qOutMessages.Count > 0) return (IBaseMessage)_qOutMessages.Dequeue(); else return null; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { var contentReader = new ContentReader(); var data = pInMsg.BodyPart.GetOriginalDataStream(); if (!data.CanSeek || !data.CanRead) { const int bufferSize = 0x280; const int thresholdSize = 0x100000; data = new ReadOnlySeekableStream(data, new VirtualStream(bufferSize, thresholdSize), bufferSize); pContext.ResourceTracker.AddResource(data); } if (contentReader.IsXmlContent(data)) { var encoding = contentReader.Encoding(data); data = new ContentWriter().RemoveNamespace(data, encoding); pContext.ResourceTracker.AddResource(data); pInMsg.BodyPart.Data = data; } else { data.Seek(0, SeekOrigin.Begin); pInMsg.BodyPart.Data = data; } return pInMsg; }
public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg) { IBaseMessagePart bodyPart = pInMsg.BodyPart; Stream inboundStream = bodyPart.GetOriginalDataStream(); VirtualStream virtualStream = new VirtualStream(0x280, 0x100000); ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream, 0x280); string tempFile = Path.GetTempFileName(); using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Write, FileShare.Read)) { byte[] buffer = new byte[0x280]; int bytesRead = readOnlySeekableStream.Read(buffer, 0, buffer.Length); while (bytesRead != 0) { fs.Write(buffer, 0, bytesRead); fs.Flush(); bytesRead = readOnlySeekableStream.Read(buffer, 0, buffer.Length); } } VirtualStream outputStream = new VirtualStream(); using (XmlWriter xw = XmlWriter.Create(outputStream)) { const string NameSpace = "http://Codit.LFT.Schemas"; xw.WriteStartDocument(); xw.WriteStartElement("ns0", "LFT", NameSpace); xw.WriteElementString("TempFile", tempFile); xw.WriteEndDocument(); } outputStream.Position = 0; pContext.ResourceTracker.AddResource(outputStream); pInMsg.BodyPart.Data = outputStream; return pInMsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } String value = null; IBaseMessagePart bodyPart = pInMsg.BodyPart; Stream inboundStream = bodyPart.GetOriginalDataStream(); VirtualStream virtualStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk); ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream); XmlTextReader xmlTextReader = new XmlTextReader(readOnlySeekableStream); XPathCollection xPathCollection = new XPathCollection(); XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection); xPathCollection.Add(XPath); while (xPathReader.ReadUntilMatch()) { if (xPathReader.Match(0)) { if (xPathReader.NodeType == XmlNodeType.Attribute) { value = xPathReader.GetAttribute(xPathReader.Name); } else { value = xPathReader.ReadString(); } if (PromoteProperty) { pInMsg.Context.Promote(new ContextProperty(PropertyPath), value); } else { pInMsg.Context.Write(new ContextProperty(PropertyPath), value); } break; } } if (string.IsNullOrEmpty(value) && ThrowIfNoMatch) { throw new InvalidOperationException("The specified XPath did not exist or contained an empty value."); } readOnlySeekableStream.Position = 0; pContext.ResourceTracker.AddResource(readOnlySeekableStream); bodyPart.Data = readOnlySeekableStream; return pInMsg; }
async Task RequestImmediateDispatch(IPipelineContext context) { #region RequestImmediateDispatch SendOptions options = new SendOptions(); options.RequireImmediateDispatch(); await context.Send(new MyMessage(), options); #endregion }
public override IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { //write the itinerary to context, using the typed service request - //assumes the message body is not to be altered: RecordResult serviceRequest = new RecordResult(); PipelineComponentHelper.WriteItineraryToMessage(inmsg, serviceRequest); return inmsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { var ticket = new ISSOTicket(); pInMsg.Context.Write(new ContextProperty(SSOTicketProperties.SSOTicket), ticket.IssueTicket(0)); return pInMsg; }
public IBaseMessage GetNext(IPipelineContext pContext) { if (_reader == null) { return null; } if (!_reader.Read()) { _reader.Dispose(); _reader = null; return null; } StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.Append(@"<?xml version=""1.0"" ?>"); xmlBuilder.Append(@"<Messages xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/ExcelUpload.Messages"">"); xmlBuilder.Append(@"<AddProduct>"); xmlBuilder.Append(@"<BatchId></BatchId>"); xmlBuilder.Append(@"<RegistrationIndex></RegistrationIndex>"); xmlBuilder.Append(@"<RegistrationsInBatch></RegistrationsInBatch>"); xmlBuilder.Append(@"<BatchSourcePath></BatchSourcePath>"); xmlBuilder.Append(@"<OriginatorDestination></OriginatorDestination>"); xmlBuilder.AppendFormat(@"<Name>{0}</Name>", _reader.GetString(0)); xmlBuilder.AppendFormat(@"<ProductNumber>{0}</ProductNumber>", _reader.GetString(1)); xmlBuilder.AppendFormat(@"<SafetyStockLevel>{0}</SafetyStockLevel>", _reader.GetInt32(2)); xmlBuilder.AppendFormat(@"<ReorderPoint>{0}</ReorderPoint>", _reader.GetInt32(3)); xmlBuilder.AppendFormat(@"<StandardCost>{0}</StandardCost>", _reader.GetDecimal(4)); xmlBuilder.AppendFormat(@"<ListPrice>{0}</ListPrice>", _reader.GetDecimal(5)); xmlBuilder.AppendFormat(@"<DaysToManufacture>{0}</DaysToManufacture>", _reader.GetInt32(6)); //write date in XSD format: xmlBuilder.AppendFormat(@"<SellStartDate>{0}</SellStartDate>", DateTime.FromOADate(_reader.GetDouble(7)).ToString("yyyy-MM-ddTHH:mm:ss.fffffff")); xmlBuilder.Append(@"</AddProduct>"); xmlBuilder.Append(@"</Messages>"); byte[] data = Encoding.UTF8.GetBytes(xmlBuilder.ToString()); MemoryStream memStream = new MemoryStream(data); IBaseMessagePart messagePart = pContext.GetMessageFactory().CreateMessagePart(); messagePart.Data = memStream; messagePart.ContentType = "text/xml"; messagePart.Charset = "utf-8"; IBaseMessage outMsg = pContext.GetMessageFactory().CreateMessage(); outMsg.AddPart("Body", messagePart, true); foreach (ContextProperty property in _contextProperties) { if (property.IsPromoted) outMsg.Context.Promote(property.Name, property.Namespace, property.Value); else outMsg.Context.Write(property.Name, property.Namespace, property.Value); } outMsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", "http://tempuri.net/ExcelUpload.Messages#Messages"); return outMsg; }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { IBaseMessagePart bodyPart = pInMsg.BodyPart; if (bodyPart != null) { _qOutMessages = _decompressionManager.DecompressAndSpliMessage(pInMsg, pContext); } }
async Task RequestImmediateDispatchUsingScope(IPipelineContext context) { #region RequestImmediateDispatchUsingScope using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { await context.SendLocal(new MyMessage()); } #endregion }
async Task DisablePerMessage(IPipelineContext context) { #region DisableBestPracticeEnforcementPerMessage SendOptions options = new SendOptions(); options.DoNotEnforceBestPractices(); await context.Send(new MyEvent(), options); #endregion }
public IBaseMessage Assemble(IPipelineContext pContext) { var message = _inputMessage; _inputMessage = null; if ( message != null ) { _stagesSeen.Add(pContext.StageID); } return message; }
async Task Correlation(IPipelineContext context) { #region custom-correlationid SendOptions options = new SendOptions(); options.SetCorrelationId("My custom correlation id"); await context.Send(new MyRequest(),options); #endregion }
public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg) { System.Diagnostics.EventLog.WriteEntry("BizTalk pipeline", "Writing original caller to the SOAP header"); // original caller string originalCaller = "<headers>" + pInMsg.Context.Read("OriginalCaller", "http://www.riziv-inami.fgov.be/BizTalk/common").ToString() + "</headers>"; System.Diagnostics.EventLog.WriteEntry("BizTalk pipeline", originalCaller); pInMsg.Context.Write("OutboundCustomHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", originalCaller); return pInMsg; }
public async Task Start(Guid taskId, IPipelineContext context) { TaskDefinition taskDefinition; if (!scheduledTasks.TryGetValue(taskId, out taskDefinition)) { logger.InfoFormat("Could not find any scheduled task with id {0}. The DefaultScheduler does not persist tasks between restarts.", taskId); return; } await DeferTask(taskDefinition, context).ConfigureAwait(false); await ExecuteTask(taskDefinition, context).ConfigureAwait(false); }
/// <summary> /// Returns a seekable version of a message's data stream. The stream will be wrapped in a ReadOnlySeekableDataStream if needed. /// </summary> /// <param name="pipelineContext">The pipeline context of the message.</param> /// <param name="messagePart">The message part for which a seekable stream is required.</param> /// <returns>A seekable version of the message stream.</returns> public static Stream GetReadOnlySeekableDataStream(IPipelineContext pipelineContext, IBaseMessagePart messagePart) { Stream dataStream = messagePart.GetOriginalDataStream(); if (!dataStream.CanSeek) { ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(dataStream); messagePart.Data = seekableStream; pipelineContext.ResourceTracker.AddResource(seekableStream); dataStream = seekableStream; } return(dataStream); }
async Task DisablePerMessage(IPipelineContext context) { #region DisableBestPracticeEnforcementPerMessage var options = new SendOptions(); options.DoNotEnforceBestPractices(); await context.Send(new MyEvent(), options) .ConfigureAwait(false); #endregion }
/// <summary> /// Returns the <see cref="ISchemaMetadata"/> associated to the XML schema of messages of a given <see /// cref="DocumentSpec"/> type. /// </summary> /// <param name="pipelineContext"> /// The pipeline context from which the <see cref="DocumentSpec"/> can be queried. /// </param> /// <param name="docType"> /// The <see cref="DocumentSpec"/> type of the messages for which the <see cref="ISchemaMetadata"/> are to be /// returned. /// </param> /// <param name="throwOnError"> /// <c>false</c> to swallow <see cref="COMException"/> and return a <see cref="SchemaMetadata.Unknown"/> should /// the document specification not to be found; it will however be logged as a warning. <c>true</c> to let any /// exception through. /// </param> /// <returns> /// The <see cref="ISchemaMetadata"/> associated to the XML Schema. /// </returns> public static ISchemaMetadata GetSchemaMetadataByType(this IPipelineContext pipelineContext, string docType, bool throwOnError) { if (throwOnError) { return(pipelineContext.GetSchemaMetadataByType(docType)); } IDocumentSpec documentSpec; var schemaType = !docType.IsNullOrEmpty() && pipelineContext.TryGetDocumentSpecByType(docType, out documentSpec) ? Type.GetType(documentSpec.DocSpecStrongName, false) : null; return(schemaType.IsSchema() ? schemaType.GetMetadata() : SchemaMetadata.Unknown); }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } pInMsg.Context.Promote(new ContextProperty(DestinationProperty), Guid.NewGuid().ToString()); return(pInMsg); }
internal MqttTransportHandler( IPipelineContext context, IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Func <MethodRequestInternal, Task> onMethodCallback = null, Action <TwinCollection> onDesiredStatePatchReceivedCallback = null, Func <string, Message, Task> onReceiveCallback = null) : this(context, iotHubConnectionString, settings, null) { this.messageListener = onMethodCallback; this.messageReceivedListener = onReceiveCallback; this.onDesiredStatePatchListener = onDesiredStatePatchReceivedCallback; }
internal MqttTransportHandler( IPipelineContext context, IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Action <object, ConnectionEventArgs> onConnectionOpenedCallback, Func <object, ConnectionEventArgs, Task> onConnectionClosedCallback, Func <MethodRequestInternal, Task> onMethodCallback = null, Action <TwinCollection> onDesiredStatePatchReceivedCallback = null) : this(context, iotHubConnectionString, settings, null, onConnectionOpenedCallback, onConnectionClosedCallback) { this.messageListener = onMethodCallback; this.onDesiredStatePatchListener = onDesiredStatePatchReceivedCallback; }
private static void CloneParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart) { for (int i = 0; i < inmsg.PartCount; i++) { string partName = null; IBaseMessagePart currentPart = inmsg.GetPartByIndex(i, out partName); if (currentPart == null) continue; outmsg.AddPart(partName, partName == inmsg.BodyPartName ? bodyPart : currentPart, partName == inmsg.BodyPartName); } }
async Task ConcreteMessage(IPipelineContext context) { #region InstancePublish var message = new MyEvent { SomeProperty = "Hello world" }; await context.Publish(message) .ConfigureAwait(false); #endregion }
public async Task <PipelineProcessingResult> Process(IPipelineContext context) { var missingFields = new List <string>(); var baseSchemaItem = (((context.Schema as MappingSchemaItem).Mapping["websites"] as SequenceSchemaItem).Items[0] as MappingSchemaItem); foreach (var kvp in baseSchemaItem.Mapping) { switch (kvp.Value) { case KeyValueSchemaItem keyValueItem: if (!context.MerchantDetails.Values.ContainsKey(kvp.Key) || string.IsNullOrEmpty(context.MerchantDetails.Values[kvp.Key].Value)) { await TryResolveMissingKey(context.MerchantDetails, kvp.Key); } // Special exception for the img tag. The bot needs it to run the pipeline. if (keyValueItem.Required || kvp.Key == "img") { if (!context.MerchantDetails.Values.ContainsKey(kvp.Key) || string.IsNullOrEmpty(context.MerchantDetails.Values[kvp.Key].Value)) { missingFields.Add(kvp.Key); } } break; } } // Check categories if (!context.MerchantDetails.Values.ContainsKey("category") || !context.RepositoryContext.EnumerateCategories().Contains(context.MerchantDetails.Values["category"].Value, StringComparer.OrdinalIgnoreCase)) { missingFields.Add("category"); } if (missingFields.Count == 0) { return(PipelineProcessingResult.Success()); } else { var messageBuilder = new StringBuilder(); messageBuilder.AppendLine("The following fields are missing:"); foreach (var field in missingFields) { messageBuilder.Append("- "); messageBuilder.AppendLine(field); } return(PipelineProcessingResult.Failure(messageBuilder.ToString())); } }
public Task <PipelineProcessingResult> Process(IPipelineContext context) { var categoryFileName = $"{context.MerchantDetails.Values["category"].Value.ToLower()}.yml"; var categoryFilePath = Path.Combine(context.RepositoryContext.RepositoryDirectory, "_data", categoryFileName); var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); Dictionary <string, List <Dictionary <string, object> > > document; using (var fileStream = new FileStream(categoryFilePath, FileMode.Open)) { using (var streamReader = new StreamReader(fileStream)) { document = deserializer.Deserialize <Dictionary <string, List <Dictionary <string, object> > > >(streamReader); } } var websitesCollection = document["websites"]; var merchantEntry = context.MerchantDetails.Export(); var existingEntry = websitesCollection.Where(x => ((string)x["url"]).ToLower().TrimEnd('/') == context.MerchantDetails.Values["url"].Value.ToLower().TrimEnd('/')).FirstOrDefault(); if (existingEntry != null) { websitesCollection.Remove(existingEntry); // Copy fields from the original entry to the new one // Only copy fields that aren't already on the new one - new fields take priority foreach (var key in existingEntry.Keys) { if (!merchantEntry.ContainsKey(key)) { merchantEntry.Add(key, existingEntry[key]); } } } websitesCollection.Add(merchantEntry); document["websites"] = websitesCollection.OrderBy(x => (string)x["name"], StringComparer.OrdinalIgnoreCase).ToList(); var serializer = new SerializerBuilder() .Build(); var yml = serializer.Serialize(document); yml = AddSpacesBetweenListItems(yml); File.WriteAllText(categoryFilePath, yml); return(Task.FromResult(PipelineProcessingResult.Success())); }
public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { try { Stream s = ReformatEnvelope(inmsg.BodyPart.Data); s.Position = 0; inmsg.BodyPart.Data = s; return(inmsg); } catch (Exception ex) { throw new ApplicationException(string.Format("The {0} pipeline component encountered an error. ", this.GetType().ToString()), ex); } }
static Task DeferTask(TaskDefinition taskDefinition, IPipelineContext context) { var options = new SendOptions(); options.DelayDeliveryWith(taskDefinition.Every); options.RouteToThisEndpoint(); return context.Send(new ScheduledTask { TaskId = taskDefinition.Id, Name = taskDefinition.Name, Every = taskDefinition.Every }, options); }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { if (pInMsg.BodyPart != null) { Stream currentPartSource = pInMsg.BodyPart.GetOriginalDataStream(); byte[] currentPartBuffer = new byte[currentPartSource.Length]; currentPartSource.Read(currentPartBuffer, 0, currentPartBuffer.Length); byte[] decompressedPartBuffer; string filename = ""; //Unzip arquive using (var unzipArchive = new ZipArchive(currentPartSource, ZipArchiveMode.Read, true)) { //Loop arquive file for message foreach (var entryStream in unzipArchive.Entries) { IBaseMessage inboundInstanceMessage; //Here we are gets the filename (with extension) of an entery present in the arquive file filename = entryStream.FullName; using (var outStream = new MemoryStream()) { entryStream.Open().CopyTo(outStream); decompressedPartBuffer = outStream.ToArray(); } MemoryStream messageInstanceStream = new MemoryStream(decompressedPartBuffer); messageInstanceStream.Position = 0; #region Generating a new inbound message //Creating a new message from the pipeline context inboundInstanceMessage = pContext.GetMessageFactory().CreateMessage(); //Cloning the context to the new message, instead of assigning it inboundInstanceMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context); inboundInstanceMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true); inboundInstanceMessage.BodyPart.Data = messageInstanceStream; inboundInstanceMessage.BodyPart.Charset = "UTF-8"; inboundInstanceMessage.BodyPart.ContentType = "text/xml"; //we promote the filename so that we can access it in the Send Port. inboundInstanceMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", filename); #endregion inboundMsgQueue.Enqueue(inboundInstanceMessage); } } } }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { IEnumerator e = Properties.GetEnumerator(); while (e.MoveNext()) { ContextValue v = (ContextValue)e.Current; var value = Convert.ChangeType(v.Value, v.Code); pInMsg.Context.Promote(v.Key, v.Namespace, value); } return(pInMsg); }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } //component will not be executed if the property is set to true if (Disabled) { return(pInMsg); } //get the value from the provided property IBaseMessageContext context = pInMsg.Context; string key = (string)context.Read(new ContextProperty(PropertyPath)); // PropertyPath.Split('#')[1], PropertyPath.Split('#')[0]).ToString(); //query the sharepoint table var lookupService = new LookupUtilityService(new SharepointLookupRepository()); string result = ""; try { result = lookupService.GetValue(ListName, key, true); }catch (ArgumentException ex) { if (ThrowException) { throw ex; } else { System.Diagnostics.EventLog.WriteEntry(pContext.PipelineName, ex.Message, System.Diagnostics.EventLogEntryType.Warning); } } //promote the result to the provided destination property if (PromoteProperty) { pInMsg.Context.Promote(new ContextProperty(DestinationPath), result); } else { pInMsg.Context.Write(new ContextProperty(DestinationPath), result); } return(pInMsg); }
public async Task ExecuteAsync(Input input, IPipelineContext context = default) { if (context == default) { context = new PipelineContext(); } _output = await step.ExecuteAsync(input, context); if (!(context.IsBroken || _next == default)) { Task.WaitAll(_next.Select(x => x.ExecuteAsync(_output, context.Copy())).ToArray()); } }
/// <summary> /// Executes a pipeline component. /// </summary> /// <param name="pContext">Pipeline context</param> /// <param name="pInMsg">Input message</param> /// <returns>Outgoing message</returns> public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { try { return(ExecuteInternal(pContext, pInMsg)); } catch (Exception e) { // Put component name as a source information in this exception, // so the event log in message could reflect this. e.Source = Name; throw e; } }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage inMsg) { //ActivityLogger activityLogger = new ActivityLogger(this.InterfaceName, true, this.StageId); ActivityLogger1 activityLogger = new ActivityLogger1(); string ActivityId = default(string); //string eventID = activityLogger.GenerateEventID(); try { //ActivityLogger activityLogger = new ActivityLogger(this.InterfaceName,true, this.StageId); //This is when a new activity is logged. if (StartActivty == true) { ActivityId = activityLogger.StartActivity(StageId, InterfaceName, null, inMsg); //activityLogger.StartActivity(inMsg, InterfaceName, StageId, eventID); } //When archive activity is enabled. // throw new Exception("Test Pipeline Exception"); if (UpdateActivity == true) { activityLogger.UpdateStageActivity(inMsg, InterfaceName, StageId); } if (ArchiveMessage == true) { activityLogger.ArchiveMessage(inMsg, ActivityId); } string trackingId = (string)inMsg.Context.Read("StageActivityId", "https://Kovai.AtomicScope"); StringBuilder strbuilder = new StringBuilder(); Random a = new Random(); inMsg.Context.Write("HttpHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", "x-ms-client-tracking-id: " + trackingId); inMsg.Context.Write("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true); return(inMsg); } catch (Exception ex) { activityLogger.logException(ActivityId, "System Exception", "RcvPort Decode " + ex.Message); } return(inMsg); }
public RetryDelegatingHandler(IPipelineContext context, IDelegatingHandler innerHandler) : base(context, innerHandler) { IRetryPolicy defaultRetryStrategy = new ExponentialBackoff( retryCount: RetryMaxCount, minBackoff: TimeSpan.FromMilliseconds(100), maxBackoff: TimeSpan.FromSeconds(10), deltaBackoff: TimeSpan.FromMilliseconds(100)); _internalRetryPolicy = new RetryPolicy(new TransientErrorStrategy(), new RetryStrategyAdapter(defaultRetryStrategy)); _onConnectionStatusChanged = context.Get <ConnectionStatusChangesHandler>(); Logging.Associate(this, _internalRetryPolicy, nameof(SetRetryPolicy)); }
public PipelineText(PipelineFactory factory, IPipelineContext context, IEnumerable <TT> stream, TransformIndexTree indexTree, IDisposable chain) { this.Context = context; this.CurrentStream = stream; _tracker = new PipelineDisposeHelper(); _tracker.TrackInstance(chain); _indexTree = indexTree; _factory = factory; if (FORCE_INMEMORY_PROCESS) { this.CurrentStream = stream.ToArray(); } }
/// <summary> /// Public execute metod of the pipeline. /// </summary> /// <param name="pipelineContext"></param> /// <param name="message"></param> /// <returns></returns> public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { Guard.NotNull(pipelineContext, "pipelineContext"); Guard.NotNull(message, "message"); IBaseMessage returnMessage = message; if (IsEnabled) { returnMessage = ExecuteInternal(pipelineContext, message); } return(returnMessage); }
public async Task <PipelineProcessingResult> Process(IPipelineContext context) { var imageLocalPath = diskService.GetTempFilePath(); try { await networkService.DownloadFile(context.MerchantDetails.Values["img"].Value, imageLocalPath); } catch (WebException) { return(PipelineProcessingResult.Failure($"Unable to download image at `{context.MerchantDetails.Values["img"].Value}`.")); } context.Data.Add("ImageLocalPath", imageLocalPath); return(PipelineProcessingResult.Success()); }
/// <summary> /// Processes the specified context. /// </summary> /// <param name="context">The context.</param> public override void Process(IPipelineContext <InstallationConflictDetails> context) { Assert.ArgumentNotNull(context, nameof(context)); var command = context.Model.CommandsResponse.FindAllByName("SetStyle").FirstOrDefault(c => c.Id == "SuccessMessage"); if (command?.Value != string.Empty) { return; } this.Installer.Events.RaiseSuccess(); this.Installer.Events.RaiseOutputRequired("The package has been installed."); }
private static IBaseMessagePart CloneMessagePart(IPipelineContext pipelineContext, IBaseMessagePart messagePart) { IBaseMessageFactory messageFactory = pipelineContext.GetMessageFactory(); IBaseMessagePart messagePart1 = messageFactory.CreateMessagePart(); messagePart1.Charset = messagePart.Charset; messagePart1.ContentType = messagePart.ContentType; messagePart1.PartProperties = PipelineUtil.CopyPropertyBag(messagePart.PartProperties, messageFactory); VirtualStream virtualStream = new VirtualStream(); MessageHelper.CopyStream(messagePart.Data, (Stream)virtualStream); messagePart1.Data = (Stream)virtualStream; return(messagePart1); }
/// <summary> /// Execute all Instructions contained within the MetaInstruction's collection of Instructions /// </summary> public void ExecuteAllBREPipelineInstructions(ref IBaseMessage inmsg, IPipelineContext pc) { if (instructionCollection != null) { foreach (var instruction in instructionCollection) { if (instruction.Value != null) { TraceManager.PipelineComponent.TraceInfo("{0} - Executing instruction {1} which has an order of {2} in the collection.", callToken, instruction.Value.ToString(), instruction.Key.ToString()); instruction.Value.Execute(ref inmsg, pc); } } } }
static Task DeferTask(TaskDefinition taskDefinition, IPipelineContext context) { var options = new SendOptions(); options.DelayDeliveryWith(taskDefinition.Every); options.RouteToThisEndpoint(); return(context.Send(new ScheduledTask { TaskId = taskDefinition.Id, Name = taskDefinition.Name, Every = taskDefinition.Every }, options)); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { int PartCount = inmsg.PartCount; string BodyPartName = inmsg.BodyPartName; string systemPropertiesNamespace = @"http://schemas.microsoft.com/BizTalk/2003/system-properties"; try { for (int i = 0; i < inmsg.PartCount; i++) { string PartName; IBaseMessagePart CurrentPart = inmsg.GetPartByIndex(i, out PartName); if (!PartName.Equals(BodyPartName)) { Stream CurrentPartSource = CurrentPart.GetOriginalDataStream(); byte[] CurrentPartBuffer = new byte[CurrentPartSource.Length]; CurrentPartSource.Read(CurrentPartBuffer, 0, CurrentPartBuffer.Length); byte[] CompressedPartBuffer; using (MemoryStream TempStream = new MemoryStream()) { using (GZipStream CompressedStream = new GZipStream(TempStream, CompressionMode.Compress, true)) { CompressedStream.Write(CurrentPartBuffer, 0, CurrentPartBuffer.Length); CompressedStream.Close(); } CompressedPartBuffer = TempStream.ToArray(); } MemoryStream TempCompressedStream = new MemoryStream(CompressedPartBuffer); inmsg.GetPartByIndex(i, out PartName).Data = TempCompressedStream; string PropertyName = "FileName"; string PropertySchema = "http://schemas.microsoft.com/BizTalk/2003/mime-properties"; string SourcePartName = inmsg.GetPartByIndex(i, out PartName).PartProperties.Read(PropertyName, PropertySchema).ToString(); SourcePartName += this.FileExtension; inmsg.GetPartByIndex(i, out PartName).PartProperties.Write("FileName", PropertySchema, SourcePartName); } } } catch { throw; } return(inmsg); }
internal AmqpTransportHandler( IPipelineContext context, IotHubConnectionString connectionString, AmqpTransportSettings transportSettings, Func <MethodRequestInternal, Task> onMethodCallback = null, Action <TwinCollection> onDesiredStatePatchReceived = null, Func <string, Message, Task> onEventReceivedCallback = null) : base(context, transportSettings) { this.productInfo = context.Get <ProductInfo>(); TransportType transportType = transportSettings.GetTransportType(); this.deviceId = connectionString.DeviceId; this.moduleId = connectionString.ModuleId; if (!transportSettings.AmqpConnectionPoolSettings.Pooling) { this.IotHubConnection = new IotHubSingleTokenConnection(null, connectionString, transportSettings); } else { switch (transportType) { case TransportType.Amqp_Tcp_Only: this.IotHubConnection = TcpConnectionCache.GetConnection(connectionString, transportSettings); break; case TransportType.Amqp_WebSocket_Only: this.IotHubConnection = WsConnectionCache.GetConnection(connectionString, transportSettings); break; default: throw new InvalidOperationException("Invalid Transport Type {0}".FormatInvariant(transportType)); } } this.IotHubConnection.OnConnectionClose += OnAmqpConnectionClose; this.openTimeout = transportSettings.OpenTimeout; this.operationTimeout = transportSettings.OperationTimeout; this.prefetchCount = transportSettings.PrefetchCount; this.faultTolerantEventSendingLink = new Client.FaultTolerantAmqpObject <SendingAmqpLink>(this.CreateEventSendingLinkAsync, OnAmqpLinkClose); this.faultTolerantDeviceBoundReceivingLink = new Client.FaultTolerantAmqpObject <ReceivingAmqpLink>(this.CreateDeviceBoundReceivingLinkAsync, OnAmqpLinkClose); this.iotHubConnectionString = connectionString; this.methodReceivedListener = onMethodCallback; this.onDesiredStatePatchListener = onDesiredStatePatchReceived; this.eventReceivedListener = onEventReceivedCallback; }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { try { var bodyPart = inmsg.BodyPart; if (bodyPart != null) { var dataStream = bodyPart.GetOriginalDataStream(); if (!dataStream.CanWrite) { dataStream = new VirtualStream(bodyPart.GetOriginalDataStream()); } var xDoc = new XPathDocument(dataStream); var xNav = xDoc.CreateNavigator(); xNav.MoveToRoot(); var xNodeIt = xNav.Select(_xpath); while (xNodeIt.MoveNext()) { var byte64 = Encoding.ASCII.GetBytes(xNodeIt.Current.Value); var strmBase64 = new MemoryStream(byte64); var strm = new CryptoStream(strmBase64, new FromBase64Transform(), CryptoStreamMode.Read); bodyPart.Data = new FakeSeekableStream(strm); pc.ResourceTracker.AddResource(strm); pc.ResourceTracker.AddResource(strmBase64); } string messageType = RecognizeMessageType(pc, inmsg); if (!String.IsNullOrEmpty(messageType)) { inmsg.Context.Promote("MessageType" , "http://schemas.microsoft.com/BizTalk/2003/system-properties" , messageType); string schemaStrongName = GetSchemaStrongName(messageType); inmsg.Context.Promote("SchemaStrongName", "http://schemas.microsoft.com/BizTalk/2003/system-properties" , schemaStrongName); } pc.ResourceTracker.AddResource(dataStream); } } catch (Exception e) { throw new InvalidProgramException(e.Message); } return(inmsg); }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { //read the incoming JSON stream: var inStream = pInMsg.BodyPart.GetOriginalDataStream(); var json = string.Empty; using (var reader = new StreamReader(inStream)) { json = reader.ReadToEnd(); } //convert to XML: var document = JsonConvert.DeserializeXNode(json, "root"); var output = new XElement(XName.Get(RootElementName, TargetNamespace)); output.Add(document.Root.Descendants()); //fix up the namespaces: XNamespace ns = TargetNamespace; foreach (var element in output.Descendants()) { element.Name = ns.GetName(element.Name.LocalName); var attributes = element.Attributes().ToList(); element.Attributes().Remove(); foreach (XAttribute attribute in attributes) { if (!attribute.IsNamespaceDeclaration) { element.Add(new XAttribute(attribute.Name.LocalName, attribute.Value)); } } } //write to output body stream: var outStream = new MemoryStream(); var writer = new XmlTextWriter(outStream, Encoding.Default); output.WriteTo(writer); writer.Flush(); outStream.Flush(); outStream.Position = 0; pInMsg.BodyPart.Data = outStream; //promote the message type: pInMsg.Context.Promote(_MessageTypeProperty.Name.Name, _MessageTypeProperty.Name.Namespace, string.Format("{0}#{1}", TargetNamespace, RootElementName)); return(pInMsg); }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { IBaseMessagePart bodyPart = pInMsg.BodyPart; if (bodyPart != null) { Stream originalStream = bodyPart.GetOriginalDataStream(); MemoryStream memStream = new MemoryStream(); byte[] buffer = new Byte[1024]; int bytesRead = 1024; while (bytesRead != 0) { bytesRead = originalStream.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, bytesRead); } memStream.Position = 0; if (originalStream != null) { using (ZipArchive zipArchive = new ZipArchive(memStream, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry entry in zipArchive.Entries) { MemoryStream entryStream = new MemoryStream(); byte[] entrybuffer = new Byte[1024]; int entryBytesRead = 1024; Stream zipArchiveEntryStream = entry.Open(); while (entryBytesRead != 0) { entryBytesRead = zipArchiveEntryStream.Read(entrybuffer, 0, entrybuffer.Length); entryStream.Write(entrybuffer, 0, entryBytesRead); } IBaseMessage outMessage; outMessage = pContext.GetMessageFactory().CreateMessage(); outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true); entryStream.Position = 0; outMessage.BodyPart.Data = entryStream; pInMsg.Context.Promote(new ContextProperty(FileProperties.ReceivedFileName), entry.Name); outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context); _qOutMessages.Enqueue(outMessage); } } } } }
public IBaseMessage ExecuteForwardOnly(IPipelineContext pc, IBaseMessage inmsg) { TraceStream traceStream = new TraceStream(inmsg.BodyPart.GetOriginalDataStream(), true); Microsoft.BizTalk.Streaming.CForwardOnlyEventingReadStream eventStream = new Microsoft.BizTalk.Streaming.CForwardOnlyEventingReadStream(traceStream); eventStream.BeforeFirstReadEvent += new Microsoft.BizTalk.Streaming.BeforeFirstReadEventHandler(eventStream_BeforeFirstReadEvent); eventStream.ReadEvent += new Microsoft.BizTalk.Streaming.ReadEventHandler(eventStream_ReadEvent); eventStream.AfterLastReadEvent += new Microsoft.BizTalk.Streaming.AfterLastReadEventHandler(eventStream_AfterLastReadEvent); inmsg.BodyPart.Data = eventStream; return(inmsg); }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } //Get a reference to the BizTalk schema. var documentSpec = pContext.GetDocumentSpecByName(DocumentSpecName); //Get a list of properties defined in the schema. var annotations = documentSpec.GetPropertyAnnotationEnumerator(); var doc = new XmlDocument(); using (var sw = new StringWriter(new StringBuilder())) { //Create a new instance of the schema. doc.Load(((IFFDocumentSpec)documentSpec).CreateXmlInstance(sw)); } //Write all properties to the message body. while (annotations.MoveNext()) { var annotation = (IPropertyAnnotation)annotations.Current; var node = doc.SelectSingleNode(annotation.XPath); object propertyValue; if (pInMsg.Context.TryRead(new ContextProperty(annotation.Name, annotation.Namespace), out propertyValue)) { node.InnerText = propertyValue.ToString(); } } var data = new VirtualStream(); pContext.ResourceTracker.AddResource(data); doc.Save(data); data.Seek(0, SeekOrigin.Begin); var outMsg = pInMsg; outMsg.BodyPart.Data = data; //Promote message type and SchemaStrongName outMsg.Context.Promote(new ContextProperty(SystemProperties.MessageType), documentSpec.DocType); outMsg.Context.Promote(new ContextProperty(SystemProperties.SchemaStrongName), documentSpec.DocSpecStrongName); _outputQueue.Enqueue(outMsg); }
public void Handle(IPipelineContext ctx, Object payload) { var msg = (ProducerMessage)payload; var topic = msg.Topic; if (string.IsNullOrEmpty(topic)) { log.Error("Topic not set, won't send"); return; } enrichPartitionKey(msg, Local.IPV4); enrichRefKey(msg); enrichMessageProperties(msg, Local.IPV4); ctx.Next(payload); }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { //load up the Excel reader: Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream(); string fileName = (string) pInMsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties"); _reader = GetDataReader(fileName, originalStream); //store the incoming context properties to write out again: _contextProperties = new List<ContextProperty>(); for (int i = 0; i < pInMsg.Context.CountProperties; i++) { ContextProperty property = new ContextProperty(); property.Value = pInMsg.Context.ReadAt(i, out property.Name, out property.Namespace); property.IsPromoted = pInMsg.Context.IsPromoted(property.Name, property.Namespace); _contextProperties.Add(property); } }
public object Resolve(Type pluginType, IPipelineContext context, object rawValue) { // Yeah Microsoft! try { var converter = TypeDescriptor.GetConverter(pluginType); if (converter == null) return null; return converter.CanConvertFrom(rawValue.GetType()) ? converter.ConvertFrom(rawValue) : null; } catch (Exception) { return null; } }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } var contentReader = new ContentReader(); var data = pInMsg.BodyPart.GetOriginalDataStream(); if (!data.CanSeek || !data.CanRead) { const int bufferSize = 0x280; const int thresholdSize = 0x100000; data = new ReadOnlySeekableStream(data, new VirtualStream(bufferSize, thresholdSize), bufferSize); pContext.ResourceTracker.AddResource(data); } if (contentReader.IsXmlContent(data) && contentReader.NamespacExists(data, NamespaceToModify)) { var encoding = contentReader.Encoding(data); data = new ContentWriter().ModifyNamespace(data, NamespaceToModify, NewNamespace, encoding); pContext.ResourceTracker.AddResource(data); pInMsg.BodyPart.Data = data; if (ShouldUpdateMessageTypeContext) { var rootName = contentReader.GetRootNode(data); var contextReader = new ContextReader(); contextReader.UpdateMessageTypeContext(pInMsg.Context, NewNamespace, rootName); } } else { data.Seek(0, SeekOrigin.Begin); pInMsg.BodyPart.Data = data; } return pInMsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { //read the incoming JSON stream: var inStream = pInMsg.BodyPart.GetOriginalDataStream(); var json = string.Empty; using (var reader = new StreamReader(inStream)) { json = reader.ReadToEnd(); } //convert to XML: var document = JsonConvert.DeserializeXNode(json, "root"); var output = new XElement(XName.Get(RootElementName, TargetNamespace)); output.Add(document.Root.Descendants()); //fix up the namespaces: XNamespace ns = TargetNamespace; foreach (var element in output.Descendants()) { element.Name = ns.GetName(element.Name.LocalName); var attributes = element.Attributes().ToList(); element.Attributes().Remove(); foreach (XAttribute attribute in attributes) { if (!attribute.IsNamespaceDeclaration) { element.Add(new XAttribute(attribute.Name.LocalName, attribute.Value)); } } } //write to output body stream: var outStream = new MemoryStream(); var writer = new XmlTextWriter(outStream, Encoding.Default); output.WriteTo(writer); writer.Flush(); outStream.Flush(); outStream.Position = 0; pInMsg.BodyPart.Data = outStream; //promote the message type: pInMsg.Context.Promote(_MessageTypeProperty.Name.Name, _MessageTypeProperty.Name.Namespace, string.Format("{0}#{1}", TargetNamespace, RootElementName)); return pInMsg; }
static async Task ExecuteTask(TaskDefinition taskDefinition, IPipelineContext context) { logger.InfoFormat("Start executing scheduled task named '{0}'.", taskDefinition.Name); var sw = new Stopwatch(); sw.Start(); try { await taskDefinition.Task(context).ConfigureAwait(false); logger.InfoFormat("Scheduled task '{0}' run for {1}", taskDefinition.Name, sw.Elapsed); } catch (Exception ex) { logger.Error($"Failed to execute scheduled task '{taskDefinition.Name}'.", ex); } finally { sw.Stop(); } }
public Queue DecompressAndSpliMessage(IBaseMessage inMsg, IPipelineContext pctx) { var readOnlySeekableStream = GetSeekableStream(inMsg); var messages = _decompressor.DecompressMessage(readOnlySeekableStream); var outMsgs = new Queue(); IBaseMessage outMessage; foreach (var msg in messages) { outMessage = pctx.GetMessageFactory().CreateMessage(); outMessage.AddPart("Body", pctx.GetMessageFactory().CreateMessagePart(), true); outMessage.BodyPart.Data = msg.Value; outMessage.Context = PipelineUtil.CloneMessageContext(inMsg.Context); ContextExtensions.Promote(outMessage.Context, new ContextProperty(FileProperties.ReceivedFileName), msg.Key); outMsgs.Enqueue(outMessage); } return outMsgs; }
public void AddDocument(IPipelineContext pc, IBaseMessage pInMsg) { assembler.AddDocument(pc, pInMsg); string type = String.Empty; try { type = pInMsg.Context.Read("MessageType", NS) as string; } catch { type = String.Empty; } if (!string.IsNullOrWhiteSpace(type)) { pInMsg.Context.Write("Operation", NS, type); pInMsg.Context.Promote("Operation", NS, type); } }