Microsoft.Extensions.Logging.ILogger.LogDebug(string, params object[])

Here are the examples of the csharp api Microsoft.Extensions.Logging.ILogger.LogDebug(string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1079 Examples 7

19 View Source File : ScenarioRouteWalker.cs
License : MIT License
Project Creator : Azure

private IList<(MessagingObject RoutingObject, Channel InputChannel)> WalkSendRouteRecursively(string rule, string scenario, IEnumerable<Intermediary> intermediaries, IEnumerable<Channel> channels, IEnumerable<Endpoint> endpoints, IList<string> channelKeyRefs)
        {
            var discoveredRoutingObjects = new List<(MessagingObject, Channel)>();

            _logger.LogTrace(TraceMessages.CheckingInputChannels, rule, channelKeyRefs);

            // Loop through all of the channel keys.
            foreach (var channelKeyRef in channelKeyRefs)
            {
                var discoveredChannel = channels.FirstOrDefault(c => c.Key == channelKeyRef);
                if (discoveredChannel != null)
                {
                    // Only follow channels that are part of the route.
                    if (discoveredChannel.Properties.ContainsKey(ModelConstants.RouteLabel))
                    {
                        // Check if the next channel points to an intermediary.
                        var discoveredIntermediary = intermediaries.FirstOrDefault(i => i.InputChannelKeyRefs.Contains(channelKeyRef));
                        if (discoveredIntermediary != null)
                        {
                            _logger.LogTrace(TraceMessages.FoundIntermediaryAttachedToChannel, rule, discoveredIntermediary.Name, discoveredChannel.Name);

                            // Add the intermediary and carry on the route search.
                            discoveredRoutingObjects.Add((discoveredIntermediary, discoveredChannel));
                            discoveredRoutingObjects.AddRange(WalkSendRouteRecursively(rule, scenario, intermediaries, channels, endpoints, discoveredIntermediary.OutputChannelKeyRefs));
                        }
                        else
                        {
                            // Check to see if the channel points to an endpoint.
                            var discoveredEndpoint = endpoints.FirstOrDefault(e => e.InputChannelKeyRef == channelKeyRef);
                            if (discoveredEndpoint != null)
                            {
                                _logger.LogTrace(TraceMessages.FoundEndpointAttachedToChannel, rule, discoveredEndpoint.Name, discoveredChannel.Name);

                                // This is the end of this route, stop searching the branch.
                                discoveredRoutingObjects.Add((discoveredEndpoint, discoveredChannel));
                            }
                            else
                            {
                                _logger.LogError(ErrorMessages.UnableToFindMessagingObjectWithAnInputChannelInTargetModel, channelKeyRef);
                                _context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithAnInputChannelInTargetModel, channelKeyRef)));
                            }
                        }
                    }
                    else
                    {
                        _logger.LogDebug(TraceMessages.IgnoringChannel, rule, discoveredChannel.Name);
                    }
                }
                else
                {
                    _logger.LogError(ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, channelKeyRef);
                    _context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, channelKeyRef)));
                }
            }

            return discoveredRoutingObjects;
        }

19 View Source File : PipelineComponentParser.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "By design as the exception messages are collated in an error object.")]
        protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(PipelineComponentParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(PipelineComponentParser));

                foreach (var pipeline in group.Applications.SelectMany(a => a.Application.Pipelines).Where(p => p.Components != null))
                {
                    var pipelineType = pipeline.Direction == Types.Enumerations.PipelineDirection.Send ? ModelConstants.ResourceDefinitionSendPipeline : ModelConstants.ResourceReceivePipeline;

                    // Find the resource for the pipeline.                    
                    var pipelineResource = model.FindResourceByKey(pipeline.ResourceKey);

                    if (pipelineResource != null)
                    {
                        // Loop through all of the components.
                        var stageComponents = Doreplacedent.FindStageComponents(pipeline.Doreplacedent);
                        foreach (var stageComponent in stageComponents)
                        {
                            var resourceName = stageComponent.ComponentName;
                            var resourceKey = string.Concat(pipelineResource.Key, ":", resourceName);

                            // Create the component resource.
                            var pipelineComponentResource = new ResourceItem
                            {
                                Name = resourceName,
                                Key = resourceKey,
                                Type = ModelConstants.ResourcePipelineComponent,
                                Description = stageComponent.Description,
                                ParentRefId = pipelineResource.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            stageComponent.Resource = pipelineComponentResource; // Maintain pointer to the resource.
                            pipelineComponentResource.SourceObject = stageComponent; // Maintain backward pointer.
                            stageComponent.ResourceKey = resourceKey;
                            pipelineResource.Resources.Add(pipelineComponentResource);

                            _logger.LogDebug(TraceMessages.ResourceCreated, nameof(PipelineComponentParser), pipelineComponentResource.Key, pipelineComponentResource.Name, pipelineComponentResource.Type, pipelineResource.Key);
                        }                        
                    }
                    else 
                    {
                        var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResource, pipelineType, pipeline.ResourceKey);
                        _logger.LogError(error);
                        context.Errors.Add(new ErrorMessage(error));
                    }
                }
                _logger.LogDebug(TraceMessages.CompletedParser, nameof(PipelineComponentParser));
            }
        }

19 View Source File : DP003OrchestrationDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get the parsed BizTalk model from the application model.
            var parsedApplicationGroup = Model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (Model == null || Model.MigrationSource == null || Model.MigrationSource.MigrationSourceModel == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(DP003OrchestrationDependencyreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(DP003OrchestrationDependencyreplacedyzer));

                var resources = Model.FindAllResources();  // Gets all the resources in the model as a list

                ResolveMessageSchemaDependencies(resources);
                ResolveTransformDependencies(resources);

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(DP003OrchestrationDependencyreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP008ProcessManagerConfigurationEntryGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The configuration entry file name is expected to be lowercase")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(AP008ProcessManagerConfigurationEntryGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP008ProcessManagerConfigurationEntryGenerator));

                // Get all of the intermediaries and channels from the migration target.
                var intermediaries = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Intermediaries);
                var channels = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Channels);

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    // Loop through all of the activating process manager intermediaries.
                    foreach (var initiatingProcessManager in targetApplication.Intermediaries.Where(
                        im => (im.Activator && im is ProcessManager)
                        && !string.IsNullOrEmpty(im.ResourceMapKey))
                        )
                    {
                        var scenarioName = initiatingProcessManager.Properties[ModelConstants.ScenarioName].ToString();
                        var scenarioStepName = initiatingProcessManager.Properties[ModelConstants.ScenarioStepName].ToString();

                        var appConfigResource = initiatingProcessManager.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeConfigurationEntry);

                        if (appConfigResource != null)
                        {
                            // Walk the intermediaries starting at the receive endpoint.
                            var routingObjects = _routeWalker.WalkProcessManagerRoute(RuleName, scenarioName, initiatingProcessManager, intermediaries, channels);

                            // Get any global config from the resource.
                            var globalConfig = new JObject(
                                new JProperty("globalConfig",
                                new JObject(
                                from globalConfigSetting in appConfigResource.Parameters
                                where globalConfigSetting.Key.StartsWith(ModelConstants.ResourceTemplateParamterGlobalConfigPrefix, StringComparison.OrdinalIgnoreCase)
                                select new JProperty(
                                               globalConfigSetting.Key.Replace(ModelConstants.ResourceTemplateParamterGlobalConfigPrefix, string.Empty).Replace("_", " ").ConvertSnakeCaseToCamelCase(),
                                               globalConfigSetting.Value)
                                )));

                            // Get the configuration object.
                            var configurationObjects = from routingObject in routingObjects
                                                       where routingObject.RoutingObject.Properties.ContainsKey(ModelConstants.ScenarioStepName)
                                                       select new
                                                       {
                                                           ScenarioStepName = routingObject.RoutingObject.Properties[ModelConstants.ScenarioStepName].ToString(),
                                                           Configuration = routingObject.RoutingObject.Properties.TryGetValue(ModelConstants.ConfigurationEntry, out var value) ? value as Dictionary<string, object> : new Dictionary<string, object>()
                                                       };

                            // Generate the JSON configuration.
                            var configurationEntry = new JObject(
                                from configurationObject in configurationObjects
                                where configurationObject.Configuration != null
                                select new JProperty(configurationObject.ScenarioStepName,
                                    new JObject(
                                    from configurationProperty in configurationObject.Configuration.AsEnumerable()
                                    select new JProperty(configurationProperty.Key, JToken.FromObject(configurationProperty.Value))
                                    ))
                                );

                            // Merge in the global config.
                            configurationEntry.Merge(globalConfig, new JsonMergeSettings
                            {
                                MergeArrayHandling = MergeArrayHandling.Union
                            });

                            var conversionPath = Context.ConversionFolder;

                            var fileName = $"{initiatingProcessManager.Properties[ModelConstants.ScenarioName]}".ToLowerInvariant().Replace(" ", string.Empty); ;
                            var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(appConfigResource.OutputPath, $"{fileName}.configurationentry.json")));

                            _fileRepository.WriteJsonFile(outputPath.FullName, configurationEntry);
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeConfigurationEntry, initiatingProcessManager.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeConfigurationEntry, initiatingProcessManager.Name)));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(AP008ProcessManagerConfigurationEntryGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : DP005DistributionListDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var resources = Model.FindAllResources();

            if (resources == null || !resources.Any())
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(DP005DistributionListDependencyreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(DP005DistributionListDependencyreplacedyzer));

                // Get a list of all the send port groups
                var distributionLists = resources.Where(r => r.Type == ModelConstants.ResourceDistributionList);

                foreach (var distributionList in distributionLists)
                {
                    if (distributionList.SourceObject == null || !(distributionList.SourceObject.GetType() == typeof(DistributionList)))
                    {
                        // Source model corrupt
                        _logger.LogError(ErrorMessages.UnableToFindreplacedociatedResource, distributionList.Type, distributionList.Name, distributionList.Key);
                        distributionList.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Error, Message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindreplacedociatedResource, distributionList.Type, distributionList.Name, distributionList.Key) });
                        continue;
                    }

                    // Look up the send ports in the send port group.
                    var dl = (DistributionList)distributionList.SourceObject;
                    foreach (var sendPortRef in dl.SendPorts)
                    {
                        var matchingSendPorts = resources.Where(r => r.Type == ModelConstants.ResourceSendPort && r.SourceObject != null && r.SourceObject.GetType() == typeof(SendPort) && ((SendPort)r.SourceObject).Name == sendPortRef.Name);
                        if (matchingSendPorts == null || !matchingSendPorts.Any())
                        {
                            // No send ports found matching the one referenced in the DL
                            _logger.LogWarning(WarningMessages.DistributionListSendPortNotFound, sendPortRef.Name, distributionList.Name, distributionList.Key);
                            distributionList.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.DistributionListSendPortNotFound, sendPortRef.Name, distributionList.Name, distributionList.Key) });
                        }
                        else if (matchingSendPorts.Count() > 1)
                        {
                            // There are multiple send ports found, for example when two apps being replacedyzed use the same name
                            _logger.LogWarning(WarningMessages.DistributionListSendPortMultipleMatches, sendPortRef.Name, distributionList.Name, distributionList.Key);
                            distributionList.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.DistributionListSendPortMultipleMatches, sendPortRef.Name, distributionList.Name, distributionList.Key) });
                        }
                        else
                        {
                            // All good.  A send port has been found.
                            var sendPort = matchingSendPorts.Single();
                            distributionList.AddRelationship(new ResourceRelationship(sendPort.RefId, ResourceRelationshipType.CallsTo));
                            sendPort.AddRelationship(new ResourceRelationship(distributionList.RefId, ResourceRelationshipType.CalledBy));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(DP005DistributionListDependencyreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : SP003HttpSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var parsedApplicationGroup = Model.GetSourceModel<ParsedBizTalkApplicationGroup>();
            if (parsedApplicationGroup?.Applications != null)
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(SP003HttpSendPortreplacedyzer));

                foreach (var application in parsedApplicationGroup.Applications)
                {
                    var sendPorts = application.Application?.Bindings?.BindingInfo?.SendPortCollection;
                    if (sendPorts != null && sendPorts.Any())
                    {
                        foreach(var sendPort in sendPorts)
                        {
                            if (sendPort?.PrimaryTransport?.TransportType?.Name == "HTTP")
                            {
                                // Find adapter in target model
                                var adapterKey = $"{ModelConstants.MessageBusLeafKey}:{application.Application.Name.FormatKey()}:{sendPort.Name.FormatKey()}:{ModelConstants.AdapterEndpointLeafKey}";
                                var adapter = Model.FindMessagingObject(adapterKey);
                                if (adapter.messagingObject != null)
                                {
                                    var httpAdapter = (AdapterEndpoint)adapter.messagingObject;

                                    // Set conversion rating
                                    httpAdapter.Rating = ConversionRating.FullConversionWithFidelityLoss;

                                    // Set the message exchange pattern.
                                    httpAdapter.MessageExchangePattern = MessageExchangePattern.Send;

                                    // Set resource map key to hook into the configuration process
                                    var messagingObject = Model.FindMessagingObject(httpAdapter.Key);
                                    var appName = $"{messagingObject.application.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-")}";
                                    var adapterName = httpAdapter.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-");
                                    httpAdapter.ResourceMapKey = $"httpSendAdapterEndpoint{appName}{adapterName}";

                                    if (!string.IsNullOrEmpty(sendPort.PrimaryTransport.TransportTypeData))
                                    {
                                        var configItems = MapTransportTypeData(sendPort.PrimaryTransport.TransportTypeData);

                                        MapAdapterProperties(configItems, httpAdapter);

                                        foreach (var item in configItems)
                                        {
                                            httpAdapter.ReportMessages.Add(new ReportMessage()
                                            {
                                                Severity = MessageSeverity.Warning,
                                                Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkHttpAdapterPropertyNotSupported, item.Key, item.Value)
                                            });
                                        }

                                        // Map the config.
                                        var configProperties = httpAdapter.Properties[ModelConstants.ConfigurationEntry] as Dictionary<string, object>;

                                        httpAdapter.ReportLinks.Add(replacedysisResources.HttpAdapterHelpLink);
                                    }
                                    else
                                    {
                                        _logger.LogDebug(WarningMessages.SendPortTransportTypeDataNotFound, httpAdapter.Name);
                                        httpAdapter.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SendPortTransportTypeDataNotFound, httpAdapter.Name) });
                                    }
                                }
                                else
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey)));
                                }
                            }
                        }
                    }
                }
                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(SP003HttpSendPortreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(SP003HttpSendPortreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : DistributionListParser.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "By design as the exception messages are collated in an error object.")]
        protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(DistributionListParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(DistributionListParser));

                foreach (var application in group.Applications)
                {
                    // Defensive check
                    if (application.Application.Bindings == null)
                    {
                        _logger.LogWarning(WarningMessages.BindingInfoNotFound, application.Application.Name);
                        continue;
                    }

                    _logger.LogDebug(TraceMessages.ParsingBizTalkSendPortGroupFilterForApplication, application.Application.Name);

                    var bindingFileDefinition = model.FindResourceDefinitionByKey(application.Application.Bindings.ResourceDefinitionKey, ModelConstants.ResourceDefinitionBindings);
                    var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                    foreach (var distributionList in application.Application.Bindings.BindingInfo.DistributionListCollection)
                    {
                        _logger.LogDebug(TraceMessages.ParsingBizTalkSendPortGroupFilterForDistributionList, distributionList.Name);

                        // Set the resource key for the distribution list.
                        distributionList.ResourceKey = string.Concat(application.Application.Bindings.ResourceDefinitionKey, ":", distributionList.Name);

                        // Create the resource under the application.
                        var distributionListResource = new ResourceItem
                        {
                            Key = distributionList.ResourceKey,
                            Name = distributionList.Name,
                            Description = distributionList.Description,
                            Type = ModelConstants.ResourceDistributionList,
                            ParentRefId = bindingFileDefinition.RefId,
                            Rating = ConversionRating.NotSupported
                        };

                        distributionList.Resource = distributionListResource; // Maintain pointer to the resource.
                        distributionListResource.SourceObject = distributionList; // Maintain backward pointer.

                        bindingFileDefinition.Resources.Add(distributionListResource);
                     
                        if (applicationResource != null)
                        {
                            applicationResource.AddRelationship(new ResourceRelationship(distributionListResource.RefId, ResourceRelationshipType.Child));
                            distributionListResource.AddRelationship(new ResourceRelationship(applicationResource.RefId, ResourceRelationshipType.Parent));
                        }
                        else
                        {
                            var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceApplication, application.Application?.ApplicationDefinition?.ResourceKey);
                            _logger.LogError(error);
                            context.Errors.Add(new ErrorMessage(error));
                        }

                        try
                        {
                            if (!string.IsNullOrEmpty(distributionList.Filter))
                            {
                                distributionList.FilterExpression = Filter.FromXml(distributionList.Filter);
                                distributionList.FilterExpression.ResourceKey = string.Concat(distributionList.Name, ":", "filter");

                                // Create the distribution filter resource.
                                var filterReportResource = new ResourceItem
                                {
                                    Key = distributionList.FilterExpression.ResourceKey,
                                    Name = distributionListResource.Name + " filter expression",                                    
                                    Type = ModelConstants.ResourceFilterExpression,
                                    ParentRefId = distributionListResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                distributionList.FilterExpression.Resource = filterReportResource; // Maintain pointer to the resource.
                                filterReportResource.SourceObject = distributionList.FilterExpression; // Maintain backward pointer.
                                distributionListResource.Resources.Add(filterReportResource);
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorParsingDistributionListFilter, distributionList.Name, application.Application.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(DistributionListParser));
            }
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void BindResponseChannels(string channelKeyPrefix, Application targetApplication, ReceivePort receivePort, IList<MessagingObject> route)
        {
            _logger.LogDebug(TraceMessages.BindingChannelsForReceivePortResponse, RuleName, receivePort.Name);

            // replacedume route is in order, that is, first entry is the start of the route.  As the route is built
            // in this clreplaced, not expecting anything other than intermediaries and optionally an endpoint.
            for (var i = 0; i < route.Count - 1; i++)
            {
                // Determine from and to steps
                var fromStep = route[i];
                var toStep = route[i + 1];

                // Create channel
                var channel = new TriggerChannel(MigrationTargetResources.TriggerChannelName)
                {
                    Description = string.Format(CultureInfo.CurrentCulture, MigrationTargetResources.TriggerChannelDescription, toStep),
                    Key = $"{channelKeyPrefix}:{ModelConstants.TriggerChannelLeafKey}Response:{fromStep.Name.FormatKey()}-{toStep.Name.FormatKey()}",
                    Rating = ConversionRating.FullConversion
                };

                // Are we going from a routing slip router?
                if (fromStep is RoutingSlipRouter)
                {
                    // Set URL
                    var scenarioStep = toStep.Properties[ModelConstants.ScenarioStepName];
                    channel.TriggerUrl = $"/routingManager/route/{scenarioStep}";

                    // Label the channel appropriately
                    channel.Properties.Add(ModelConstants.RouteLabel, MigrationTargetResources.RouteToChannelLabel);
                }
                else
                {
                    // Label the channel appropriately
                    channel.Properties.Add(ModelConstants.RouteLabel, MigrationTargetResources.RouteFromChannelLabel);
                }

                // Add channel to application
                targetApplication.Channels.Add(channel);

                // Bind channel with endpoint and intermediaries
                if (fromStep is Endpoint endpoint)
                {
                    endpoint.OutputChannelKeyRef = channel.Key;
                }

                if (fromStep is Intermediary intermediary)
                {
                    intermediary.OutputChannelKeyRefs.Add(channel.Key);
                }

                ((Intermediary)toStep).InputChannelKeyRefs.Add(channel.Key);
            }
        }

19 View Source File : SendPortPipelineDataParser.cs
License : MIT License
Project Creator : Azure

protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(SendPortPipelineDataParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(SendPortPipelineDataParser));

                foreach (var application in group.Applications)
                {
                    // Defensive check
                    if (application.Application.Bindings == null)
                    {
                        _logger.LogWarning(WarningMessages.BindingInfoNotFound, application.Application.Name);
                        continue;
                    }

                    _logger.LogDebug(TraceMessages.ParsingBizTalkSendPipelineDataInApplication, application.Application.Name);
                    if (application.Application.Bindings.BindingInfo.SendPortCollection != null)
                    {
                        foreach (var sendPort in application.Application.Bindings.BindingInfo.SendPortCollection)
                        {
                            _logger.LogDebug(TraceMessages.ParsingBizTalkSendPortPipelineDataForSendPort, sendPort.Name);

                            sendPort.SendPipelineCustomConfiguration = ParsePipelineData(application, sendPort.Name, sendPort.SendPipelineData, PipelineDirection.Send, context.Errors);

                            sendPort.ReceivePipelineCustomConfiguration = ParsePipelineData(application, sendPort.Name, sendPort.ReceivePipelineData, PipelineDirection.Receive, context.Errors);
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(SendPortPipelineDataParser));
            }
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private SubscriptionFilter CreateDefaultSubscriptionFilter(Application targetApplication, SendPort sendPort)
        {
            _logger.LogDebug(TraceMessages.CreatingDefaultSendPortSubscription, RuleName, sendPort.Name);

            // Create filter expression
            string targetFilterExpression;
            if (sendPort.IsStatic)
            {
                targetFilterExpression = $"{ModelConstants.BizTalkSpTransportId} = '{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}.{sendPort.PrimaryTransport.TransportType.Name}'";
            }
            else
            {
                // It's a dynamic port, so won't have a primary transport
                targetFilterExpression = $"{ModelConstants.BizTalkSpTransportId} = '{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}'";
            }

            // Create a group, doesn't matter too much what the operation is as there is only one filter
            var targetFilterGroup = new OrFilterGroup();
            targetFilterGroup.Filters.Add(new Filter() { FilterExpression = targetFilterExpression });

            _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterStatement, RuleName, targetFilterExpression);

            // Create filter and return
            var subscriptionFilter = new SubscriptionFilter(targetFilterGroup);

            _logger.LogTrace(TraceMessages.CreatedDefaultSubscriptionFilterGroupForSendPort, RuleName, targetFilterGroup.Operation, sendPort.Name);

            return subscriptionFilter;
        }

19 View Source File : AP002SendRoutingSlipGenerator.cs
License : MIT License
Project Creator : Azure

private TargetResourceTemplate FindLogicAppResource(IEnumerable<TargetResourceTemplate> resources, string scope, string scenarioStepName)
        {
            
            _logger.LogTrace(TraceMessages.FindingResourceTemplateByScenarioStepName, RuleName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);

            var templates = resources.Where(r =>
                r.ResourceType.StartsWith(ModelConstants.ResourceTypeAzureLogicApp) &&
                r.Parameters.ContainsKey(ModelConstants.ResourceTemplateParameterScenarioStepName) &&
                r.Parameters[ModelConstants.ResourceTemplateParameterScenarioStepName].ToString() == scenarioStepName);

            if (templates != null && templates.Any())
            {
                if (templates.Count() == 1)
                {
                    return templates.Single();
                }
                else
                {
                    _logger.LogDebug(TraceMessages.FoundTooManyResourceTemplatesByScenarioStepName, RuleName, templates.Count(), ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);
                }
            }
            else
            {
                _logger.LogDebug(TraceMessages.FoundNoResourceTemplateByScenarioStepName, RuleName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);
            }

            return null;
        }

19 View Source File : ResourceGeneratorAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get temp location for rendered template configuration
            var tempPath = Path.Combine(Path.GetTempPath(), "aim-config");

            _logger.LogDebug(TraceMessages.RenderingTemplateConfigInTempPath, tempPath);

            // Render the Liquid configuration first into a new temp location
            await _repository.RenderConfigurationAsync(Model, Context.TemplateConfigFolder, tempPath).ConfigureAwait(false);

            _logger.LogTrace(TraceMessages.RetrievingConfigurationFromTempPath, tempPath);

            // Get configuration from temp path
            var config = _repository.GetConfiguration(tempPath);

            _logger.LogDebug(TraceMessages.GeneratingResourcesInTargetModel);

            // Generate resources in target model using rendered configuration
            await _generator.GenerateResourcesAsync(Model, config, token).ConfigureAwait(false);
        }

19 View Source File : SP002FileSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var parsedApplicationGroup = Model.GetSourceModel<ParsedBizTalkApplicationGroup>();
            if (parsedApplicationGroup?.Applications != null)
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(SP002FileSendPortreplacedyzer));

                foreach (var application in parsedApplicationGroup.Applications)
                {
                    var sendPorts = application.Application?.Bindings?.BindingInfo?.SendPortCollection;
                    if (sendPorts != null && sendPorts.Any())
                    {
                        foreach(var sendPort in sendPorts)
                        {
                            if (sendPort?.PrimaryTransport?.TransportType?.Name == "FILE")
                            {
                                // Find adapter in target model
                                var adapterKey = $"{ModelConstants.MessageBusLeafKey}:{application.Application.Name.FormatKey()}:{sendPort.Name.FormatKey()}:{ModelConstants.AdapterEndpointLeafKey}";
                                var adapter = Model.FindMessagingObject(adapterKey);
                                if (adapter.messagingObject != null)
                                {
                                    var fileAdapter = (AdapterEndpoint)adapter.messagingObject;

                                    // Set conversion rating
                                    fileAdapter.Rating = ConversionRating.FullConversionWithFidelityLoss;

                                    // Set the message exchange pattern.
                                    fileAdapter.MessageExchangePattern = MessageExchangePattern.Send;

                                    // Set resource map key to hook into the configuration process
                                    var messagingObject = Model.FindMessagingObject(fileAdapter.Key);
                                    var appName = $"{messagingObject.application.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-")}";
                                    var adapterName = fileAdapter.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-");
                                    fileAdapter.ResourceMapKey = $"fileSendAdapterEndpoint{appName}{adapterName}";

                                    if (!string.IsNullOrEmpty(sendPort.PrimaryTransport.TransportTypeData))
                                    {
                                        var configItems = MapTransportTypeData(sendPort.PrimaryTransport.TransportTypeData);

                                        // Add the address to the config items.
                                        var address = sendPort.PrimaryTransport.Address;
                                        if (!string.IsNullOrEmpty(address))
                                        {
                                            if (configItems.TryGetValue("FileName", out var fileName))
                                            {
                                                address = address.Replace(fileName, string.Empty);
                                            }
                                            // Replace the path separator to ensure its can be processed by the Azure CLI.
                                            address = address.Replace("\\", "/");
                                        }
                                        configItems.Add("Address", address);

                                        MapAdapterProperties(configItems, fileAdapter);

                                        foreach (var item in configItems)
                                        {
                                            fileAdapter.ReportMessages.Add(new ReportMessage()
                                            {
                                                Severity = MessageSeverity.Warning,
                                                Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkFileAdapterPropertyNotSupported, item.Key, item.Value)
                                            });
                                        }

                                        // Map the config.
                                        var configProperties = fileAdapter.Properties[ModelConstants.ConfigurationEntry] as Dictionary<string, object>;

                                        configProperties["copyMode"] = MapCopyMode(fileAdapter.Properties["copyMode"]);
                                        configProperties["destinationFolder"] = fileAdapter.Properties["rootFolder"];
                                        configProperties["fileName"] = fileAdapter.Properties["fileName"];

                                        fileAdapter.ReportLinks.Add(replacedysisResources.FileAdapterHelpLink);
                                    }
                                    else
                                    {
                                        _logger.LogDebug(WarningMessages.SendPortTransportTypeDataNotFound, fileAdapter.Name);
                                        fileAdapter.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SendPortTransportTypeDataNotFound, fileAdapter.Name) });
                                    }
                                }
                                else
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey)));
                                }
                            }
                        }
                    }
                }
                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(SP002FileSendPortreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(SP002FileSendPortreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : SC001DocumentSchemaGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The folder paths are lowercased, so must use a lowercase function.")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(SC001DoreplacedentSchemaGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(SC001DoreplacedentSchemaGenerator));

                var conversionPath = Context.ConversionFolder;

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    foreach (var message in targetApplication.Messages)
                    {
                        // Key the resource for the schema (message definition from the model).
                        var messageResource = Model.FindResourceByKey(message.MessageSchema?.ResourceKeyRef);

                        if (messageResource == null)
                        {
                            _logger.LogWarning(WarningMessages.ResourceNotFoundByKey, message.MessageSchema?.ResourceKeyRef);
                        }
                        else
                        {
                            // Get the schema resource (which is a parent of the message definition) from the model.
                            var schemaResource = Model.FindResourceByRefId(messageResource.ParentRefId);

                            if (schemaResource == null)
                            {
                                _logger.LogWarning(WarningMessages.ResourceNotFoundByRefId, messageResource.ParentRefId);
                            }
                            else
                            {
                                // Get the schema resource definition which is the parent of the schema resource. This is required for the schema resource definition content.
                                var schemaResourceDefinition = Model.FindResourceDefinitionByRefId(schemaResource.ParentRefId);

                                if (schemaResourceDefinition == null)
                                {
                                    _logger.LogWarning(WarningMessages.ResourceDefinitionNotFound, schemaResource.ParentRefId);
                                }
                                else
                                {
                                    var schemaXmlResources = message.Resources.Where(r => r.ResourceType == ModelConstants.ResourceTypeXml);

                                    if (schemaXmlResources != null && schemaXmlResources.Count() > 0)
                                    {
                                        foreach (var schemaXmlResource in schemaXmlResources)
                                        {
                                            var fileName = $"{targetApplication.Name}.{message.MessageSchema.Name}".Replace(" ", string.Empty);

                                            var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(schemaXmlResource.OutputPath, $"{fileName}.xsd")));

                                            _fileRepository.WriteXmlFile(outputPath.FullName, schemaResourceDefinition.ResourceContent.ToString());

                                            _logger.LogDebug(TraceMessages.SavingArtifact, outputPath.FullName);
                                        }
                                    }
                                    else
                                    {
                                        var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeXml, message.Name);
                                        _logger.LogError(error);
                                        Context.Errors.Add(new ErrorMessage(error));
                                    }
                                }
                            }
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(SC001DoreplacedentSchemaGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private IList<MessagingObject> BindRoute(string intermediaryKeyPrefix, Application targetApplication, SendPort sendPort, IList<MessagingObject> route)
        {
            _logger.LogDebug(TraceMessages.BindingRouteForSendPort, RuleName, sendPort.Name);

            var boundRoute = new List<MessagingObject>();

            // Add routing slip routers
            for (var i = 1; i < route.Count; i++)
            {
                // Determine from and to steps
                var fromStep = route[i - 1];
                var toStep = route[i];

                // Add step and then follow with a routing slip router intermediary
                boundRoute.Add(fromStep);
                boundRoute.Add(CreateRoutingSlipRouterIntermediary(intermediaryKeyPrefix, fromStep.Name, toStep.Name));

                // If at the end, add last step
                if (i == (route.Count - 1))
                {
                    boundRoute.Add(toStep);
                }
            }

            // Add to target application
            foreach (var step in boundRoute)
            {
                if (step is Endpoint)
                {
                    targetApplication.Endpoints.Add((Endpoint)step);
                }
                else
                {
                    targetApplication.Intermediaries.Add((Intermediary)step);
                }
            }

            return boundRoute;
        }

19 View Source File : BizTalkApplicationParser.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "By design as the exception messages are collated in an error object.")]
        protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(BizTalkApplicationParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(BizTalkApplicationParser));

                foreach (var application in group.Applications)
                {
                    try
                    {
                        // Defensive check
                        if (application.Application.ApplicationDefinition == null)
                        {
                            _logger.LogWarning(WarningMessages.ApplicationDefinitionNotFound, application.Application.Name);
                            continue;
                        }

                        _logger.LogDebug(TraceMessages.ParsingBizTalkApplicationFromResourceContainer, application.Application.ApplicationDefinition.ResourceContainerKey);

                        var adf = from resourceContainer in model.MigrationSource.ResourceContainers
                                    from resourceDefinition in resourceContainer.ResourceDefinitions
                                    where resourceContainer.Key == application.ResourceContainerKey &&
                                    application.Application.ApplicationDefinition.ResourceContainerKey == resourceContainer.Key &&
                                    application.Application.ApplicationDefinition.ResourceDefinitionKey == resourceDefinition.Key &&
                                    resourceDefinition.Type == ModelConstants.ResourceDefinitionApplicationDefinition
                                    select resourceDefinition;

                        var applicationResourceDefinition = adf.SingleOrDefault();
                        if (applicationResourceDefinition == null)
                        {
                            _logger.LogWarning(WarningMessages.ApplicationDefinitionNotFound, application.Application.Name);
                            continue;
                        }

                        var applicationDefinition = application.Application.ApplicationDefinition.ApplicationDefinition ?? ApplicationDefinition.FromXml((string)applicationResourceDefinition.ResourceContent); // Only parse if not already deserialized.
                        var applicationName = applicationDefinition.Properties.Where(p => p.Name == BizTalkApplicationParser.ApplicationDisplayNameProperty).SingleOrDefault();

                        if (applicationName != null && !string.IsNullOrWhiteSpace(applicationName.Value))
                        {
                            // Check to see if there is already an application in the source with this name (duplicate names can occur is preplaceding multiple unrelated
                            // MSI files).
                            var duplicateApplication = model.FindResourcesByType(ModelConstants.ResourceApplication).Any(a => a.Name == applicationName.Value);

                            // Set application name
                            application.Application.Name = applicationName.Value;
                            if (duplicateApplication)
                            {
                                application.Application.Name = $"{application.Application.Name} {ResourceItemProperties.Duplicate}";
                            }

                            // Define resource key for application.
                            var resourceKey = string.Concat(applicationResourceDefinition.Key, ":", applicationName);
                            application.Application.ApplicationDefinition.ResourceKey = resourceKey;

                            // Create the application resource under the application definition resource.
                            var applicationResource = new ResourceItem
                            {
                                Name = applicationName.Value,
                                Description = applicationDefinition.Properties.Where(p => p.Name == BizTalkApplicationParser.ApplicationDescriptionProperty).SingleOrDefault()?.Value,
                                Key = resourceKey,
                                Type = ModelConstants.ResourceApplication,
                                ParentRefId = applicationResourceDefinition.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            application.Application.ApplicationDefinition.Resource = applicationResource; // Maintain pointer to the resource.
                            applicationResource.SourceObject = applicationDefinition; // Maintain backward pointer.
                            applicationResourceDefinition.Resources.Add(applicationResource);

                            _logger.LogTrace(TraceMessages.ResourceCreated, nameof(BizTalkApplicationParser), applicationResource.Key, applicationResource.Name, applicationResource.Type, applicationResource.Key);

                            // If this does not exist then update on the source model.
                            if (application.Application.ApplicationDefinition.ApplicationDefinition == null)
                            {
                                application.Application.ApplicationDefinition.ApplicationDefinition = applicationDefinition;
                            }

                            _logger.LogDebug(TraceMessages.ParsedTheBizTalkApplicationWithName, application.Application.Name);

                            // Raise an error if this was a duplicate application
                            if (duplicateApplication)
                            {
                                // Raise an error that there is already an application with this name
                                var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.DuplicateApplicationFound, applicationName.Value);
                                context.Errors.Add(new ErrorMessage(message));
                                _logger.LogError(message);
                            }
                        }
                        else
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ApplicationNameNotFound, applicationResourceDefinition.Key);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorReadingApplicationFromAdf, application.Application.ApplicationDefinition.ResourceDefinitionKey, ex.Message);
                        context.Errors.Add(new ErrorMessage(message));
                        _logger.LogError(message);
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(BizTalkApplicationParser));
            }
        }

19 View Source File : SP006SapSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

private void MapAdapterAddressProperties(Dictionary<string, string> configItems, AdapterEndpoint endpoint)
        {
            // Set supported property names and defaults
            var supportedProperties = new Dictionary<string, (string, object)>()
            {
                { "ConnectionType", ("connectionType", string.Empty) },
                { "ApplicationServerHost", ("applicationServerHost", string.Empty) },
                { "SystemNumber", ("applicationServerSystemNumber", string.Empty) },
                { "MessageServerHost", ("messageServerHost", string.Empty) },
                { "R3SystemName", ("messageServerSystemName", string.Empty) },
                { "DestinationName", ("sapRfcIniDestinationName", string.Empty) },
                { "CLIENT", ("clientNumber", "800") },
                { "LANG", ("language", "EN") },
                { "GWHOST", ("applicationServerGatewayHost", string.Empty) },
                { "GWSERV", ("applicationServerGatewayService", string.Empty) },
                { "MSSERV", ("messageServerService", string.Empty) },
                { "GROUP", ("messageServerApplicationServerGroupName", string.Empty) },
                { "ListenerDest", ("rfcServerSapRfcIniDestinationName", string.Empty) },
                { "ListenerGwServ", ("rfcServerGatewayService", string.Empty) },
                { "ListenerGwHost", ("rfcServerGatewayHost", string.Empty) },
                { "ListenerProgramId", ("rfcServerProgramId", string.Empty) },
                { "RfcSdkTrace", ("rfcSdkTraceEnabled", false) },
                { "AbapDebug", ("abapDebugEnabled", false) },
                { "UseSnc", ("useSnc", false) }
            };

            // Search through BizTalk adapter properties and match properties
            foreach (var supportedProperty in supportedProperties)
            {
                (string mappedName, object mappedValue) mappedProperty = supportedProperty.Value;

                if (configItems.ContainsKey(supportedProperty.Key) && !string.IsNullOrEmpty(configItems[supportedProperty.Key]))
                {
                    // Convert values
                    var convertedValue = ConvertAdapterProperty(supportedProperty.Key, configItems[supportedProperty.Key]);

                    // Set value on endpoint
                    endpoint.Properties.Add(mappedProperty.mappedName, convertedValue);

                    _logger.LogDebug(TraceMessages.BizTalkSapSendAdapterBindingPropertyFound, RuleName, supportedProperty.Key, endpoint.Name, convertedValue);

                    // Remove handled property from BizTalk adapter property list
                    configItems.Remove(supportedProperty.Key);
                }
                else
                {
                    // Set default value
                    endpoint.Properties.Add(mappedProperty.mappedName, mappedProperty.mappedValue);

                    _logger.LogDebug(TraceMessages.BizTalkSapSendAdapterBindingPropertyNotFound, RuleName, supportedProperty.Key, endpoint.Name, mappedProperty.mappedValue);
                }
            }
        }

19 View Source File : OrchestrationServiceDeclarationParser.cs
License : MIT License
Project Creator : Azure

protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(OrchestrationServiceDeclarationParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(OrchestrationServiceDeclarationParser));

                foreach (var application in group.Applications)
                {
                    // Loop through all of the orchestrations.
                    foreach (var orchestration in application.Application.Orchestrations)
                    {
                        // Find the module for the orchestration.
                        var moduleResource = orchestration.Model?.Resource?.FindResourcesByType(ModelConstants.ResourceModule).SingleOrDefault();
                        if (moduleResource != null)
                        {
                            // Find service declaration
                            var serviceDeclaration = orchestration.FindServiceDeclaration();
                            if (serviceDeclaration != null)
                            {
                                var resourceName = serviceDeclaration.FindPropertyValue(MetaModelConstants.PropertyKeyName);
                                var resourceKey = string.Concat(moduleResource.Key, ":", resourceName);

                                var serviceDeclarationResource = new ResourceItem
                                {
                                    Name = resourceName,
                                    Key = resourceKey,
                                    Type = ModelConstants.ResourceServiceDeclaration,
                                    ParentRefId = moduleResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                serviceDeclaration.Resource = serviceDeclarationResource; // Maintain pointer to resource.
                                serviceDeclarationResource.SourceObject = serviceDeclaration; // Maintain backward pointer.
                                moduleResource.Resources.Add(serviceDeclarationResource);

                                _logger.LogTrace(TraceMessages.ResourceCreated, nameof(OrchestrationServiceDeclarationParser), serviceDeclarationResource.Key, serviceDeclarationResource.Name, serviceDeclarationResource.Type, moduleResource.Key);

                                ParseMessageDeclarations(orchestration, serviceDeclarationResource);
                                ParseCorrelationDeclarations(orchestration, serviceDeclarationResource);
                                ParsePortDeclarations(orchestration, serviceDeclarationResource);
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindServiceDeclarationInOrchestrationModel, orchestration.ResourceContainerKey, orchestration.FullName);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            };
                        }
                        else
                        {
                            var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResource, ModelConstants.ResourceModule, orchestration.ResourceDefinitionKey);
                            _logger.LogError(error);
                            context.Errors.Add(new ErrorMessage(error));
                        }
                    }
                }
                _logger.LogDebug(TraceMessages.CompletedParser, nameof(OrchestrationServiceDeclarationParser));
            }
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private MessageSubscriber CreateMessageSubscriberIntermediary(string intermediaryKeyPrefix, Application targetApplication, ReceivePort receivePort, ResourceItem receiveLocation)
        {
            _logger.LogDebug(TraceMessages.CreatingMessageSubscriberIntermediaryReceivePort, RuleName, MigrationTargetResources.MessageSubscriberName, receivePort.Name);

            // Format names
            var applicationName = targetApplication.Name.FormatKey();
            var receivePortName = receivePort.Name.FormatKey();
            var receiveLocationName = receiveLocation.Name.FormatKey();

            var scenarioName = $"{targetApplication.Name.FormatKey()}.{receivePort.Name.FormatKey()}.{receiveLocationName}.Response";

            // Create an intermediary based on the message subscriber
            var messageSubscriberIntermediary = new MessageSubscriber(receivePort.Name)
            {
                Description = MigrationTargetResources.MessageSubscriberDescription,
                Key = $"{intermediaryKeyPrefix}:{ModelConstants.MessageSubscriberLeafKey}",
                ResourceMapKey = $"topicSubscriber{applicationName.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-")}{receivePortName.Replace(".", "-").Replace("/", "-").Replace(":", "-")}",
                Rating = ConversionRating.FullConversion,
                Activator = true
            };

            // Set scenario and step name as properties on the endpoint
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ScenarioName, scenarioName);
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ScenarioStepName, "messageSubscriber");

            // Set BizTalk specific configuration properties
            var configurationEntries = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkAckReceivePortId, $"{applicationName}.{receivePortName}" }
            };

            // Add configuration properties
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ConfigurationEntry, configurationEntries);

            // Set BizTalk specific routing properties
            var routingProperties = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkAckReceivePortId, ModelConstants.BizTalkAckReceivePortId }
            };

            // Add routing properties
            messageSubscriberIntermediary.Properties.Add(ModelConstants.RoutingProperties, routingProperties);

            // Add subscription filter
            CreateMessageSubscriberFilter(messageSubscriberIntermediary, receivePort);

            return messageSubscriberIntermediary;
        }

19 View Source File : SendPortParser.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "By design as the exception messages are collated in an error object.")]
        protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(SendPortParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(SendPortParser));

                foreach (var application in group.Applications)
                {
                    // Defensive check
                    if (application.Application.Bindings == null)
                    {
                        _logger.LogWarning(WarningMessages.BindingInfoNotFound, application.Application.Name);
                        continue;
                    }

                    _logger.LogDebug(TraceMessages.ParsingBizTalkSendPortFiltersInApplication, application.Application.Name);

                    var bindingFileDefinition = model.FindResourceDefinitionByKey(application.Application.Bindings.ResourceDefinitionKey, ModelConstants.ResourceDefinitionBindings);
                    var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                    foreach (var sendPort in application.Application.Bindings.BindingInfo.SendPortCollection)
                    {
                        try
                        {
                            sendPort.ResourceKey = string.Concat(application.Application.Bindings.ResourceDefinitionKey, ":", sendPort.Name);

                            // Create the resource under the binding file.
                            var sendPortResource = new ResourceItem
                            {
                                Key = sendPort.ResourceKey,
                                Name = sendPort.Name,
                                Description = sendPort.Description,
                                Type = ModelConstants.ResourceSendPort,
                                ParentRefId = bindingFileDefinition.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            sendPort.Resource = sendPortResource; // Maintain pointer to the resource.
                            sendPortResource.SourceObject = sendPort; // Maintain backward pointer.

                            // Static or dynamic port?
                            if (sendPort.IsStatic)
                            {
                                // Static port
                                sendPortResource.Properties.Add(ResourceItemProperties.SendPortTypeProperty, ResourceItemProperties.StaticSendPortType);
                                sendPortResource.Properties.Add(ResourceItemProperties.SendPortPrimaryTransportTypeProperty, sendPort.PrimaryTransport.TransportType?.Name);
                                sendPortResource.Properties.Add(ResourceItemProperties.SendPortPrimaryAddressProperty, sendPort.PrimaryTransport.Address);
                                if (sendPort.SecondaryTransport != null && !string.IsNullOrEmpty(sendPort.SecondaryTransport.Address))
                                {
                                    sendPortResource.Properties.Add(ResourceItemProperties.SendPortSecondaryTransportTypeProperty, sendPort.SecondaryTransport.TransportType?.Name);
                                    sendPortResource.Properties.Add(ResourceItemProperties.SendPortSecondaryAddressProperty, sendPort.SecondaryTransport.Address);
                                }
                            }
                            else
                            {
                                // Dynamic port
                                sendPortResource.Properties.Add(ResourceItemProperties.SendPortTypeProperty, ResourceItemProperties.DynamicSendPortType);
                            }

                            sendPortResource.Properties.Add(ResourceItemProperties.PortDirectionProperty, sendPort.IsTwoWay ? ResourceItemProperties.PortDirectionTwoWay : ResourceItemProperties.PortDirectionOneWay);

                            bindingFileDefinition.Resources.Add(sendPortResource);

                            if (applicationResource != null)
                            {
                                applicationResource.AddRelationship(new ResourceRelationship(sendPortResource.RefId, ResourceRelationshipType.Child));
                                sendPortResource.AddRelationship(new ResourceRelationship(applicationResource.RefId, ResourceRelationshipType.Parent));
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceApplication, application.Application?.ApplicationDefinition?.ResourceKey);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            }

                            if (!string.IsNullOrEmpty(sendPort.Filter))
                            {
                                sendPort.FilterExpression = Filter.FromXml(sendPort.Filter);
                                sendPort.FilterExpression.ResourceKey = string.Concat(sendPort.Name, ":", "filter");

                                var filterResource = new ResourceItem
                                {                                    
                                    Key = sendPort.FilterExpression.ResourceKey,
                                    Name = sendPortResource.Name + " filter expression",
                                    Type = ModelConstants.ResourceFilterExpression,
                                    ParentRefId = sendPortResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                sendPort.FilterExpression.Resource = filterResource; // Maintain pointer to the resource.
                                filterResource.SourceObject = sendPort.FilterExpression; // Maintain backward pointer.
                                sendPortResource.Resources.Add(filterResource);

                                _logger.LogDebug(TraceMessages.ParsedBizTalkSendPortFilterExpression, sendPort.Name);
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorParsingSendPort, sendPort.Name, application.Application.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(SendPortParser));
            }
        }

19 View Source File : DP003OrchestrationDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

private void ResolveTransformDependencies(IList<ResourceItem> resources)
        {
            var serviceDeclarations = resources.Where(s => s.Type == ModelConstants.ResourceServiceDeclaration);
            var transforms = resources.Where(t => t.Type == ModelConstants.ResourceMap && t.SourceObject != null);

            // Iterate through the service declarations (orchestrations) and look for transforms used within the service declaration.
            foreach (var serviceDeclaration in serviceDeclarations)
            {
                // Check for bad references.
                if (serviceDeclaration.SourceObject == null)
                {
                    _logger.LogError(ErrorMessages.SourceObjectNotFound, serviceDeclaration.Name, serviceDeclaration.Type);
                    var errorMessage = string.Format(CultureInfo.CurrentCulture, ErrorMessages.SourceObjectNotFound, serviceDeclaration.Name, serviceDeclaration.Type);
                    Context.Errors.Add(new ErrorMessage(errorMessage));
                    serviceDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Error, Message = errorMessage });
                    continue;
                }

                // Find all the transform shapes within the orchestration.
                var sourceObject = (Element)serviceDeclaration.SourceObject;
                var transformShapes = sourceObject.FindTransforms();

                if (transformShapes != null && transformShapes.Any())
                {
                    foreach (var transformShape in transformShapes)
                    {
                        var transformType = transformShape.FindPropertyValue(MetaModelConstants.PropertyKeyClreplacedName);

                        // Search for a matching resource.
                        var matchingTransforms = transforms.Where(t => ((Transform)t.SourceObject).FullName == transformType);

                        if (matchingTransforms == null || !matchingTransforms.Any())
                        {
                            // Log as we can't find a matching schema.
                            _logger.LogDebug(TraceMessages.TransformDependencyNotResolved, RuleName, transformType);
                            serviceDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.TransformReferencedByServiceDeclarationIsMissing, transformType, serviceDeclaration.Key) });
                        }
                        else if (matchingTransforms.Count() > 1)
                        {
                            serviceDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.TransformReferenceMultipleMatches, transformType, serviceDeclaration.Key, matchingTransforms.Count()) });
                        }
                        else
                        {
                            // We have a matching reference
                            var transform = matchingTransforms.Single();
                            transform.AddRelationship(new ResourceRelationship(serviceDeclaration.RefId, ResourceRelationshipType.ReferencedBy));
                            serviceDeclaration.AddRelationship(new ResourceRelationship(transform.RefId, ResourceRelationshipType.ReferencesTo));
                        }
                    }
                }
            }
        }

19 View Source File : DP004ApplicationDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var parsedApplicationGroup = Model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (parsedApplicationGroup?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(DP004ApplicationDependencyreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(DP004ApplicationDependencyreplacedyzer));

                // Find all application definitions in source model
                var applicationDefinitionFiles = parsedApplicationGroup.Applications.Select(a => a.Application.ApplicationDefinition).Where(ad => ad != null);
                if (applicationDefinitionFiles != null && applicationDefinitionFiles.Any())
                {
                    foreach (var applicationDefinitionFile in applicationDefinitionFiles)
                    {
                        if (applicationDefinitionFile.ApplicationDefinition != null)
                        {
                            // Get application name
                            var applicationName = applicationDefinitionFile.ApplicationDefinition.GetPropertyValue(ApplicationDefinitionConstants.PropertyKeyDisplayName);

                            // Defensive check
                            if (applicationDefinitionFile.Resource == null)
                            {
                                _logger.LogError(ErrorMessages.UnableToFindreplacedociatedResource, applicationDefinitionFile.GetType(), applicationName, applicationDefinitionFile.ResourceKey);
                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindreplacedociatedResource, applicationDefinitionFile.GetType(), applicationName, applicationDefinitionFile.ResourceKey)));
                                continue;
                            }
                            
                            // Get application references
                            var applicationRefs = applicationDefinitionFile?.ApplicationDefinition?.References?.Where(r => r.Name != "BizTalk.System");
                            if (applicationRefs != null && applicationRefs.Any())
                            {
                                foreach (var applicationRef in applicationRefs)
                                {
                                    var foundReference = false;

                                    // Search all application definitions in source model for related applications
                                    var relatedApplicationDefinitionFiles = parsedApplicationGroup.Applications.Select(a => a.Application.ApplicationDefinition).Where(a => a != null && a.ApplicationDefinition != null);
                                    if (relatedApplicationDefinitionFiles != null && relatedApplicationDefinitionFiles.Any())
                                    {
                                        foreach (var relatedApplicationDefinitionFile in applicationDefinitionFiles)
                                        {
                                            // Get application name
                                            var relatedApplicationName = relatedApplicationDefinitionFile.ApplicationDefinition.GetPropertyValue(ApplicationDefinitionConstants.PropertyKeyDisplayName);

                                            // Defensive check
                                            if (relatedApplicationDefinitionFile.Resource == null)
                                            {
                                                _logger.LogError(ErrorMessages.UnableToFindreplacedociatedResource, relatedApplicationDefinitionFile.GetType(), relatedApplicationName, relatedApplicationDefinitionFile.ResourceKey);
                                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindreplacedociatedResource, relatedApplicationDefinitionFile.GetType(), relatedApplicationName, relatedApplicationDefinitionFile.ResourceKey)));
                                                continue;
                                            }

                                            if (relatedApplicationName == applicationRef.Name)
                                            {
                                                // Add relationships between application resource and related application resource
                                                applicationDefinitionFile.Resource.ResourceRelationships.Add(new ResourceRelationship(relatedApplicationDefinitionFile.Resource.RefId, ResourceRelationshipType.ReferencesTo));

                                                _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, applicationDefinitionFile.ResourceKey, relatedApplicationDefinitionFile.ResourceKey, ResourceRelationshipType.ReferencesTo);

                                                // Add reverse relationship between schema resource and transform resource
                                                relatedApplicationDefinitionFile.Resource.ResourceRelationships.Add(new ResourceRelationship(applicationDefinitionFile.Resource.RefId, ResourceRelationshipType.ReferencedBy));

                                                _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, relatedApplicationDefinitionFile.ResourceKey, applicationDefinitionFile.ResourceKey, ResourceRelationshipType.ReferencedBy);

                                                foundReference = true;
                                            }
                                        }
                                    }

                                    if (!foundReference)
                                    {
                                        // Add unresolved dependency message to application resource
                                        _logger.LogWarning(WarningMessages.ApplicationReferencedByApplicationIsMissing, applicationRef.Name, applicationName);
                                        var warning = string.Format(CultureInfo.CurrentCulture, WarningMessages.ApplicationReferencedByApplicationIsMissing, applicationRef.Name, applicationName);
                                        applicationDefinitionFile.Resource.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = warning });
                                    }
                                }
                            }
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.NoApplicationDefinition, applicationDefinitionFile.ResourceDefinitionKey);
                            var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.NoApplicationDefinition, applicationDefinitionFile.ResourceDefinitionKey);
                            Context.Errors.Add(new ErrorMessage(error));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(DP004ApplicationDependencyreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void BindChannels(string channelKeyPrefix, Application targetApplication, ReceivePort receivePort, IList<MessagingObject> route)
        {
            _logger.LogDebug(TraceMessages.BindingChannelsForReceivePort, RuleName, receivePort.Name);

            // replacedume route is in order, that is, first entry is the start of the route.  As the route is built
            // in this clreplaced, not expecting anything other than intermediaries and optionally an endpoint.
            for (var i = 0; i < route.Count - 1; i++)
            {
                // Determine from and to steps
                var fromStep = route[i];
                var toStep = route[i + 1];

                // Create channel
                var channel = new TriggerChannel(MigrationTargetResources.TriggerChannelName)
                {
                    Description = string.Format(CultureInfo.CurrentCulture, MigrationTargetResources.TriggerChannelDescription, toStep),
                    Key = $"{channelKeyPrefix}:{ModelConstants.TriggerChannelLeafKey}:{fromStep.Name.FormatKey()}-{toStep.Name.FormatKey()}",
                    Rating = ConversionRating.FullConversion
                };

                // Are we going from a routing slip router?
                if (fromStep is RoutingSlipRouter)
                {
                    // Set URL
                    var scenarioStep = toStep.Properties[ModelConstants.ScenarioStepName];
                    channel.TriggerUrl = $"/routingManager/route/{scenarioStep}";

                    // Label the channel appropriately
                    channel.Properties.Add(ModelConstants.RouteLabel, MigrationTargetResources.RouteToChannelLabel);
                }
                else
                {
                    // Label the channel appropriately
                    channel.Properties.Add(ModelConstants.RouteLabel, MigrationTargetResources.RouteFromChannelLabel);
                }

                // Add channel to application
                targetApplication.Channels.Add(channel);

                // Bind channel with endpoint and intermediaries
                if (fromStep is Endpoint endpoint)
                {
                    endpoint.OutputChannelKeyRef = channel.Key;
                }

                if (fromStep is Intermediary intermediary)
                {
                    intermediary.OutputChannelKeyRefs.Add(channel.Key);
                }

                ((Intermediary)toStep).InputChannelKeyRefs.Add(channel.Key);
            }
        }

19 View Source File : DP006ParentChildDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var resources = Model.FindAllResources();

            if (resources == null || !resources.Any())
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(DP006ParentChildDependencyreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(DP006ParentChildDependencyreplacedyzer));

                foreach (var parent in resources.Where(r => r.Resources != null && r.Resources.Count > 0))
                {
                    // Ensure the parent-child relationship exists for each resource.
                    foreach (var child in parent.Resources)
                    {
                        parent.AddRelationship(new ResourceRelationship(child.RefId, ResourceRelationshipType.Child));
                        child.AddRelationship(new ResourceRelationship(parent.RefId, ResourceRelationshipType.Parent));
                    }
                }

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(DP006ParentChildDependencyreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private SubscriptionFilter CreateSubscriptionFilter(Application targetApplication, SendPort sendPort)
        {
            _logger.LogDebug(TraceMessages.CreatingSendPortSubscription, RuleName, sendPort.Name);

            // Create an overall OR filter group so that if any sub-group matches a condition
            var targetFilterGroup = new OrFilterGroup();

            // Add default
            string defaultTargetFilterExpression;
            if (sendPort.IsStatic)
            {
                defaultTargetFilterExpression = $"{ModelConstants.BizTalkSpTransportId} = '{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}.{sendPort.PrimaryTransport.TransportType.Name}'";
            }
            else
            {
                // It's a dynamic port, so won't have a primary transport
                defaultTargetFilterExpression = $"{ModelConstants.BizTalkSpTransportId} = '{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}'";
            }

            targetFilterGroup.Groups.Add(new AndFilterGroup() { Filters = { new Filter() { FilterExpression = defaultTargetFilterExpression } } });

            // Loop around the filter groups, converting each one to an AND filter group with a list of filter expressions
            foreach (var sendPortFilterGroup in sendPort.FilterExpression.Group)
            {
                var targetFilterSubGroup = new AndFilterGroup();
                foreach (var statement in sendPortFilterGroup.Statement)
                {
                    Filter filter = null;
                    var expressionProperty = MapSubscriptionFilterProperty(statement.Property);

                    switch (statement.Operator)
                    {
                        // Equals
                        case 0:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} = '{statement.Value}'"
                            };
                            break;

                        // LessThan
                        case 1:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} < '{statement.Value}'"
                            };
                            break;

                        // LessThanEqualTo
                        case 2:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} <= '{statement.Value}'"
                            };
                            break;

                        // GreaterThan
                        case 3:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} > '{statement.Value}'"
                            };
                            break;

                        // GreaterThanEqualTo
                        case 4:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} >= '{statement.Value}'"
                            };
                            break;

                        // NotEqual
                        case 5:

                            filter = new Filter()
                            {
                                FilterExpression = $"{expressionProperty} != '{statement.Value}'"
                            };
                            break;

                        // Exists
                        case 6:

                            filter = new Filter()
                            {
                                FilterExpression = $"EXISTS ( {expressionProperty} )"
                            };
                            break;

                        default:

                            _logger.LogError(ErrorMessages.SubscriptionFilterOperatorNotSupported, statement.Operator);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.SubscriptionFilterOperatorNotSupported, statement.Operator)));

                            continue;
                    }

                    targetFilterSubGroup.Filters.Add(filter);

                    _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterStatement, RuleName, filter.FilterExpression);
                }

                _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterSubGroup, RuleName, targetFilterSubGroup.Operation, targetFilterSubGroup.Filters.Count);

                // Add to filter group
                targetFilterGroup.Groups.Add(targetFilterSubGroup);
            }

            _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterGroupForSendPort, RuleName, targetFilterGroup.Operation, sendPort.Name);

            // Create filter and return
            var subscriptionFilter = new SubscriptionFilter(targetFilterGroup);
            return subscriptionFilter;
        }

19 View Source File : AP002SendRoutingSlipGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The routing slip configuration file name is expected to be lowercase")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(AP002SendRoutingSlipGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP002SendRoutingSlipGenerator));

                // Get all of the intermediaries and endpoints from the migration target.
                var intermediaries = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Intermediaries);
                var channels = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Channels);
                var endpoints = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Endpoints);

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    // Loop through all of the activating intermediaries (that are topic subscribers).
                    foreach (var activatingIntermediary in targetApplication.Intermediaries.Where(i => i.Activator == true && i is MessageSubscriber && !string.IsNullOrEmpty(i.ResourceMapKey)))
                    {
                        // Get scenario name
                        var scenarioName = activatingIntermediary.Properties[ModelConstants.ScenarioName].ToString();

                        // Walk the routing objects starting at the activating intermediary.
                        var routingObjects = _routeWalker.WalkSendRoute(RuleName, scenarioName, activatingIntermediary, intermediaries, channels, endpoints);

                        // Get the information from the endpoints and intermediaries into one list, filtering out any intermediaries or endpoints which dont have a scenario step.
                        var configurationRoutingObjects = routingObjects.Where(r => r.RoutingObject is Intermediary)
                            .Select(r => r.RoutingObject as Intermediary)
                            .Where(i => i.Properties.ContainsKey(ModelConstants.ScenarioStepName) && i.Activator == false)
                            .Select(i => new
                            {
                                ScenarioStepName = i.Properties[ModelConstants.ScenarioStepName].ToString(),
                                Resources = i.Resources,
                            })
                            .Union(
                            routingObjects.Where(r => r.RoutingObject is Endpoint)
                            .Select(r => r.RoutingObject as Endpoint)
                            .Where(ep => ep.Properties.ContainsKey(ModelConstants.ScenarioStepName))
                            .Select(ep => new
                            {
                                ScenarioStepName = ep.Properties[ModelConstants.ScenarioStepName].ToString(),
                                Resources = ep.Resources,
                            }));

                        // Initialise the JSON routing slip config.
                        var routes = new JArray();
                        var routingSlipConfig = new JObject
                        {
                            ["routes"] = routes
                        };

                        var buildRoutingSlipConfig = true;

                        // Get all template resources in the route.
                        var routeResources = routingObjects.SelectMany(i => i.RoutingObject.Resources);

                        // Build the routes.
                        foreach (var configurationRoutingObject in configurationRoutingObjects)
                        {
                            // Find the logic app resource under the routing object.
                            var logicAppResource = FindLogicAppResource(routeResources, scenarioName, configurationRoutingObject.ScenarioStepName);

                            if (logicAppResource == null)
                            {
                                // Find the logic app resource under the application.
                                var applicationResources = targetApplication.Intermediaries.SelectMany(i => i.Resources).Union(targetApplication.Endpoints.SelectMany(e => e.Resources));
                                logicAppResource = FindLogicAppResource(applicationResources, targetApplication.Name, configurationRoutingObject.ScenarioStepName);

                                if (logicAppResource == null)
                                {
                                    // Find the logic app resource at the global level as this is a common resource.
                                    var messageBusResources = Model.FindAllTargetResourceTemplates();
                                    logicAppResource = FindLogicAppResource(messageBusResources, Model.MigrationTarget.MessageBus.Name, configurationRoutingObject.ScenarioStepName);
                                }
                            }

                            if (logicAppResource != null)
                            {
                                // Generate the routing config.
                                routes.Add(BuildRoutingSlipConfig(configurationRoutingObject.ScenarioStepName, logicAppResource));
                            }
                            else
                            {
                                // Log failure to parse the route.
                                _logger.LogDebug(TraceMessages.UnableToFindResourceWithTypeInTargetModelForScenarioStepName, RuleName, ModelConstants.ResourceTypeAzureLogicApp, configurationRoutingObject.ScenarioStepName);
                                buildRoutingSlipConfig = false;
                            }
                        }

                        if (buildRoutingSlipConfig)
                        {
                            var conversionPath = Context.ConversionFolder;

                            var appConfigResource = activatingIntermediary.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeRoutingSlip);

                            if (appConfigResource != null)
                            {
                                var fileName = $"{scenarioName}".ToLowerInvariant().Replace(" ", string.Empty); ;
                                var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(appConfigResource.OutputPath, $"{fileName}.routingslip.json")));

                                _fileRepository.WriteJsonFile(outputPath.FullName, routingSlipConfig);
                            }
                            else
                            {
                                _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, activatingIntermediary.Name);
                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, activatingIntermediary.Name)));
                            }
                        }
                        else
                        {
                            // Remove the resources to generate the routing slip as there is no valid route.
                            var routingSlipResource = activatingIntermediary.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeRoutingSlip);
                            if (routingSlipResource != null)
                            {
                                var resourceName = routingSlipResource.ResourceName;

                                var powerShellResource = activatingIntermediary.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypePowerShell && r.ResourceName == resourceName);
                                if (powerShellResource != null)
                                {
                                    activatingIntermediary.Resources.Remove(routingSlipResource);
                                    activatingIntermediary.Resources.Remove(powerShellResource);

                                    // Log.
                                    _logger.LogDebug(TraceMessages.RoutingSlipNotGeneratedForScenario, RuleName, activatingIntermediary.Properties[ModelConstants.ScenarioName]);

                                    // Add to report.
                                    activatingIntermediary.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = WarningMessages.RoutingSlipNotGeneratedForScenario });
                                }
                                else
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypePowerShell, activatingIntermediary.Name);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypePowerShell, activatingIntermediary.Name)));
                                }
                            }
                            else
                            {
                                _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, activatingIntermediary.Name);
                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, activatingIntermediary.Name)));
                            }
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(AP002SendRoutingSlipGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP001ReceiveRoutingSlipGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The routing slip configuration file name is expected to be lowercase")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(AP001ReceiveRoutingSlipGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP001ReceiveRoutingSlipGenerator));

                // Get all of the intermediaries and channels from the migration target.
                var intermediaries = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Intermediaries);
                var channels = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Channels);

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    // Loop through all of the receive endpoints and request/reply send points, which have config.
                    foreach (var initiatingEndpoint in targetApplication.Endpoints.Where(
                        ep => (ep.Activator || ep.MessageExchangePattern == ApplicationModel.Target.Endpoints.MessageExchangePattern.RequestReply)
                        && !string.IsNullOrEmpty(ep.ResourceMapKey))
                        )
                    {
                        // Get scenario name
                        var scenarioName = initiatingEndpoint.Properties[ModelConstants.ScenarioName].ToString();

                        // Walk the intermediaries starting at the receive endpoint.
                        var routingObjects = _routeWalker.WalkReceiveRoute(RuleName, scenarioName, initiatingEndpoint, intermediaries, channels);

                        // Get the messaging objects in the route which are intermediaries.
                        var routingIntermediaries = 
                            from routingObject in routingObjects
                            where routingObject.RoutingObject is Intermediary
                            select new
                            {
                                Intermediary = (Intermediary)routingObject.RoutingObject,
                                Channel = routingObject.InputChannel
                            };

                        // Filter out the intermediaries which don't have a scenario step.
                        var configurationIntermediaries = routingIntermediaries.Where(i => i.Intermediary.Properties.ContainsKey(ModelConstants.ScenarioStepName));

                        // Initialise the JSON routing slip config.
                        var routes = new JArray();
                        var routingSlipConfig = new JObject
                        {
                            ["routes"] = routes
                        };

                        // Get all template resources in the route.
                        var routeResources = routingIntermediaries.Select(i => i.Intermediary).SelectMany(i => i.Resources);

                        // Build the routes.
                        foreach (var configurationIntermediary in configurationIntermediaries)
                        {
                            var scenarioStepName = configurationIntermediary.Intermediary.Properties[ModelConstants.ScenarioStepName].ToString();

                            // Find the logic app resource in the route.
                            var logicAppResource = FindLogicAppResource(routeResources, scenarioName, scenarioStepName);

                            if (logicAppResource == null)
                            {
                                // Find the logic app resource under the application.
                                var applicationResources = targetApplication.Intermediaries.SelectMany(i => i.Resources);
                                logicAppResource = FindLogicAppResource(applicationResources, targetApplication.Name, scenarioStepName);

                                if (logicAppResource == null)
                                {
                                    // Find the logic app resource at the global level as this is a common resource.
                                    var messageBusResources = Model.FindAllTargetResourceTemplates();
                                    logicAppResource = FindLogicAppResource(messageBusResources, Model.MigrationTarget.MessageBus.Name, scenarioStepName);
                                }
                            }

                            if (logicAppResource != null)
                            {
                                // Generate the routing config.
                                routes.Add(BuildRoutingSlipConfig(scenarioStepName, logicAppResource));
                            }
                            else
                            {
                                _logger.LogError(ErrorMessages.UnableToFindResourceWithTypeInTargetModelForScenarioStepName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName);
                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceWithTypeInTargetModelForScenarioStepName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName)));
                            }
                        }

                        var conversionPath = Context.ConversionFolder;

                        var appConfigResource = initiatingEndpoint.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeRoutingSlip);

                        if (appConfigResource != null)
                        {
                            var fileName = $"{scenarioName}".ToLowerInvariant().Replace(" ", string.Empty); ;
                            var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(appConfigResource.OutputPath, $"{fileName}.routingslip.json")));

                            _fileRepository.WriteJsonFile(outputPath.FullName, routingSlipConfig);
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, initiatingEndpoint.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, initiatingEndpoint.Name)));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(AP001ReceiveRoutingSlipGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : SP001FtpSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

private void MapAdapterProperties(Dictionary<string, string> configItems, AdapterEndpoint endpoint)
        {
            // Set supported property names and defaults
            var supportedProperties = new Dictionary<string, (string, object)>()
            {
                { "serverAddress", ("serverAddress", "localhost") },
                { "serverPort", ("serverPort", 21) },
                { "userName", ("userName", "temp.user") },
                { "representationType", ("isBinaryTransport", true) },
                { "useSsl", ("isSSL", false) },
                { "targetFolder", ("targetFolder", "/") },
                { "targetFileName", ("targetFileName", "%MessageID%.xml") }
            };

            // Search through BizTalk adapter properties and match properties
            foreach (var supportedProperty in supportedProperties)
            {
                (string mappedName, object mappedValue) mappedProperty = supportedProperty.Value;

                if (configItems.ContainsKey(supportedProperty.Key) && !string.IsNullOrEmpty(configItems[supportedProperty.Key]))
                {
                    // Convert values
                    var convertedValue = ConvertAdapterProperty(supportedProperty.Key, configItems[supportedProperty.Key]);

                    // Set value on endpoint
                    endpoint.Properties.Add(mappedProperty.mappedName, convertedValue);

                    _logger.LogDebug(TraceMessages.BizTalkFtpSendAdapterBindingPropertyFound, RuleName, supportedProperty.Key, endpoint.Name, convertedValue);

                    // Remove handled property from BizTalk adapter property list
                    configItems.Remove(supportedProperty.Key);
                }
                else
                {
                    // Set default value
                    endpoint.Properties.Add(mappedProperty.mappedName, mappedProperty.mappedValue);

                    _logger.LogDebug(TraceMessages.BizTalkFtpSendAdapterBindingPropertyNotFound, RuleName, supportedProperty.Key, endpoint.Name, mappedProperty.mappedValue);
                }
            }

            // Special case preplacedword because it is a sensitive value
            endpoint.Properties.Add("preplacedword", "");
            endpoint.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Information, Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkFtpAdapterSensitivePropertyMustBeSpecifiedLater, "preplacedword") });
            configItems.Remove("preplacedword");

            _logger.LogDebug(TraceMessages.BizTalkFtpSendAdapterBindingPropertySensitive, RuleName, "preplacedword", endpoint.Name);
        }

19 View Source File : AP003ReceiveConfigurationEntryGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The configuration entry file name is expected to be lowercase")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(AP003ReceiveConfigurationEntryGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP003ReceiveConfigurationEntryGenerator));

                // Get all of the intermediaries and channels from the migration target.
                var intermediaries = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Intermediaries);
                var channels = Model.MigrationTarget.MessageBus.Applications.SelectMany(a => a.Channels);

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    // Loop through all of the receive endpoints and request/reply send points, which have config.
                    foreach (var initiatingEndpoint in targetApplication.Endpoints.Where(
                        ep => (ep.Activator || ep.MessageExchangePattern == ApplicationModel.Target.Endpoints.MessageExchangePattern.RequestReply) 
                        && !string.IsNullOrEmpty(ep.ResourceMapKey))
                        )
                    {
                        var scenarioName = initiatingEndpoint.Properties[ModelConstants.ScenarioName].ToString();
                        var scenarioStepName = initiatingEndpoint.Properties[ModelConstants.ScenarioStepName].ToString();

                        var appConfigResource = initiatingEndpoint.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeConfigurationEntry);

                        if (appConfigResource != null)
                        {
                            // Walk the intermediaries starting at the receive endpoint.
                            var routingObjects = _routeWalker.WalkReceiveRoute(RuleName, scenarioName, initiatingEndpoint, intermediaries, channels);

                            // Get any global config from the resource.
                            var globalConfig = new JObject(
                                new JProperty("globalConfig",
                                new JObject(
                                from globalConfigSetting in appConfigResource.Parameters
                                where globalConfigSetting.Key.StartsWith(ModelConstants.ResourceTemplateParamterGlobalConfigPrefix, StringComparison.OrdinalIgnoreCase)
                                select new JProperty(
                                               globalConfigSetting.Key.Replace(ModelConstants.ResourceTemplateParamterGlobalConfigPrefix, string.Empty).Replace("_", " ").ConvertSnakeCaseToCamelCase(),
                                               globalConfigSetting.Value)
                                )));

                            // Get the configuration object.
                            var configurationObjects = from routingObject in routingObjects
                                                       where routingObject.RoutingObject.Properties.ContainsKey(ModelConstants.ScenarioStepName)
                                                       select new
                                                       {
                                                           ScenarioStepName = routingObject.RoutingObject.Properties[ModelConstants.ScenarioStepName].ToString(),
                                                           Configuration = routingObject.RoutingObject.Properties.TryGetValue(ModelConstants.ConfigurationEntry, out var value) ? value as Dictionary<string, object> : new Dictionary<string, object>()
                                                       };

                            // Generate the JSON configuration.
                            var configurationEntry = new JObject(
                                from configurationObject in configurationObjects
                                where configurationObject.Configuration != null
                                select new JProperty(configurationObject.ScenarioStepName,
                                    new JObject(
                                    from configurationProperty in configurationObject.Configuration.AsEnumerable()
                                    select new JProperty(configurationProperty.Key, configurationProperty.Value != null ? JToken.FromObject(configurationProperty.Value) : null)
                                    ))
                                );

                            // Merge in the global config.
                            configurationEntry.Merge(globalConfig, new JsonMergeSettings
                            {
                                MergeArrayHandling = MergeArrayHandling.Union
                            });

                            var conversionPath = Context.ConversionFolder;

                            var fileName = $"{initiatingEndpoint.Properties[ModelConstants.ScenarioName]}".ToLowerInvariant().Replace(" ", string.Empty); ;
                            var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(appConfigResource.OutputPath, $"{fileName}.configurationentry.json")));

                            _fileRepository.WriteJsonFile(outputPath.FullName, configurationEntry);
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeConfigurationEntry, initiatingEndpoint.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeConfigurationEntry, initiatingEndpoint.Name)));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(AP003ReceiveConfigurationEntryGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void BuildInterchangeAggregationRoute(string intermediaryKeyPrefix, ResourceItem sourceApplication, Application targetApplication, SendPort sendPort)
        {
            _logger.LogDebug(TraceMessages.BuildingNewRouteForInterchangeBatching, RuleName);

            // Find interchange queue channel
            var interchangeQueueChannelKey = $"{ModelConstants.MessageBusLeafKey}:{ModelConstants.SystemApplicationLeafKey}:{ModelConstants.InterchangeQueueLeafKey}";

            var messagingObject = Model.FindMessagingObject(interchangeQueueChannelKey);
            if (messagingObject.messagingObject != null)
            {
                _logger.LogDebug(TraceMessages.CreatingInterchangeAggregatorIntermediary, RuleName, MigrationTargetResources.InterchangeAggregatorName);

                var route = new List<MessagingObject>();

                // Create an intermediary based on the aggregator
                var aggregatorIntermediary = new Aggregator(MigrationTargetResources.InterchangeAggregatorName)
                {
                    Activator = true,
                    Description = MigrationTargetResources.InterchangeAggregatorDescription,
                    Key = $"{intermediaryKeyPrefix}:{ModelConstants.InterchangeAggregatorLeafKey}",
                    Rating = ConversionRating.NoAutomaticConversion
                };

                var scenarioName = $"{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}.{ModelConstants.InterchangeAggregatorLeafKey}";
                aggregatorIntermediary.Properties.Add(ModelConstants.ScenarioName, scenarioName);
                aggregatorIntermediary.Properties.Add(ModelConstants.ScenarioStepName, "interchangeAggregator");
                aggregatorIntermediary.Properties.Add(ModelConstants.ConfigurationEntry, new Dictionary<string, object>());
                aggregatorIntermediary.Properties.Add(ModelConstants.RoutingProperties, new Dictionary<string, object>());

                // Hook aggregator up to interchange queue
                aggregatorIntermediary.InputChannelKeyRefs.Add(interchangeQueueChannelKey);

                route.Add(aggregatorIntermediary);

                // Create the send pipeline intermediaries
                route.AddRange(CreateSendPipelineIntermediaries(intermediaryKeyPrefix, sourceApplication, sendPort.TransmitPipeline, sendPort.SendPipelineCustomConfiguration));

                // Create endpoint adapter
                route.Add(CreateSendEndpoint(intermediaryKeyPrefix, sendPort));

                // Binds the route by adding routing slip router intermediaries between the intermediaries and the endpoint in the send port
                var boundRoute = BindRoute(intermediaryKeyPrefix, targetApplication, sendPort, route);

                // Binds the channels between the message box (topic channel), intermediaries up to the endpoint (send adapter)
                BindChannels(intermediaryKeyPrefix, interchangeQueueChannelKey, targetApplication, sendPort, boundRoute);
            }
            else
            {
                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Channel, interchangeQueueChannelKey);
                _logger.LogError(error);
                Context.Errors.Add(new ErrorMessage(error));
            }
        }

19 View Source File : MA001TransformGenerator.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The folder paths are lowercased, so must use a lowercase function.")]
        protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(MA001TransformGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(MA001TransformGenerator));

                var conversionPath = Context.ConversionFolder;

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    foreach (var message in targetApplication.Messages)
                    {
                        foreach (var messageTransform in message.MessageTransforms)
                        {
                            var messageResource = Model.FindResourceByKey(messageTransform.ResourceKeyRef);

                            if (messageResource == null)
                            {
                                _logger.LogWarning(WarningMessages.ResourceNotFoundByKey, messageTransform.ResourceKeyRef);
                            }
                            else
                            {
                                var mapResourceDefinition = Model.FindResourceDefinitionByRefId(messageResource.ParentRefId);

                                if (mapResourceDefinition == null)
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindResourceDefinition, mapResourceDefinition.ParentRefId);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, mapResourceDefinition.ParentRefId)));
                                }
                                else
                                {
                                    var xmlTransformResources = message.Resources.Where(r => r.ResourceType == ModelConstants.ResourceTypeXslt);

                                    foreach (var xmlTransformResource in xmlTransformResources)
                                    {
                                        var fileName = $"{targetApplication.Name}.{messageResource.Name}".Replace(" ", string.Empty);

                                        var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(xmlTransformResource.OutputPath, $"{fileName}.xslt")));

                                        _fileRepository.WriteXmlFile(outputPath.FullName, mapResourceDefinition.ResourceContent.ToString());

                                        _logger.LogDebug(TraceMessages.SavingArtifact, outputPath.FullName);
                                    }
                                }
                            }
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(MA001TransformGenerator));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : SP002FileSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

private void MapAdapterProperties(Dictionary<string, string> configItems, AdapterEndpoint endpoint)
        {
            // Set supported property names and defaults
            var supportedProperties = new Dictionary<string, (string, object)>()
            {
                { "Address", ("rootFolder", "C:/")},
                { "FileName", ("fileName", "%MessageID%.xml") },
                { "Username", ("userName", "temp.user")},
                { "CopyMode", ("copyMode", 1) }
            };

            // Search through the BizTalk adapter properties and match properties
            foreach (var supportedProperty in supportedProperties)
            {
                (string mappedName, object mappedValue) mappedProperty = supportedProperty.Value;

                if (configItems.ContainsKey(supportedProperty.Key) && !string.IsNullOrEmpty(configItems[supportedProperty.Key]))
                {
                    // Set value on endpoint
                    endpoint.Properties.Add(mappedProperty.mappedName, configItems[supportedProperty.Key]);

                    _logger.LogDebug(TraceMessages.BizTalkFileSendAdapterBindingPropertyFound, RuleName, supportedProperty.Key, endpoint.Name, mappedProperty.mappedValue);

                    // Remove handled property from BizTalk adapter property list
                    configItems.Remove(supportedProperty.Key);
                }
                else
                {
                    // Set default value
                    endpoint.Properties.Add(mappedProperty.mappedName, mappedProperty.mappedValue);

                    _logger.LogDebug(TraceMessages.BizTalkFileSendAdapterBindingPropertyFound, RuleName, supportedProperty.Key, endpoint.Name, mappedProperty.mappedValue);
                }
            }

            // Special case preplacedword because it is a sensitive value
            endpoint.Properties.Add("preplacedword", "");
            endpoint.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Information, Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkFileAdapterSensitivePropertyMustBeSpecifiedLater, "preplacedword") });
            configItems.Remove("Preplacedword");

            _logger.LogDebug(TraceMessages.BizTalkFileSendAdapterBindingPropertySensitive, RuleName, "preplacedword", endpoint.Name);
        }

19 View Source File : SC002PropertySchemaGenerator.cs
License : MIT License
Project Creator : Azure

protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            if (Model.MigrationTarget.MessageBus?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsMigrationTargetMessageBusMissing, RuleName, nameof(SC001DoreplacedentSchemaGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(SC002PropertySchemaGenerator));

                // Find the messages in the target application.
                var applicationMessages = from application in Model.MigrationTarget?.MessageBus?.Applications
                                          from message in application.Messages
                                          where message.RoutingProperties?.Count > 0
                                          select new { Application = application, Message = message };

                var conversionPath = Context.ConversionFolder;

                foreach (var applicationMessage in applicationMessages)
                {
                    var appConfigResource = applicationMessage.Message.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeRoutingProperties);

                    if (appConfigResource != null)
                    {

                        // Get the routing properties for the schema.
                        // This logic is to handle multi-root schemas, the routing properties will be against each root element/nested type in the model, 
                        // and need to be consolidated for the configuration.
                        var routingProperties = from appMessage in applicationMessages
                                                from properties in appMessage.Message.RoutingProperties.ToList()
                                                where appMessage.Message.MessageSchema.Name == applicationMessage.Message.MessageSchema.Name
                                                select new { PropertyName = properties.Key, PropertyValue = properties.Value };

                        // Generate the config.
                        var routingConfig =
                            new JObject(
                                new JProperty("routingProperties",
                                new JArray(
                                    from routingProperty in routingProperties
                                    select new JObject(
                                        new JProperty("propertyName", routingProperty.PropertyName),
                                        new JProperty("propertyType", "xpath"),
                                        new JProperty("propertyValue", routingProperty.PropertyValue)
                                        )
                                    )
                                ));

                        var fileName = $"{applicationMessage.Application.Name}.{applicationMessage.Message.MessageSchema.Name}".Replace(" ", string.Empty);

                        var outputPath = new FileInfo(Path.Combine(conversionPath, Path.Combine(appConfigResource.OutputPath, $"{fileName}.json")));

                        _fileRepository.WriteJsonFile(outputPath.FullName, routingConfig);
                    }
                    else
                    {
                        var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingProperties, applicationMessage.Message.Name);
                        _logger.LogError(error);
                        Context.Errors.Add(new ErrorMessage(error));
                    }
                }

                _logger.LogDebug(TraceMessages.GeneratorCompleted, RuleName, nameof(SC002PropertySchemaGenerator));

            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Used as routing slip config key.")]
        private MessagingObject CreateReceiveEndpoint(string endpointKeyPrefix, ResourceItem sourceApplication, Application targetApplication, ReceivePort receivePort, ReceiveLocation receiveLocation)
#pragma warning restore CA1801
        {
            _logger.LogDebug(TraceMessages.CreatingReceiveEndpointAdapter, RuleName, receiveLocation.ReceiveLocationTransportType.Name, receiveLocation.Name);

            // Create an endpoint adapter (replacedume receive-response or receive, but some adapters may be accept which will be changed later by a specific rule)
            var endpointAdapter = new AdapterEndpoint(receiveLocation.Name, receiveLocation.ReceiveLocationTransportType.Name)
            {
                Activator = true,
                Description = receiveLocation.Description,
                Key = $"{endpointKeyPrefix}:{ModelConstants.AdapterEndpointLeafKey}",
                MessageDeliveryGuarantee = MessageDeliveryGuarantee.AtLeastOnce,
                MessageExchangePattern = receivePort.IsTwoWay ? MessageExchangePattern.ReceiveResponse : MessageExchangePattern.Receive
            };

            // TODO: Add schema references from source application

            // By default, this isn't convertible unless overridden by a specific rule
            endpointAdapter.Rating = ConversionRating.NoAutomaticConversion;

            // Set scenario and step name as properties on the endpoint
            var scenarioName = $"{targetApplication.Name.FormatKey()}.{receivePort.Name.FormatKey()}.{receiveLocation.Name.FormatKey()}";
            endpointAdapter.Properties.Add(ModelConstants.ScenarioName, scenarioName);
            endpointAdapter.Properties.Add(ModelConstants.ScenarioStepName, $"{receiveLocation.ReceiveLocationTransportType.Name.ToLowerInvariant()}ReceiveAdapter");

            // Set BizTalk specific configuration properties
            var configurationEntries = new Dictionary<string, object>()
            {
                { ModelConstants.IsTwoWay, receivePort.IsTwoWay },
                { ModelConstants.BizTalkReceivePortName, receivePort.Name },
                { ModelConstants.BizTalkReceivePortId, $"{targetApplication.Name.FormatKey()}.{receivePort.Name.FormatKey()}" },
                { ModelConstants.BizTalkInboundTransportType, receiveLocation.ReceiveLocationTransportType.Name },
                { ModelConstants.BizTalkInboundTransportLocation, receiveLocation.Address },
                { ModelConstants.FailedMessageRouting, true }
            };

            // Is it a two-way port?
            if (receivePort.IsTwoWay)
            {
                configurationEntries.Add(ModelConstants.ResponseTimeout, 20);
            }

            // Add configuration properties
            endpointAdapter.Properties.Add(ModelConstants.ConfigurationEntry, configurationEntries);

            // Set BizTalk specific routing properties
            var routingProperties = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkReceivePortName, ModelConstants.BizTalkReceivePortName },
                { ModelConstants.BizTalkReceivePortId, ModelConstants.BizTalkReceivePortId },
                { ModelConstants.BizTalkInboundTransportType, ModelConstants.BizTalkInboundTransportType },
                { ModelConstants.BizTalkInboundTransportLocation, ModelConstants.BizTalkInboundTransportLocation }
            };

            // Add routing properties
            endpointAdapter.Properties.Add(ModelConstants.RoutingProperties, routingProperties);

            // Add response topic subscription
            if (receivePort.IsTwoWay)
            {
                CreateEndpointFilter(endpointAdapter, receivePort);
            }

            return endpointAdapter;
        }

19 View Source File : TemplateRendererConverter.cs
License : MIT License
Project Creator : Azure

protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            // Ensure conversion path exists
            var conversionPath = new DirectoryInfo(Context.ConversionFolder);
            if (!_fileRepository.DoesDirectoryExist(conversionPath.FullName))
            {
                _logger.LogDebug(TraceMessages.CreatingConversionPath, conversionPath.FullName);

                _fileRepository.CreateDirectory(conversionPath.FullName);
            }

            // Get template paths
            var templatePaths = Context.TemplateFolders.Select(p => new DirectoryInfo(p));
            if (templatePaths.Any())
            {
                // Render templates
                var generatedFiles = 0;
                var messageBus = Model.MigrationTarget.MessageBus;
                if (messageBus != null)
                {
                    // Message Bus
                    generatedFiles += await GenerateFilesAsync(messageBus, templatePaths, conversionPath).ConfigureAwait(false);

                    // Applications
                    if (messageBus.Applications.Any())
                    {
                        foreach (var application in messageBus.Applications)
                        {
                            generatedFiles += await GenerateFilesAsync(application, templatePaths, conversionPath).ConfigureAwait(false);

                            // Messages
                            if (application.Messages.Any())
                            {
                                foreach (var message in application.Messages)
                                {
                                    generatedFiles += await GenerateFilesAsync(message, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Channels
                            if (application.Channels.Any())
                            {
                                foreach (var channel in application.Channels)
                                {
                                    generatedFiles += await GenerateFilesAsync(channel, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Intermediaries
                            if (application.Intermediaries.Any())
                            {
                                foreach (var intermediary in application.Intermediaries)
                                {
                                    generatedFiles += await GenerateFilesAsync(intermediary, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Endpoints
                            if (application.Endpoints.Any())
                            {
                                foreach (var endpoint in application.Endpoints)
                                {
                                    generatedFiles += await GenerateFilesAsync(endpoint, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }
                        }
                    }
                }

                if (generatedFiles == 0)
                {
                    _logger.LogInformation(InformationMessages.NoResourceTemplatesToConvert);
                }
                else
                {
                    _logger.LogInformation(InformationMessages.GeneratedResourceTemplateFiles, generatedFiles);
                }
            }
            else
            {
                _logger.LogWarning(WarningMessages.NoTemplatePathsFound);
            }
        }

19 View Source File : SP006SapSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override async Task replacedyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var parsedApplicationGroup = Model.GetSourceModel<ParsedBizTalkApplicationGroup>();
            if (parsedApplicationGroup?.Applications != null)
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(SP006SapSendPortreplacedyzer));

                foreach (var application in parsedApplicationGroup.Applications)
                {
                    var sendPorts = application.Application?.Bindings?.BindingInfo?.SendPortCollection;
                    if (sendPorts != null && sendPorts.Any())
                    {
                        foreach (var sendPort in sendPorts)
                        {
                            // We're looking either for the WCF-SAP adapter, or WCF-Custom with a binding type of "sapBinding"
                            if (sendPort?.PrimaryTransport?.TransportType?.Name == "WCF-SAP" || (sendPort?.PrimaryTransport?.TransportType?.Name == "WCF-Custom" && GetBindingType(sendPort?.PrimaryTransport?.TransportTypeData) == "sapBinding"))
                            {
                                // If we're using the sapBinding in a WCF-Custom adapter, then change the TrasportType to be WCF-SAP,
                                // as this is the transport type we key against in the resource maps
                                if (sendPort?.PrimaryTransport?.TransportType?.Name == "WCF-Custom")
                                {
                                    sendPort.PrimaryTransport.TransportType.Name = "WCF-SAP";
                                }

                                // Find adapter in target model
                                var adapterKey = $"{ModelConstants.MessageBusLeafKey}:{application.Application.Name.FormatKey()}:{sendPort.Name.FormatKey()}:{ModelConstants.AdapterEndpointLeafKey}";
                                var adapter = Model.FindMessagingObject(adapterKey);
                                if (adapter.messagingObject != null)
                                {
                                    var sapAdapter = (AdapterEndpoint)adapter.messagingObject;

                                    // Set conversion rating
                                    sapAdapter.Rating = ConversionRating.FullConversionWithFidelityLoss;

                                    // We're using a Send pattern
                                    sapAdapter.MessageExchangePattern = MessageExchangePattern.Send;

                                    // Set resource map key to hook into the configuration process
                                    var messagingObject = Model.FindMessagingObject(sapAdapter.Key);
                                    var appName = $"{messagingObject.application.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-")}";
                                    var adapterName = sapAdapter.Name.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-");
                                    sapAdapter.ResourceMapKey = $"sapSendAdapterEndpoint{appName}{adapterName}";

                                    // SAP Adapter settings are held in both the TransportTypeData and the PrimaryEndpoint Address field
                                    // Note that we don't currently support secondary endpoints.

                                    // Process TransportTypeData settings
                                    if (!string.IsNullOrEmpty(sendPort.PrimaryTransport.TransportTypeData))
                                    {
                                        var configItems = MapTransportTypeData(sendPort.PrimaryTransport.TransportTypeData);

                                        MapAdapterProperties(configItems, sapAdapter);

                                        foreach (var item in configItems)
                                        {
                                            sapAdapter.ReportMessages.Add(new ReportMessage()
                                            {
                                                Severity = MessageSeverity.Warning,
                                                Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkSapAdapterPropertyNotSupported, item.Key, item.Value)
                                            });
                                        }

                                        sapAdapter.ReportLinks.Add(replacedysisResources.SapAdapterHelpLink);
                                    }
                                    else
                                    {
                                        _logger.LogDebug(WarningMessages.SendPortTransportTypeDataNotFound, sapAdapter.Name);
                                        sapAdapter.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SendPortTransportTypeDataNotFound, sapAdapter.Name) });
                                    }

                                    // Process PrimaryEndpointAddress settings
                                    if (!string.IsNullOrEmpty(sendPort.PrimaryTransport.Address))
                                    {
                                        var configItems = MapAddressData(sendPort.PrimaryTransport.Address);

                                        MapAdapterAddressProperties(configItems, sapAdapter);

                                        foreach (var item in configItems)
                                        {
                                            sapAdapter.ReportMessages.Add(new ReportMessage()
                                            {
                                                Severity = MessageSeverity.Warning,
                                                Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkSapAdapterPropertyNotSupported, item.Key, item.Value)
                                            });
                                        }

                                        sapAdapter.ReportLinks.Add(replacedysisResources.SapAdapterHelpLink);
                                    }
                                    else
                                    {
                                        _logger.LogDebug(WarningMessages.SendPortAddressDataNotFound, sapAdapter.Name);
                                        sapAdapter.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SendPortAddressDataNotFound, sapAdapter.Name) });
                                    }
                                }
                                else
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Endpoint, adapterKey)));
                                }
                            }
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(SP006SapSendPortreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(SP006SapSendPortreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : BizTalkOrchestrationParser.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "By design as the exception messages are collated in an error object.")]
        protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(BizTalkOrchestrationParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(BizTalkOrchestrationParser));

                foreach (var application in group.Applications)
                {
                    _logger.LogDebug(TraceMessages.ParsingBizTalkOrchestrationsInApplication, application.Application.Name);

                    // Loop through all of the orchestrations.
                    foreach (var orchestration in application.Application.Orchestrations)
                    {
                        var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                        try
                        {
                            var orchestrationResourceDefinition = model.FindResourceDefinitionByKey(orchestration.ResourceDefinitionKey, ModelConstants.ResourceDefinitionOrchestration);
                            if (orchestrationResourceDefinition != null)
                            {
                                // Load metamodel
                                orchestration.Model = MetaModel.FromXml((string)orchestrationResourceDefinition.ResourceContent);

                                _logger.LogDebug(TraceMessages.ParsedBizTalkOrchestration, orchestration.FullName);

                                // Create resource for metamodel
                                var metaModelResource = new ResourceItem()
                                {
                                    Name = orchestration.Name,
                                    Key = string.Concat(orchestrationResourceDefinition.Key, ":", MetaModelConstants.MetaModelRootElement),
                                    Type = ModelConstants.ResourceMetaModel,
                                    ParentRefId = orchestrationResourceDefinition.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                orchestration.Model.Resource = metaModelResource; // Maintain pointer to resource.
                                metaModelResource.SourceObject = orchestration.Model; // Maintain backward pointer.
                                orchestrationResourceDefinition.Resources.Add(metaModelResource);

                                if (applicationResource != null)
                                {
                                    applicationResource.AddRelationship(new ResourceRelationship(metaModelResource.RefId, ResourceRelationshipType.Child));
                                    metaModelResource.AddRelationship(new ResourceRelationship(applicationResource.RefId, ResourceRelationshipType.Parent));
                                }
                                else
                                {
                                    var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceApplication, application.Application?.ApplicationDefinition?.ResourceKey);
                                    _logger.LogError(error);
                                    context.Errors.Add(new ErrorMessage(error));
                                }

                                _logger.LogTrace(TraceMessages.ResourceCreated, nameof(BizTalkOrchestrationParser), metaModelResource.Key, metaModelResource.Name, metaModelResource.Type, orchestrationResourceDefinition.Key);

                                var module = orchestration.FindModule();
                                if (module != null)
                                {
                                    var resourceName = module.FindPropertyValue(MetaModelConstants.PropertyKeyName);
                                    var resourceKey = string.Concat(metaModelResource.Key, ":", resourceName);

                                    // Create resource for module
                                    var moduleResource = new ResourceItem()
                                    {
                                        Name = resourceName,
                                        Key = resourceKey,
                                        Type = ModelConstants.ResourceModule,
                                        ParentRefId = metaModelResource.RefId,
                                        Rating = ConversionRating.NotSupported
                                    };

                                    module.Resource = moduleResource; // Maintain pointer to resource.
                                    moduleResource.SourceObject = module; // Maintain backward pointer.
                                    metaModelResource.Resources.Add(moduleResource);

                                    _logger.LogTrace(TraceMessages.ResourceCreated, nameof(BizTalkOrchestrationParser), moduleResource.Key, moduleResource.Name, moduleResource.Type, metaModelResource.Key);
                                }
                                else
                                {
                                    var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindModuleInOrchestrationModel, orchestration.ResourceContainerKey, orchestration.FullName);
                                    _logger.LogError(error);
                                    context.Errors.Add(new ErrorMessage(error));
                                }
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceDefinitionOrchestration, orchestration.ResourceDefinitionKey);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorParsingMetaModel, orchestration.Name, application.Application.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(BizTalkOrchestrationParser));
            }
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void CreateMessageSubscriberFilter(MessageSubscriber messageSubscriber, ReceivePort receivePort)
        {
            var topicChannelKey = _messageBoxChannelKey;
            var receivePortSubscriptionName = receivePort.Name.FormatKey();

            // Find topic channel to add subscriptions to
            var topicChannelObject = Model.FindMessagingObject(topicChannelKey);
            if (topicChannelObject.application != null && topicChannelObject.messagingObject != null)
            {
                var topicChannel = (TopicChannel)topicChannelObject.messagingObject;

                // Subscriptions will be created independent of subscribers so that messages can be delivered to
                // the subscriptions, meaning the subscription lifetime is not tied to the consumer.  This is a durable
                // subscription and the only ones we intend to create.
                messageSubscriber.IsDurable = true;

                // Create subscription and name it after the receive port
                var subscription = new Subscription(receivePortSubscriptionName, topicChannel.TopicName)
                {
                    IsDurable = messageSubscriber.IsDurable
                };

                _logger.LogDebug(TraceMessages.CreatingReceivePortSubscription, RuleName, receivePort.Name);

                // Create filter expression against the receive port ID
                var targetFilter = new Filter()
                {
                    FilterExpression = $"{ModelConstants.BizTalkAckReceivePortId} = '{((Dictionary<string, object>)messageSubscriber.Properties[ModelConstants.ConfigurationEntry])[ModelConstants.BizTalkAckReceivePortId]}'"
                };

                // Create a group, doesn't matter too much what the operation is as there is only one filter
                var targetFilterGroup = new OrFilterGroup();
                targetFilterGroup.Filters.Add(targetFilter);

                _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterStatement, RuleName, targetFilter.FilterExpression);

                // Create filter
                subscription.Filters.Add(new SubscriptionFilter(targetFilterGroup));

                _logger.LogTrace(TraceMessages.CreatedSubscriptionFilterGroupForReceivePort, RuleName, targetFilterGroup.Operation, receivePort.Name);

                // Add subscription to channel
                topicChannel.Subscriptions.Add(subscription);

                // Relate subscription on channel to the subscriber
                messageSubscriber.TopicSubscriptions.Add(topicChannel.TopicName, subscription.Name);
            }
            else
            {
                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Channel, topicChannelKey);
                _logger.LogError(error);
                Context.Errors.Add(new ErrorMessage(error));
            }
        }

19 View Source File : DocumentSchemaParser.cs
License : MIT License
Project Creator : Azure

protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            // Get the applications from the source model.
            var parsedApplications = model.GetSourceModel<ParsedBizTalkApplicationGroup>()?.Applications;

            if (parsedApplications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(DoreplacedentSchemaParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(DoreplacedentSchemaParser));

                // Iterate through the applications and then through the parsed schemas.
                foreach (var application in parsedApplications)
                {
                    var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                    foreach (var schema in application.Application.Schemas.Where(s => s.SchemaType == BizTalkSchemaType.Doreplacedent))
                    {
                        _logger.LogDebug(TraceMessages.ParsingBizTalkDoreplacedentSchema, schema.Name);

                        // Find resource definition
                        var resourceDefinition = model.FindResourceDefinitionByKey(schema.ResourceDefinitionKey, ModelConstants.ResourceDefinitionSchema);
                        if (resourceDefinition != null)
                        {
                            var schemaResource = new ResourceItem()
                            {
                                Name = schema.Name,
                                Description = schema.XmlNamespace,
                                Type = ModelConstants.ResourceDoreplacedentSchema,
                                Key = schema.ResourceKey,
                                ParentRefId = resourceDefinition.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            schema.Resource = schemaResource; // Maintain pointer to the resource.
                            schemaResource.SourceObject = schema; // Maintain backward pointer.
                            schemaResource.Properties.Add(ResourceItemProperties.XmlNamespaceProperty, schema.XmlNamespace);
                            schemaResource.Properties.Add(ResourceItemProperties.DotnetTypeNameProperty, schema.FullName);
                            schemaResource.Properties.Add(ResourceItemProperties.NumberOfRootNodesProperty, schema.MessageDefinitions.Count.ToString(CultureInfo.CurrentCulture));
                            schemaResource.Properties.Add(ResourceItemProperties.IsEnvelopeProperty, schema.IsEnvelope.ToString());

                            if (schema.IsEnvelope)
                            {
                                schemaResource.Properties.Add(ResourceItemProperties.BodyXPathProperty, schema.BodyXPath);
                            }

                            // Add the message definitions.
                            foreach (var messageDefinition in schema.MessageDefinitions)
                            {
                                _logger.LogDebug(TraceMessages.ParsingMessageTypeDefinition, messageDefinition.MessageType);

                                var messageDefResource = new ResourceItem()
                                {
                                    Name = messageDefinition.RootElementName,
                                    Description = messageDefinition.MessageType,
                                    Type = ModelConstants.ResourceMessageType,
                                    Key = messageDefinition.ResourceKey,
                                    ParentRefId = schemaResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                messageDefinition.Resource = messageDefResource; // Maintain pointer to the resource.
                                messageDefResource.SourceObject = messageDefinition; // Maintain backward pointer.
                                messageDefResource.Properties.Add(ResourceItemProperties.RootNodeNameProperty, messageDefinition.RootElementName);
                                messageDefResource.Properties.Add(ResourceItemProperties.XmlNamespaceProperty, messageDefinition.XmlNamespace);

                                schemaResource.Resources.Add(messageDefResource);
                            }

                            resourceDefinition.Resources.Add(schemaResource);

                            if (applicationResource != null)
                            {
                                applicationResource.AddRelationship(new ResourceRelationship(schemaResource.RefId, ResourceRelationshipType.Child));
                                schemaResource.AddRelationship(new ResourceRelationship(applicationResource.RefId, ResourceRelationshipType.Parent));
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceApplication, application.Application?.ApplicationDefinition?.ResourceKey);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            }
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceDefinitionSchema, schema.ResourceDefinitionKey);
                            context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceDefinitionSchema, schema.ResourceDefinitionKey)));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(DoreplacedentSchemaParser));
            }
        }

19 View Source File : SP006SapSendPortAnalyzer.cs
License : MIT License
Project Creator : Azure

private void MapAdapterProperties(Dictionary<string, string> configItems, AdapterEndpoint endpoint)
        {
            // Set supported property names and defaults
            var supportedProperties = new Dictionary<string, (string, object)>()
            {
                { "UserName", ("userName", "") },
                { "EnableTransaction", ("enableTransaction", false) }
            };

            // Search through BizTalk adapter properties and match properties
            foreach (var supportedProperty in supportedProperties)
            {
                (string mappedName, object mappedValue) mappedProperty = supportedProperty.Value;

                if (configItems.ContainsKey(supportedProperty.Key) && !string.IsNullOrEmpty(configItems[supportedProperty.Key]))
                {
                    // Convert values
                    var convertedValue = ConvertAdapterProperty(supportedProperty.Key, configItems[supportedProperty.Key]);

                    // Set value on endpoint
                    endpoint.Properties.Add(mappedProperty.mappedName, convertedValue);

                    _logger.LogDebug(TraceMessages.BizTalkSapSendAdapterBindingPropertyFound, RuleName, supportedProperty.Key, endpoint.Name, convertedValue);

                    // Remove handled property from BizTalk adapter property list
                    configItems.Remove(supportedProperty.Key);
                }
                else
                {
                    // Set default value
                    endpoint.Properties.Add(mappedProperty.mappedName, mappedProperty.mappedValue);

                    _logger.LogDebug(TraceMessages.BizTalkSapSendAdapterBindingPropertyNotFound, RuleName, supportedProperty.Key, endpoint.Name, mappedProperty.mappedValue);
                }
            }

            // Special case preplacedword because it is a sensitive value
            endpoint.Properties.Add("preplacedword", "");
            endpoint.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Information, Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.BizTalkSapAdapterSensitivePropertyMustBeSpecifiedLater, "preplacedword") });
            configItems.Remove("preplacedword");
            _logger.LogDebug(TraceMessages.BizTalkSapSendAdapterBindingPropertySensitive, RuleName, "preplacedword", endpoint.Name);
        }

19 View Source File : OrchestrationServiceLinkTypeParser.cs
License : MIT License
Project Creator : Azure

protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();
            if (group?.Applications != null)
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(OrchestrationServiceLinkTypeParser));

                foreach (var application in group.Applications)
                {
                    // Loop through all of the orchestrations.
                    foreach (var orchestration in application.Application.Orchestrations)
                    {
                        // Find the module for the orchestration.
                        var moduleResource = orchestration.Model?.Resource?.FindResourcesByType(ModelConstants.ResourceModule).SingleOrDefault();
                        if (moduleResource != null)
                        {
                            foreach (var serviceLinkType in orchestration.FindServiceLinkTypes())
                            {
                                var resourceName = serviceLinkType.FindPropertyValue(MetaModelConstants.PropertyKeyName);
                                var resourceKey = string.Concat(moduleResource.Key, ":", resourceName);

                                var serviceLinkTypeResource = new ResourceItem
                                {
                                    Name = resourceName,
                                    Key = resourceKey,
                                    Type = ModelConstants.ResourceServiceLinkType,
                                    ParentRefId = moduleResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                serviceLinkType.Resource = serviceLinkTypeResource; // Maintain pointer to resource.
                                serviceLinkTypeResource.SourceObject = serviceLinkType; // Maintain backward pointer.
                                moduleResource.Resources.Add(serviceLinkTypeResource);

                                _logger.LogTrace(TraceMessages.ResourceCreated, nameof(OrchestrationServiceLinkTypeParser), serviceLinkTypeResource.Key, serviceLinkTypeResource.Name, serviceLinkTypeResource.Type, moduleResource.Key);
                            }
                        }
                        else
                        {
                            var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResource, ModelConstants.ResourceModule, orchestration.ResourceDefinitionKey);
                            _logger.LogError(error);
                            context.Errors.Add(new ErrorMessage(error));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(OrchestrationServiceLinkTypeParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(OrchestrationServiceLinkTypeParser));
            }
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void replacedyzeReceivePortResponse(string intermediaryKeyPrefix, ResourceItem sourceApplication, Application targetApplication, ReceivePort receivePort, ResourceItem receiveLocation)
        {
            _logger.LogDebug(TraceMessages.ReceivePortIsTwoWay, RuleName, receivePort.Name);

            var receiveLocationSource = (ReceiveLocation)receiveLocation.SourceObject;

            // Create the message subscriber.
            var route = new List<MessagingObject>
            {
                CreateMessageSubscriberIntermediary(intermediaryKeyPrefix, targetApplication, receivePort, receiveLocation)
            };

            // If there is a pipeline
            if (receiveLocationSource.SendPipeline != null)
            {
                route.AddRange(CreateSendPipelineIntermediaries(intermediaryKeyPrefix, sourceApplication, receiveLocationSource.SendPipeline, receiveLocationSource.SendPipelineCustomConfiguration));
            }

            // Create the message agent intermediaries
            route.AddRange(CreateMessageAgentIntermediaries(intermediaryKeyPrefix, _messageBoxResponseChannelKey, receivePort.IsTwoWay, ModelConstants.CorrelationId));

            // Binds the route by adding routing slip router intermediaries between the intermediaries in the receive port
            var boundRoute = BindRoute(intermediaryKeyPrefix, targetApplication, receivePort, route);

            // Binds the channels between the endpoint and intermediaries up to the message box (topic channel)
            BindResponseChannels(intermediaryKeyPrefix, targetApplication, receivePort, boundRoute);
        }

19 View Source File : ReceivePortParser.cs
License : MIT License
Project Creator : Azure

protected override void ParseInternal(AzureIntegrationServicesModel model, MigrationContext context)
        {
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingParserAsTheSourceModelIsMissing, nameof(ReceivePortParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(ReceivePortParser));

                foreach (var application in group.Applications)
                {
                    // Defensive check
                    if (application.Application.Bindings == null)
                    {
                        _logger.LogWarning(WarningMessages.BindingInfoNotFound, application.Application.Name);
                        continue;
                    }

                    if (application.Application.Bindings.BindingInfo.ReceivePortCollection != null)
                    {
                        _logger.LogDebug(TraceMessages.ParsingBizTalkReceivePortCollectionInApplication, application.Application.Name);

                        var bindingFileDefinition = model.FindResourceDefinitionByKey(application.Application.Bindings.ResourceDefinitionKey, ModelConstants.ResourceDefinitionBindings);
                        var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                        foreach (var receivePort in application.Application.Bindings.BindingInfo.ReceivePortCollection)
                        {
                            _logger.LogDebug(TraceMessages.ParsingBizTalkReceivePort, receivePort.Name);

                            receivePort.ResourceKey = string.Concat(application.Application.Bindings.ResourceDefinitionKey, ":", receivePort.Name);

                            // Create the resource under the binding file.
                            var receivePortResource = new ResourceItem
                            {
                                Key = receivePort.ResourceKey,
                                Name = receivePort.Name,
                                Description = receivePort.Description,
                                Type = ModelConstants.ResourceReceivePort,
                                ParentRefId = bindingFileDefinition.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            receivePort.Resource = receivePortResource; // Maintain pointer to the resource.
                            receivePortResource.SourceObject = receivePort; // Maintain backward pointer.
                            bindingFileDefinition.Resources.Add(receivePortResource);
                            receivePortResource.Properties.Add(ResourceItemProperties.PortDirectionProperty, receivePort.IsTwoWay ? ResourceItemProperties.PortDirectionTwoWay : ResourceItemProperties.PortDirectionOneWay);

                            if (applicationResource != null)
                            {
                                applicationResource.AddRelationship(new ResourceRelationship(receivePortResource.RefId, ResourceRelationshipType.Child));
                                receivePortResource.AddRelationship(new ResourceRelationship(applicationResource.RefId, ResourceRelationshipType.Parent));
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceApplication, application.Application?.ApplicationDefinition?.ResourceKey);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            }

                            if (receivePort.ReceiveLocations != null)
                            {
                                foreach (var receiveLocation in receivePort.ReceiveLocations)
                                {
                                    _logger.LogDebug(TraceMessages.ParsingBizTalkReceiveLocationPipelineData, receiveLocation.Name);

                                    // Extract the send pipeline custom config.
                                    receiveLocation.SendPipelineCustomConfiguration = ParsePipelineData(application, receiveLocation.Name, receiveLocation.SendPipelineData, PipelineDirection.Send, context.Errors);

                                    // Extract the receive pipeline custom config.
                                    receiveLocation.ReceivePipelineCustomConfiguration = ParsePipelineData(application, receiveLocation.Name, receiveLocation.ReceivePipelineData, PipelineDirection.Receive, context.Errors);

                                    receiveLocation.ResourceKey = string.Concat(receivePort.Name, ":", receiveLocation.Name);

                                    // Create the resource item for the receive location.
                                    var receiveLocationResource = new ResourceItem
                                    {
                                        Key = receiveLocation.ResourceKey,
                                        Name = receiveLocation.Name,
                                        Description = receiveLocation.Description,
                                        Type = ModelConstants.ResourceReceiveLocation,
                                        ParentRefId = receivePortResource.RefId,
                                        Rating = ConversionRating.NotSupported
                                    };

                                    receiveLocation.Resource = receiveLocationResource; // Maintain pointer to the resource.
                                    receiveLocationResource.SourceObject = receiveLocation; // Maintain backward pointer.
                                    receiveLocationResource.Properties.Add(ResourceItemProperties.PortTransportTypeProperty, receiveLocation.ReceiveLocationTransportType.Name);
                                    receiveLocationResource.Properties.Add(ResourceItemProperties.ReceiveLocationAddressProperty, receiveLocation.Address);

                                    receivePortResource.Resources.Add(receiveLocationResource);
                                }
                            }
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.CompletedParser, nameof(ReceivePortParser));
            }
        }

19 View Source File : DP003OrchestrationDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

private void ResolveMessageSchemaDependencies(IList<ResourceItem> resources)
        {
            var messageDeclarations = resources.Where(r => r.Type == ModelConstants.ResourceMessageDeclaration);
            var messageTypes = resources.Where(r => r.Type == ModelConstants.ResourceMessageType && r.SourceObject != null);

            // Iterate through the message declarations and see if there is an replacedociated schema.
            foreach (var messageDeclaration in messageDeclarations)
            {
                // Check for bad references.
                if (messageDeclaration.SourceObject == null)
                {
                    _logger.LogError(ErrorMessages.SourceObjectNotFound, messageDeclaration.Name, messageDeclaration.Type);
                    var errorMessage = string.Format(CultureInfo.CurrentCulture, ErrorMessages.SourceObjectNotFound, messageDeclaration.Name, messageDeclaration.Type);
                    messageDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Error, Message = errorMessage });
                    Context.Errors.Add(new ErrorMessage(errorMessage));
                    continue;
                }

                // Check for an replacedociated message type matching the message declaration.
                var sourceObject = (Element)messageDeclaration.SourceObject;
                var schemaType = sourceObject.FindPropertyValue(MetaModelConstants.PropertyKeyType);

                if (schemaType.StartsWith("System.", StringComparison.OrdinalIgnoreCase))
                {
                    // Log as we can't lookup System types in the application.
                    _logger.LogDebug(TraceMessages.SchemaDependencyNotResolved, RuleName, schemaType);
                    messageDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Information, Message = string.Format(CultureInfo.CurrentCulture, InformationMessages.SystemSchemaDependencyFound, messageDeclaration.Key, schemaType) });
                }
                else
                {
                    var matchingMessageTypes = messageTypes.Where(m => ((MessageDefinition)m.SourceObject).FullName == schemaType);
                    if (matchingMessageTypes == null || !matchingMessageTypes.Any())
                    {
                        // Log as we can't find a matching schema.
                        _logger.LogDebug(TraceMessages.SchemaDependencyNotResolved, RuleName, schemaType);
                        messageDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SchemaReferencedByMessageDeclarationIsMissing, schemaType, messageDeclaration.Key) });
                    }
                    else if (matchingMessageTypes.Count() > 1)
                    {
                        messageDeclaration.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SchemaReferenceMultipleMatches, schemaType, messageDeclaration.Key, matchingMessageTypes.Count()) });
                    }
                    else
                    {
                        // We have a matching reference
                        var messageType = matchingMessageTypes.Single();
                        messageType.AddRelationship(new ResourceRelationship(messageDeclaration.RefId, ResourceRelationshipType.ReferencedBy));
                        messageDeclaration.AddRelationship(new ResourceRelationship(messageType.RefId, ResourceRelationshipType.ReferencesTo)); // Reference to the message declaration
                        messageDeclaration.AddRelationship(new ResourceRelationship(messageType.ParentRefId, ResourceRelationshipType.ReferencesTo)); // Reference to the schema

                        // Add a link from the schema to the message declaration.
                        var schema = resources.Where(r => r.RefId == messageType.ParentRefId).SingleOrDefault();
                        if (schema != null)
                        {
                            schema.AddRelationship(new ResourceRelationship(messageDeclaration.RefId, ResourceRelationshipType.ReferencedBy));
                        }
                    }
                }
            }
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private MessageSubscriber CreateMessageSubscriberIntermediary(string intermediaryKeyPrefix, Application targetApplication, SendPort sendPort)
        {
            _logger.LogDebug(TraceMessages.CreatingMessageSubscriberIntermediary, RuleName, MigrationTargetResources.MessageSubscriberName, sendPort.Name);

            // Format names
            var applicationName = targetApplication.Name.FormatKey();
            var sendPortName = sendPort.Name.FormatKey();

            // Create an intermediary based on the message subscriber
            var messageSubscriberIntermediary = new MessageSubscriber(sendPort.Name)
            {
                Description = MigrationTargetResources.MessageSubscriberDescription,
                Key = $"{intermediaryKeyPrefix}:{ModelConstants.MessageSubscriberLeafKey}",
                ResourceMapKey = $"topicSubscriber{applicationName.Replace(".", "-").Replace(" ", string.Empty).Replace(":", "-")}{sendPortName.Replace(".", "-").Replace("/", "-").Replace(":", "-")}",
                Rating = ConversionRating.FullConversion,
                Activator = true
            };

            // Set scenario and step name as properties on the endpoint
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ScenarioName, $"{applicationName}.{sendPortName}");
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ScenarioStepName, "messageSubscriber");

            // Set BizTalk specific configuration properties
            var configurationEntries = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkSpName, $"{sendPort.Name}" },
                { ModelConstants.BizTalkSpId, $"{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}" },
                { ModelConstants.BizTalkAckSendPortName, $"{sendPort.Name}" },
                { ModelConstants.BizTalkAckSendPortId, $"{targetApplication.Name.FormatKey()}.{sendPort.Name.FormatKey()}" }
            };

            // Add configuration properties
            messageSubscriberIntermediary.Properties.Add(ModelConstants.ConfigurationEntry, configurationEntries);

            // Set BizTalk specific routing properties
            var routingProperties = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkAckSendPortName, $"{sendPortName}" }
            };

            // Add routing properties
            messageSubscriberIntermediary.Properties.Add(ModelConstants.RoutingProperties, routingProperties);
            
            // Add subscription filter
            CreateMessageSubscriberFilter(targetApplication, messageSubscriberIntermediary, sendPort);

            return messageSubscriberIntermediary;
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "AddRange can't be added so wouldn't be consistent from a style perspective.")]
        protected override async Task replacedyzePortsAsync(ResourceItem sourceApplication, Application targetApplication, CancellationToken token)
        {
            _logger.LogDebug(TraceMessages.replacedyzingReceivePortScenarios, RuleName, sourceApplication.Name);

            var scenarios = 0;
            var applicationName = targetApplication.Name.FormatKey();

            // Find receive ports in application
            var receivePorts = sourceApplication.FindRelatedResourcesByType(Model, ResourceRelationshipType.Child, ModelConstants.ResourceReceivePort);
            foreach (var receivePort in receivePorts)
            {
                var receivePortSource = (ReceivePort)receivePort.SourceObject;
                var receivePortName = receivePort.Name.FormatKey();

                // Find receive locations in receive port
                var receiveLocations = receivePort.Resources.Where(r => r.Type == ModelConstants.ResourceReceiveLocation);
                if (receiveLocations != null && receiveLocations.Any())
                {
                    foreach (var receiveLocation in receiveLocations)
                    {
                        var receiveLocationSource = (ReceiveLocation)receiveLocation.SourceObject;
                        var receiveLocationName = receiveLocation.Name.FormatKey();

                        // Is there a pipeline?
                        if (receiveLocationSource.ReceivePipeline != null)
                        {
                            var route = new List<MessagingObject>();
                            var keyPrefix = $"{Model.MigrationTarget.MessageBus.Key}:{applicationName}:{receivePortName}:{receiveLocationName}";

                            // Create endpoint adapter
                            route.Add(CreateReceiveEndpoint(keyPrefix, sourceApplication, targetApplication, receivePortSource, receiveLocationSource));

                            // Create the intermediaries for the pipeline
                            route.AddRange(CreateReceivePipelineIntermediaries(keyPrefix, sourceApplication, receiveLocationSource.ReceivePipeline, receiveLocationSource.ReceivePipelineCustomConfiguration));

                            // If there is a map, create the intermediary
                            if (receivePortSource.Transforms != null && receivePortSource.Transforms.Any())
                            {
                                // Find map resource items
                                var transforms = receivePort.FindRelatedResourcesByType(Model, ResourceRelationshipType.ReferencesTo, ModelConstants.ResourceMap);

                                // Add to route
                                var intermediary = CreateMapIntermediary(keyPrefix, targetApplication, transforms);
                                if (intermediary != null)
                                {
                                    route.Add(intermediary);
                                }
                            }
                            else
                            {
                                _logger.LogTrace(TraceMessages.NoReceiveMapSpecifiedOnReceivePort, RuleName, receivePortSource.Name, receiveLocationSource.Name);
                            }

                            // Check the route for interchange batch handling
                            var handleBatches = route.Any(s => s.Properties.ContainsKey(ModelConstants.HandleBatches) && (bool)s.Properties[ModelConstants.HandleBatches]);
                            if (handleBatches)
                            {
                                // Need to add intermediaries for batch handling (regardless of recoverable interchange processing, all routes will
                                // go through the content based router, but if batch failures must be handled as a unit, then messages in an
                                // interchange will go via a queue used to aggregate messages back into a batch to see if the batch failed, before
                                // being split again and sent to the message box topic.
                                route.AddRange(CreateInterchangeHandlingIntermediaries(keyPrefix));
                            }

                            // Create the message agent intermediaries
                            route.AddRange(CreateMessageAgentIntermediaries(keyPrefix, _messageBoxChannelKey, false, null));

                            // Binds the route by adding routing slip router intermediaries between the intermediaries in the receive port
                            var boundRoute = BindRoute(keyPrefix, targetApplication, receivePortSource, route);

                            // Binds the channels between the endpoint and intermediaries up to the message box (topic channel)
                            BindChannels(keyPrefix, targetApplication, receivePortSource, boundRoute);

                            // Add a new route for interchange batch completion handling, if required
                            if (handleBatches)
                            {
                                // Need to add interchange aggregation for batch failure handling as an atomic unit (recoverable interchange
                                // processing = false).  If batch succeeds and the messages in the batch can be published, then it goes back through
                                // a splitter for the messages to be published individually to the message box, otherwise the aggregated message is
                                // sent to the suspend queue channel.  The aggregator is an Activator intermediary as it triggers off the interchange
                                // channel, so this is treated as its own route with routing slip.  In this instance, the content based router won't
                                // route to the content promoter and the route ends with the main scenario route before it gets to the content promoter.
                                BuildInterchangeAggregationRoute(keyPrefix, targetApplication, receivePortSource, receiveLocationSource);
                            }

                            // If port is two way, check for reverse path and add a new route if required.
                            if (receivePortSource.IsTwoWay)
                            {
                                replacedyzeReceivePortResponse(keyPrefix, sourceApplication, targetApplication, receivePortSource, receiveLocation);
                            }

                            scenarios++;
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.ReceivePipelineNotSetInReceiveLocation, receiveLocation.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.ReceivePipelineNotSetInReceiveLocation, receiveLocation.Name)));
                        }
                    }
                }
            }

            if (scenarios > 0)
            {
                _logger.LogDebug(TraceMessages.FoundReceivePortScenariosInApplication, RuleName, scenarios, sourceApplication.Name);
            }
            else
            {
                _logger.LogDebug(TraceMessages.NoReceivePortsFoundInApplication, RuleName, sourceApplication.Name);
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP003ReceivePortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void BuildInterchangeAggregationRoute(string intermediaryKeyPrefix, Application targetApplication, ReceivePort receivePort, ReceiveLocation receiveLocation)
        {
            _logger.LogDebug(TraceMessages.BuildingNewRouteForInterchangeHandling, RuleName);

            // Find interchange queue channel
            var interchangeQueueChannelKey = $"{ModelConstants.MessageBusLeafKey}:{ModelConstants.SystemApplicationLeafKey}:{ModelConstants.InterchangeQueueLeafKey}";

            var messagingObject = Model.FindMessagingObject(interchangeQueueChannelKey);
            if (messagingObject.messagingObject != null)
            {
                _logger.LogDebug(TraceMessages.CreatingInterchangeAggregatorIntermediary, RuleName, MigrationTargetResources.InterchangeAggregatorName);

                var route = new List<MessagingObject>();

                // Create an intermediary based on the aggregator
                var aggregatorIntermediary = new Aggregator(MigrationTargetResources.InterchangeAggregatorName)
                {
                    Activator = true,
                    Description = MigrationTargetResources.InterchangeAggregatorDescription,
                    Key = $"{intermediaryKeyPrefix}:{ModelConstants.InterchangeAggregatorLeafKey}",
                    Rating = ConversionRating.NoAutomaticConversion
                };

                var scenarioName = $"{targetApplication.Name.FormatKey()}.{receivePort.Name.FormatKey()}.{receiveLocation.Name.FormatKey()}.{ModelConstants.InterchangeAggregatorLeafKey}";
                aggregatorIntermediary.Properties.Add(ModelConstants.ScenarioName, scenarioName);
                aggregatorIntermediary.Properties.Add(ModelConstants.ScenarioStepName, "interchangeAggregator");
                aggregatorIntermediary.Properties.Add(ModelConstants.ConfigurationEntry, new Dictionary<string, object>());
                aggregatorIntermediary.Properties.Add(ModelConstants.RoutingProperties, new Dictionary<string, object>());

                // Hook aggregator up to interchange queue
                aggregatorIntermediary.InputChannelKeyRefs.Add(interchangeQueueChannelKey);

                route.Add(aggregatorIntermediary);

                _logger.LogDebug(TraceMessages.CreatingInterchangeSplitterIntermediary, RuleName, MigrationTargetResources.InterchangeSplitterName);

                // Create an intermediary based on the splitter
                var splitterIntermediary = new Splitter(MigrationTargetResources.InterchangeSplitterName)
                {
                    Description = MigrationTargetResources.InterchangeSplitterDescription,
                    Key = $"{intermediaryKeyPrefix}:{ModelConstants.InterchangeSplitterLeafKey}",
                    Rating = ConversionRating.NoAutomaticConversion
                };

                splitterIntermediary.Properties.Add(ModelConstants.ScenarioStepName, "interchangeSplitter");
                splitterIntermediary.Properties.Add(ModelConstants.ConfigurationEntry, new Dictionary<string, object>());
                splitterIntermediary.Properties.Add(ModelConstants.RoutingProperties, new Dictionary<string, object>());

                route.Add(splitterIntermediary);

                // Create the message agent intermediaries
                route.AddRange(CreateMessageAgentIntermediaries(intermediaryKeyPrefix, _messageBoxChannelKey, false, null));

                // Binds the route by adding routing slip router intermediaries between the intermediaries in the receive port
                var boundRoute = BindRoute(intermediaryKeyPrefix, targetApplication, receivePort, route);

                // Binds the channels between the endpoint and intermediaries up to the message box (topic channel)
                BindChannels(intermediaryKeyPrefix, targetApplication, receivePort, boundRoute);
            }
            else
            {
                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Channel, interchangeQueueChannelKey);
                _logger.LogError(error);
                Context.Errors.Add(new ErrorMessage(error));
            }
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Style", "IDE0028:Simplify collection initialization", Justification = "AddRange can't be added so wouldn't be consistent from a style perspective.")]
        protected override async Task replacedyzePortsAsync(ResourceItem sourceApplication, Application targetApplication, CancellationToken token)
        {
            _logger.LogDebug(TraceMessages.replacedyzingSendPortScenarios, RuleName, sourceApplication.Name);

            var scenarios = 0;
            var applicationName = targetApplication.Name.FormatKey();

            // TODO: Handle distribution lists

            // Find send ports in application
            var sendPorts = sourceApplication.FindRelatedResourcesByType(Model, ResourceRelationshipType.Child, ModelConstants.ResourceSendPort);
            foreach (var sendPort in sendPorts)
            {
                var sendPortSource = (SendPort)sendPort.SourceObject;
                var sendPortName = sendPort.Name.FormatKey();

                // Is there a pipeline?
                if (sendPortSource.TransmitPipeline != null)
                {
                    var route = new List<MessagingObject>();
                    var keyPrefix = $"{Model.MigrationTarget.MessageBus.Key}:{applicationName}:{sendPortName}";

                    // Create message subscriber
                    route.Add(CreateMessageSubscriberIntermediary(keyPrefix, targetApplication, sendPortSource));

                    // If there is a map, create the intermediary
                    if (sendPortSource.Transforms != null && sendPortSource.Transforms.Any())
                    {
                        // Find map resource items
                        var transforms = sendPort.FindRelatedResourcesByType(Model, ResourceRelationshipType.ReferencesTo, ModelConstants.ResourceMap);

                        // Add to route
                        var intermediary = CreateMapIntermediary(keyPrefix, targetApplication, transforms);
                        if (intermediary != null)
                        {
                            route.Add(intermediary);
                        }
                    }
                    else
                    {
                        _logger.LogTrace(TraceMessages.NoSendMapSpecifiedOnSendPort, RuleName, sendPortSource.Name);
                    }

                    // Create the intermediaries for the pipeline
                    route.AddRange(CreateSendPipelineIntermediaries(keyPrefix, sourceApplication, sendPortSource.TransmitPipeline, sendPortSource.SendPipelineCustomConfiguration));

                    // Create endpoint adapter
                    var endpointAdapter = CreateSendEndpoint(keyPrefix, sendPortSource);
                    route.Add(endpointAdapter);

                    // Binds the route by adding routing slip router intermediaries between the intermediaries and the endpoint in the send port
                    var boundRoute = BindRoute(keyPrefix, targetApplication, sendPortSource, route);

                    // Binds the channels between the message box (topic channel), intermediaries up to the endpoint (send adapter)
                    var topicChannelKey = _messageBoxChannelKey;
                    BindChannels(keyPrefix, topicChannelKey, targetApplication, sendPortSource, boundRoute);

                    // Add a new route for interchange batch completion handling, if required
                    var handleBatches = route.Any(s => s.Properties.ContainsKey(ModelConstants.HandleBatches) && (bool)s.Properties[ModelConstants.HandleBatches]);
                    if (handleBatches)
                    {
                        // Need to add interchange aggregation for individual messages that are to be sent as a batch, as would be
                        // done in an orchestration by building a batch of messages and calling send pipeline inline.  Instead, this
                        // adds an aggregator to the model which receives messages from an interchange queue and which then feeds the
                        // batch to the start of the send pipeline intermediaries.
                        BuildInterchangeAggregationRoute(keyPrefix, sourceApplication, targetApplication, sendPortSource);
                    }

                    // If port is two way, check for reverse path
                    if (sendPortSource.IsTwoWay)
                    {
                        replacedyzeSendPortResponse(keyPrefix, sourceApplication, targetApplication, sendPortSource, sendPort, endpointAdapter);
                    }

                    scenarios++;
                }
                else
                {
                    _logger.LogError(ErrorMessages.TransmitPipelineNotSetInSendPort, sendPort.Name);
                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.TransmitPipelineNotSetInSendPort, sendPort.Name)));
                }
            }

            if (scenarios > 0)
            {
                _logger.LogDebug(TraceMessages.FoundSendPortScenariosInApplication, RuleName, scenarios, sourceApplication.Name);
            }
            else
            {
                _logger.LogDebug(TraceMessages.NoSendPortsFoundInApplication, RuleName, sourceApplication.Name);
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Used as routing slip config key.")]
        private MessagingObject CreateSendEndpoint(string endpointKeyPrefix, SendPort sendPort)
        {
            AdapterEndpoint endpointAdapter;

            // Is this a static or dynamic send port (that is, has a transport been set)?
            if (sendPort.IsStatic)
            {
                _logger.LogDebug(TraceMessages.CreatingSendEndpointAdapter, RuleName, sendPort.PrimaryTransport.TransportType.Name, sendPort.Name);

                // TODO: Use primary transport only, but need to think about how to handle backup transport

                // Create an endpoint adapter (replacedume request-reply or send, but some adapters may be fire and forget which will be changed later by a specific rule)
                endpointAdapter = new AdapterEndpoint(sendPort.Name, sendPort.PrimaryTransport.TransportType.Name);

                // Set step name as a property on the endpoint
                endpointAdapter.Properties.Add(ModelConstants.ScenarioStepName, $"{sendPort.PrimaryTransport.TransportType.Name.ToLowerInvariant()}SendAdapter");
            }
            else
            {
                _logger.LogDebug(TraceMessages.CreatingDynamicSendEndpointAdapter, RuleName, sendPort.Name);

                // Create an endpoint adapter (replacedume request-reply or send, but some adapters may be fire and forget which will be changed later by a specific rule)
                endpointAdapter = new AdapterEndpoint(sendPort.Name, MigrationTargetResources.DynamicSendPortDefaultProtocol);

                // Set step name as a property on the endpoint
                endpointAdapter.Properties.Add(ModelConstants.ScenarioStepName, $"{MigrationTargetResources.DynamicSendPortDefaultProtocol.ToLowerInvariant()}SendAdapter");

                // TODO: Handle dynamic send port - need to figure out how to find the actual procotol from an orchestration
            }

            // Set common property values
            endpointAdapter.Activator = false;
            endpointAdapter.Description = sendPort.Description;
            endpointAdapter.Key = $"{endpointKeyPrefix}:{ModelConstants.AdapterEndpointLeafKey}";
            endpointAdapter.MessageDeliveryGuarantee = MessageDeliveryGuarantee.AtLeastOnce;
            endpointAdapter.MessageExchangePattern = sendPort.IsTwoWay ? MessageExchangePattern.RequestReply : MessageExchangePattern.Send;

            // Set BizTalk specific configuration properties
            var configurationEntries = new Dictionary<string, object>()
            {
                { ModelConstants.IsTwoWay, sendPort.IsTwoWay }
            };

            // Add configuration properties
            endpointAdapter.Properties.Add(ModelConstants.ConfigurationEntry, configurationEntries);

            // Set BizTalk specific routing properties
            var routingProperties = new Dictionary<string, object>()
            {
                { ModelConstants.BizTalkSpName, ModelConstants.BizTalkSpName },
                { ModelConstants.BizTalkSpId, ModelConstants.BizTalkSpId }
            };

            // Add routing properties if two-way
            if (sendPort.IsTwoWay)
            {
                // Set BizTalk specific routing properties
                routingProperties.Add(ModelConstants.BizTalkAckReceivePortName, ModelConstants.BizTalkAckReceivePortName);
                routingProperties.Add(ModelConstants.BizTalkAckReceivePortId, ModelConstants.BizTalkAckReceivePortId);
                routingProperties.Add(ModelConstants.BizTalkAckSendPortName, ModelConstants.BizTalkAckSendPortName);
                routingProperties.Add(ModelConstants.BizTalkAckSendPortId, ModelConstants.BizTalkAckSendPortId);
                routingProperties.Add(ModelConstants.BizTalkAckInboundTransportLocation, ModelConstants.BizTalkAckInboundTransportLocation);
                routingProperties.Add(ModelConstants.BizTalkAckOutboundTransportLocation, ModelConstants.BizTalkAckOutboundTransportLocation);
                routingProperties.Add(ModelConstants.BizTalkAckFailureCategory, ModelConstants.BizTalkAckFailureCategory);
                routingProperties.Add(ModelConstants.BizTalkAckFailureCode, ModelConstants.BizTalkAckFailureCode);
                routingProperties.Add(ModelConstants.BizTalkAckId, ModelConstants.BizTalkAckId);
                routingProperties.Add(ModelConstants.BizTalkAckType, ModelConstants.BizTalkAckType);
            }

            // Add routing properties
            endpointAdapter.Properties.Add(ModelConstants.RoutingProperties, routingProperties);

            // TODO: Add schema references from source application

            // By default, this isn't convertible unless overridden by a specific rule
            endpointAdapter.Rating = ConversionRating.NoAutomaticConversion;

            return endpointAdapter;
        }

19 View Source File : AP001ReceiveRoutingSlipGenerator.cs
License : MIT License
Project Creator : Azure

private TargetResourceTemplate FindLogicAppResource(IEnumerable<TargetResourceTemplate> resources, string scope, string scenarioStepName)
        {
            _logger.LogTrace(TraceMessages.FindingResourceTemplateByScenarioStepName, RuleName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);

            var templates = resources.Where(r =>
                r.ResourceType.StartsWith(ModelConstants.ResourceTypeAzureLogicApp) &&
                r.Parameters.ContainsKey(ModelConstants.ResourceTemplateParameterScenarioStepName) &&
                r.Parameters[ModelConstants.ResourceTemplateParameterScenarioStepName].ToString() == scenarioStepName);

            if (templates != null && templates.Any())
            {
                if (templates.Count() == 1)
                {
                    return templates.Single();
                }
                else
                {
                    _logger.LogDebug(TraceMessages.FoundTooManyResourceTemplatesByScenarioStepName, RuleName, templates.Count(), ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);
                }
            }
            else
            {
                _logger.LogDebug(TraceMessages.FoundNoResourceTemplateByScenarioStepName, RuleName, ModelConstants.ResourceTypeAzureLogicApp, scenarioStepName, scope);
            }

            return null;
        }

See More Examples