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

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

1651 Examples 7

19 View Source File : AppMetricsMiddlewareHealthChecksLoggerExtensions.cs
License : Apache License 2.0
Project Creator : AppMetrics

public static void MiddlewareFailed<TMiddleware>(this ILogger logger, Exception e, string message)
        {
            logger.LogError(AppMetricsEventIds.Middleware.MiddlewareErrorId, e, $"[{typeof(TMiddleware).FullName}] {message}");
        }

19 View Source File : ComponentRefreshTrigger.cs
License : Apache License 2.0
Project Creator : aspnet

private async Task RefreshAsync(OutputRefresh refresh)
        {
            // Re-evaluate project instance so we can determine compile items properly.
            var projectInstance = _projectInstanceEvaluator.Evaluate(refresh.ProjectInstance);

            foreach (var doreplacedentChangeInfo in refresh.DoreplacedentChangeInfos.Values)
            {
                try
                {
                    // Force update the OmniSharp Workspace for component declaration changes.

                    var componentDeclarationLocation = doreplacedentChangeInfo.FilePath;
                    var isCompileItem = IsCompileItem(doreplacedentChangeInfo.RelativeFilePath, projectInstance);
                    var wasACompileItem = false;
                    lock (_lastSeenCompileItems)
                    {
                        _lastSeenCompileItems.TryGetValue(doreplacedentChangeInfo.FilePath, out wasACompileItem);
                        _lastSeenCompileItems[doreplacedentChangeInfo.FilePath] = isCompileItem;
                    }

                    if (!isCompileItem && wasACompileItem)
                    {
                        // Output doreplacedent should no longer be considered as a compile item, clear the workspace content for it.
                        var request = new Request()
                        {
                            FileName = componentDeclarationLocation,
                            Buffer = string.Empty,
                        };
                        await _updateBufferDispatcher.UpdateBufferAsync(request);
                    }
                    else if (isCompileItem)
                    {
                        // Force update the OmniSharp Workspace for component declaration changes.
                        var request = new UpdateBufferRequest()
                        {
                            FileName = componentDeclarationLocation,
                            FromDisk = true,
                        };
                        await _updateBufferDispatcher.UpdateBufferAsync(request);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("Unexpected error when updating workspace representation of '" + doreplacedentChangeInfo.FilePath + "': " + ex);
                }
            }

            OnRefreshWorkCompleting();
        }

19 View Source File : BackgroundDocumentGenerator.cs
License : Apache License 2.0
Project Creator : aspnet

private async void Timer_Tick(object state)
        {
            try
            {
                _foregroundDispatcher.replacedertBackgroundThread();

                OnStartingBackgroundWork();

                KeyValuePair<string, DoreplacedentSnapshot>[] work;
                lock (_work)
                {
                    work = _work.ToArray();
                    _work.Clear();
                }

                OnBackgroundCapturedWorkload();

                for (var i = 0; i < work.Length; i++)
                {
                    var doreplacedent = work[i].Value;
                    try
                    {
                        await doreplacedent.GetGeneratedOutputAsync();
                    }
                    catch (Exception ex)
                    {
                        ReportError(ex);
                        _logger.LogError("Error when processing doreplacedent: " + doreplacedent.FilePath);
                    }
                }

                OnCompletingBackgroundWork();

                await Task.Factory.StartNew(
                    () =>
                    {
                        ReportUnsynchronizableContent(work);
                        NotifyDoreplacedentsProcessed(work);
                    },
                    CancellationToken.None,
                    TaskCreationOptions.None,
                    _foregroundDispatcher.ForegroundScheduler);

                lock (_work)
                {
                    // Resetting the timer allows another batch of work to start.
                    _timer.Dispose();
                    _timer = null;

                    // If more work came in while we were running start the worker again.
                    if (_work.Count > 0)
                    {
                        StartWorker();
                    }
                }

                OnCompletedBackgroundWork();
            }
            catch (Exception ex)
            {
                // This is something totally unexpected, let's just send it over to the workspace.
                _logger.LogError("Unexpected error processing doreplacedent: " + ex.Message);
                ReportError(ex);

                _timer?.Dispose();
                _timer = null;
            }
        }

19 View Source File : BackgroundDocumentGenerator.cs
License : Apache License 2.0
Project Creator : aspnet

private async void Timer_Tick(object state)
        {
            try
            {
                _foregroundDispatcher.replacedertBackgroundThread();

                OnStartingBackgroundWork();

                KeyValuePair<string, DoreplacedentSnapshot>[] work;
                lock (_work)
                {
                    work = _work.ToArray();
                    _work.Clear();
                }

                OnBackgroundCapturedWorkload();

                for (var i = 0; i < work.Length; i++)
                {
                    var doreplacedent = work[i].Value;
                    try
                    {
                        await doreplacedent.GetGeneratedOutputAsync();
                    }
                    catch (Exception ex)
                    {
                        ReportError(ex);
                        _logger.LogError("Error when processing doreplacedent: " + doreplacedent.FilePath);
                    }
                }

                OnCompletingBackgroundWork();

                await Task.Factory.StartNew(
                    () =>
                    {
                        ReportUnsynchronizableContent(work);
                        NotifyDoreplacedentsProcessed(work);
                    },
                    CancellationToken.None,
                    TaskCreationOptions.None,
                    _foregroundDispatcher.ForegroundScheduler);

                lock (_work)
                {
                    // Resetting the timer allows another batch of work to start.
                    _timer.Dispose();
                    _timer = null;

                    // If more work came in while we were running start the worker again.
                    if (_work.Count > 0)
                    {
                        StartWorker();
                    }
                }

                OnCompletedBackgroundWork();
            }
            catch (Exception ex)
            {
                // This is something totally unexpected, let's just send it over to the workspace.
                _logger.LogError("Unexpected error processing doreplacedent: " + ex.Message);
                ReportError(ex);

                _timer?.Dispose();
                _timer = null;
            }
        }

19 View Source File : ComponentRefreshTrigger.cs
License : Apache License 2.0
Project Creator : aspnet

public async void RazorDoreplacedentChanged(RazorFileChangeEventArgs args)
        {
            try
            {
                await RazorDoreplacedentChangedAsync(args);
            }
            catch (Exception ex)
            {
                _logger.LogError("Unexpected error when handling file " + args.FilePath + " doreplacedent changed: " + ex);
            }
        }

19 View Source File : MSBuildProjectManager.cs
License : Apache License 2.0
Project Creator : aspnet

public async void ProjectLoaded(ProjectLoadedEventArgs args)
        {
            try
            {
                await ProjectLoadedAsync(args);
            }
            catch (Exception ex)
            {
                _logger.LogError("Unexpected exception got thrown from the Razor plugin: " + ex);
            }
        }

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

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 : AP004SendPortScenarioAnalyzer.cs
License : MIT License
Project Creator : Azure

private void CreateMessageSubscriberFilter(Application targetApplication, MessageSubscriber messageSubscriber, SendPort sendPort)
        {
            var topicChannelKey = _messageBoxChannelKey;
            var sendPortSubscriptionName = sendPort.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 send port
                var subscription = new Subscription(sendPortSubscriptionName, topicChannel.TopicName)
                {
                    IsDurable = messageSubscriber.IsDurable
                };

                // Is there a subscription on the send port?
                if (sendPort.FilterExpression?.Group != null)
                {
                    // Parse the filter on the send port and create a new one for the target model
                    subscription.Filters.Add(CreateSubscriptionFilter(targetApplication, sendPort));
                }
                else
                {
                    // No filter, in these cases BizTalk will automatically set up a subscription with the
                    // property SPTransportID system property, which is used by orchestrations to automatically
                    // promote this property and replacedociated value on a message published through an orchestration
                    // send port.
                    // There are also cases where there is a Filter doreplacedent set on the property which has
                    // no groups and is empty (sendPort.FilterExpression.Groups is null).  Treat this as having
                    // no subscription.
                    subscription.Filters.Add(CreateDefaultSubscriptionFilter(targetApplication, sendPort));
                }

                // 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 : 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 : 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 : 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 : DP001SchemaDependencyAnalyzer.cs
License : MIT License
Project Creator : Azure

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

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

                // Find all doreplacedent schemas
                var schemas = parsedApplicationGroup.Applications.SelectMany(a => a.Application.Schemas).Where(s => s.SchemaType == BizTalkSchemaType.Doreplacedent);
                if (schemas != null && schemas.Any())
                {
                    foreach (var schema in schemas)
                    {
                        _logger.LogDebug(TraceMessages.replacedyzingSchemaDependencies, RuleName, schema.Name);

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

                        // Loop through the promoted properties
                        foreach (var promotedProperty in schema.PromotedProperties)
                        {
                            var foundReference = false;

                            // Find all property schemas
                            var propertySchemas = parsedApplicationGroup.Applications.SelectMany(a => a.Application.Schemas).Where(s => s.SchemaType == BizTalkSchemaType.Property);
                            if (propertySchemas != null && propertySchemas.Any())
                            {
                                foreach (var propertySchema in propertySchemas)
                                {
                                    // Defensive check
                                    if (propertySchema.Resource == null)
                                    {
                                        _logger.LogError(ErrorMessages.UnableToFindreplacedociatedResource, propertySchema.GetType(), propertySchema.Name, propertySchema.ResourceKey);
                                        Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindreplacedociatedResource, propertySchema.GetType(), propertySchema.Name, propertySchema.ResourceKey)));
                                        continue;
                                    }

                                    var contextProperty = propertySchema.ContextProperties.Where(cp => cp.FullyQualifiedName == promotedProperty.PropertyType).FirstOrDefault();
                                    if (contextProperty != null)
                                    {
                                        // Defensive check
                                        if (contextProperty.Resource == null)
                                        {
                                            _logger.LogError(ErrorMessages.UnableToFindreplacedociatedResource, contextProperty.GetType(), contextProperty.FullyQualifiedName, contextProperty.ResourceKey);
                                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindreplacedociatedResource, contextProperty.GetType(), contextProperty.FullyQualifiedName, contextProperty.ResourceKey)));
                                            continue;
                                        }

                                        // Add relationships to doreplacedent schema
                                        schema.Resource.AddRelationship(new ResourceRelationship(propertySchema.Resource.RefId, ResourceRelationshipType.ReferencesTo));

                                        _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, schema.ResourceKey, propertySchema.ResourceKey, ResourceRelationshipType.ReferencesTo);

                                        schema.Resource.AddRelationship(new ResourceRelationship(contextProperty.Resource.RefId, ResourceRelationshipType.ReferencesTo));

                                        _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, schema.ResourceKey, contextProperty.ResourceKey, ResourceRelationshipType.ReferencesTo);

                                        // Add relationships to property schema
                                        propertySchema.Resource.AddRelationship(new ResourceRelationship(schema.Resource.RefId, ResourceRelationshipType.ReferencedBy));

                                        _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, propertySchema.ResourceKey, schema.ResourceKey, ResourceRelationshipType.ReferencedBy);

                                        // Add relationships to context property
                                        contextProperty.Resource.AddRelationship(new ResourceRelationship(schema.Resource.RefId, ResourceRelationshipType.ReferencedBy));

                                        _logger.LogDebug(TraceMessages.RelationshipCreated, RuleName, contextProperty.ResourceKey, schema.ResourceKey, ResourceRelationshipType.ReferencedBy);

                                        foundReference = true;
                                    }
                                }
                            }

                            if (!foundReference)
                            {
                                // Add unresolved dependency message to schema resource
                                var warning = string.Format(CultureInfo.CurrentCulture, WarningMessages.ContextPropertyReferencedBySchemaIsMissing, promotedProperty.PropertyType, schema.FullName);
                                schema.Resource.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = warning });
                            }
                        }
                    }

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

            await Task.CompletedTask.ConfigureAwait(false);
        }

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 : 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 : 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 : 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 : AP001ReceiveRoutingSlipGenerator.cs
License : MIT License
Project Creator : Azure

private IList<(Intermediary Intermediary, Channel OutputChannel)> DiscoverIntermediariesRecursively(IEnumerable<Intermediary> intermediaries, IEnumerable<Channel> channels, string inputChannelKey)
        {
            var discoveredIntermediaries = new List<(Intermediary, Channel)>();

            var discoveredIntermediary = intermediaries.FirstOrDefault(i => i.InputChannelKeyRefs.Contains(inputChannelKey));

            // Get the channel for the intermediary.
            var discoveredChannel = channels.FirstOrDefault(c => c.Key == inputChannelKey);

            if (discoveredIntermediary != null)
            {
                // A topic channel indicates the end of the receive configuration, only continue if this is not a topic channel.
                if (!(discoveredChannel is TopicChannel))
                {
                    discoveredIntermediaries.Add((discoveredIntermediary, discoveredChannel));

                    // Loop through all of the output channels.
                    foreach (var outputChannelRef in discoveredIntermediary.OutputChannelKeyRefs)
                    {
                        discoveredIntermediaries.AddRange(DiscoverIntermediariesRecursively(intermediaries, channels, outputChannelRef));
                    }
                }
            }
            else
            {
                _logger.LogError(ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKey);
                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKey)));
            }

            return discoveredIntermediaries;
        }

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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : PropertySchemaPropertyParser.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)
        {
            // Null check
            _ = context ?? throw new ArgumentNullException(nameof(context));

            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

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

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

                    foreach (var schema in application.Application.Schemas.Where(s => s.SchemaType == BizTalkSchemaType.Property))
                    {
                        try
                        {
                            // Find resource definition
                            var resourceDefinition = model.FindResourceDefinitionByKey(schema.ResourceDefinitionKey, ModelConstants.ResourceDefinitionSchema);

                            // If the schema is empty then error and continue.
                            if (resourceDefinition == null || string.IsNullOrEmpty((string)resourceDefinition.ResourceContent))
                            {
                                var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorSchemaXmlEmpty, schema.Name, application.Application.Name);
                                context.Errors.Add(new ErrorMessage(message));
                                _logger.LogError(message);
                                continue;
                            }

                            _logger.LogDebug(TraceMessages.ParsingBizTalkPropertySchema, schema.FullName);

                            // Create the resource under the property schema's resource definition.
                            var propertySchemaResource = new ResourceItem
                            {
                                Key = schema.ResourceKey,
                                Name = schema.Name,
                                Description = schema.FullName,
                                Type = ModelConstants.ResourcePropertySchema,
                                ParentRefId = resourceDefinition.RefId,
                                Rating = ConversionRating.NotSupported
                            };

                            schema.Resource = propertySchemaResource; // Maintain pointer to the resource.
                            propertySchemaResource.SourceObject = schema; // Maintain backward pointer.
                            propertySchemaResource.Properties.Add(ResourceItemProperties.DotnetTypeNameProperty, schema.FullName);
                            propertySchemaResource.Properties.Add(ResourceItemProperties.ModuleNameProperty, schema.ModuleName);
                            resourceDefinition.Resources.Add(propertySchemaResource);

                            var xml = new XmlDoreplacedent() { XmlResolver = null };
                            using (var sReader = new StringReader((string)resourceDefinition.ResourceContent))
                            {
                                using (var reader = XmlReader.Create(sReader, new XmlReaderSettings() { XmlResolver = null }))
                                {
                                    xml.Load(reader);
                                }
                            }

                            var nodes = xml.SelectNodes(@"/*[local-name()='schema']/*[local-name()='element']");

                            foreach (XmlNode propertyNode in nodes)
                            {
                                var property = new ContextProperty()
                                {
                                    PropertyName = GetAttributeValue(propertyNode, "name"),
                                    Namespace = schema.Namespace,
                                    DataType = GetAttributeValue(propertyNode, "type")
                                };

                                property.FullyQualifiedName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", property.Namespace, property.PropertyName);
                                property.ResourceKey = schema.ResourceKey + ":" + property.PropertyName;
                                schema.ContextProperties.Add(property);

                                // Create the resource under the property schema's resource.
                                var contextPropertyResource = new ResourceItem
                                {
                                    Key = property.ResourceKey,
                                    Name = property.PropertyName,
                                    Description = property.FullyQualifiedName,
                                    Type = ModelConstants.ResourceContextProperty,
                                    ParentRefId = propertySchemaResource.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                property.Resource = contextPropertyResource; // Maintain pointer to the resource.
                                contextPropertyResource.SourceObject = property; // Maintain backward pointer.
                                contextPropertyResource.Properties.Add(ResourceItemProperties.DotnetTypeNameProperty, property.FullyQualifiedName);
                                contextPropertyResource.Properties.Add(ResourceItemProperties.ContextPropertyDataTypeProperty, property.DataType);
                                contextPropertyResource.Properties.Add(ResourceItemProperties.XmlNamespaceProperty, property.Namespace);
                                propertySchemaResource.Resources.Add(contextPropertyResource);

                                _logger.LogDebug(TraceMessages.ParsedTheBizTalkContextPropertyInSchema, property.FullyQualifiedName, schema.FullName);
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorParsingSchemaXml, schema.Name, application.Application.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }

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

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 : TransformParser.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(TransformParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(TransformParser));

                // Find all transforms in source model
                foreach (var application in group.Applications)
                {
                    var applicationResource = model.FindResourceByKey(application.Application?.ApplicationDefinition?.ResourceKey);

                    var transforms = application.Application.Transforms;
                    if (transforms != null && transforms.Any())
                    {
                        foreach (var transform in transforms)
                        {
                            // Find transform resource definition
                            var transformResourceDefinition = model.FindResourceDefinitionByKey(transform.ResourceDefinitionKey, ModelConstants.ResourceDefinitionMap);
                            if (transformResourceDefinition != null)
                            {
                                // Add transform resource to source
                                var transformResource = new ResourceItem()
                                {
                                    Name = transform.Name,
                                    Description = transform.FullName,
                                    Key = transformResourceDefinition.Key + ":map",
                                    Type = ModelConstants.ResourceMap,
                                    ParentRefId = transformResourceDefinition.RefId,
                                    Rating = ConversionRating.NotSupported
                                };

                                transform.Resource = transformResource; // Maintain pointer to the resource.
                                transformResource.SourceObject = transform; // Maintain backward pointer.
                                transformResourceDefinition.Resources.Add(transformResource);

                                if (applicationResource != null)
                                {
                                    applicationResource.AddRelationship(new ResourceRelationship(transformResource.RefId, ResourceRelationshipType.Child));
                                    transformResource.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(TransformParser), transformResource.Key, transformResource.Name, transformResource.Type, transformResourceDefinition.Key);
                            }
                            else
                            {
                                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceDefinitionMap, transform.ResourceDefinitionKey);
                                _logger.LogError(error);
                                context.Errors.Add(new ErrorMessage(error));
                            }
                        }
                    }
                }

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

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

protected override bool ValidateArgs()
        {
            var valid = true;

            // Template Directories
            _templatePaths.ForEach(p =>
            {
                var dirInfo = new DirectoryInfo(p);
                if (!dirInfo.Exists)
                {
                    _logger.LogError(ErrorMessages.TemplateDirectoryDoesNotExist, dirInfo.FullName);
                    valid = false;
                }
            });

            return valid;
        }

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

protected override bool ValidateArgs()
        {
            var valid = true;

            // MSI files
            if (_msiFiles.Count > 0)
            {
                foreach (var file in _msiFiles)
                {
                    var fileInfo = new FileInfo(file);
                    if (!fileInfo.Exists)
                    {
                        _logger.LogError(ErrorMessages.MsiFileDoesNotExist, fileInfo.FullName);
                        valid = false;
                    }
                }
            }

            // MSI directory
            if (!string.IsNullOrWhiteSpace(_msiDirectory))
            {
                var dirInfo = new DirectoryInfo(_msiDirectory);
                if (!dirInfo.Exists)
                {
                    _logger.LogError(ErrorMessages.MsiDirectoryDoesNotExist, dirInfo.FullName);
                    valid = false;
                }
            }

            // Unpack directory
            if (!string.IsNullOrWhiteSpace(_unpackDirectory))
            {
                var dirInfo = new DirectoryInfo(_unpackDirectory);
                if (!dirInfo.Exists)
                {
                    _logger.LogError(ErrorMessages.UnpackDirectoryDoesNotExist, dirInfo.FullName);
                    valid = false;
                }
            }

            return valid;
        }

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 IList<MessagingObject> CreateInterchangeHandlingIntermediaries(string intermediaryKeyPrefix)
        {
            var intermediaries = new List<MessagingObject>();

            _logger.LogDebug(TraceMessages.CreatingContentBasedRouterIntermediary, RuleName, MigrationTargetResources.ContentBasedRouterName);

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

            var messagingObject = Model.FindMessagingObject(interchangeQueueChannelKey);
            if (messagingObject.messagingObject != null)
            {
                // Create an intermediary based on the content based router
                var contentBasedRouterIntermediary = new ContentBasedRouter(MigrationTargetResources.ContentBasedRouterName)
                {
                    Description = MigrationTargetResources.ContentBasedRouterDescription,
                    Key = $"{intermediaryKeyPrefix}:{ModelConstants.ContentBasedRouterLeafKey}",
                    Rating = ConversionRating.NoAutomaticConversion
                };

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

                // Hook content based router up to interchange queue
                contentBasedRouterIntermediary.OutputChannelKeyRefs.Add(interchangeQueueChannelKey);

                intermediaries.Add(contentBasedRouterIntermediary);
            }
            else
            {
                var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindMessagingObjectWithKeyInTargetModel, MessagingObjectType.Channel, interchangeQueueChannelKey);
                _logger.LogError(error);
                Context.Errors.Add(new ErrorMessage(error));
            }

            return intermediaries;
        }

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 : SP004SftpSendPortAnalyzer.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(SP004SftpSendPortreplacedyzer));

                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 == "SFTP")
                            {
                                // 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 sftpAdapter = (AdapterEndpoint)adapter.messagingObject;

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

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

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

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

                                        MapAdapterProperties(configItems, sftpAdapter);

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

                                        sftpAdapter.ReportLinks.Add(replacedysisResources.SftpAdapterHelpLink);
                                    }
                                    else
                                    {
                                        _logger.LogDebug(WarningMessages.SendPortTransportTypeDataNotFound, sftpAdapter.Name);
                                        sftpAdapter.ReportMessages.Add(new ReportMessage() { Severity = MessageSeverity.Warning, Message = string.Format(CultureInfo.CurrentCulture, WarningMessages.SendPortTransportTypeDataNotFound, sftpAdapter.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(SP004SftpSendPortreplacedyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.SkippingRulereplacedourceModelMissing, RuleName, nameof(SP004SftpSendPortreplacedyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP004SendConfigurationEntryGenerator.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(AP004SendConfigurationEntryGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP004SendConfigurationEntryGenerator));

                // 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 activatable intermediaries (that are topic subscribers), which have config.
                    foreach (var activatingIntermediary in targetApplication.Intermediaries.Where(i => i.Activator == true && i is MessageSubscriber && !string.IsNullOrEmpty(i.ResourceMapKey)))
                    {
                        var appConfigResource = activatingIntermediary.Resources.SingleOrDefault(r => r.ResourceType == ModelConstants.ResourceTypeConfigurationEntry);

                        if (appConfigResource != null)
                        {
                            // 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 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 routing objects into one list, filtering out any routing objects which dont have a scenario step.
                            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 fileName = $"{scenarioName}".ToLowerInvariant().Replace(" ", string.Empty); ;
                            var conversionPath = Context.ConversionFolder;
                            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, activatingIntermediary.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeConfigurationEntry, activatingIntermediary.Name)));
                        }
                    }

                }

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

            await Task.CompletedTask.ConfigureAwait(false);
        }

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

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The routing properties 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(AP005SendRoutingPropertyGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP005SendRoutingPropertyGenerator));

                // Get all of the intermediaries, channels 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 the 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 don't have routing properties.
                        var scenarioStepRoutes = routingObjects.Where(r => r.RoutingObject is Intermediary)
                            .Select(r => r.RoutingObject as Intermediary)
                            .Where(i => i.Properties.ContainsKey(ModelConstants.RoutingProperties))
                            .Select(i => new
                            {
                                RoutingProperties = i.Properties[ModelConstants.RoutingProperties] as Dictionary<string, object>
                            })
                            .Union(
                            routingObjects.Where(r => r.RoutingObject is Endpoint)
                            .Select(r => r.RoutingObject as Endpoint)
                            .Where(ep => ep.Properties.ContainsKey(ModelConstants.RoutingProperties))
                            .Select(ep => new
                            {
                                RoutingProperties = ep.Properties[ModelConstants.RoutingProperties] as Dictionary<string, object>
                            }));

                        // Generate the routing property config as JSON.
                        var routingConfig =
                            new JObject(
                                new JProperty("routingProperties",
                                new JArray(
                                    from scenarioStepRoute in scenarioStepRoutes
                                    from routingProperty in scenarioStepRoute.RoutingProperties
                                    select new JObject(
                                        new JProperty("propertyName", routingProperty.Key),
                                        new JProperty("propertyType", "property"),
                                        new JProperty("propertyValue", routingProperty.Value)
                                        )
                                    )
                                ));

                        var conversionPath = Context.ConversionFolder;

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

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

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

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

            await Task.CompletedTask.ConfigureAwait(false);
        }

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

[System.Diagnostics.Codereplacedysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "The routing properties 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(AP006ReceiveRoutingPropertyGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP006ReceiveRoutingPropertyGenerator));

                // 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 the scenario name.
                        var scenarioName = initiatingEndpoint.Properties[ModelConstants.ScenarioName].ToString();

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

                        // Get the information from the endpoints and intermediaries into one list, filtering out any intermediaries or endpoints which don't have routing properties.
                        var scenarioStepRoutes = routingObjects.Where(r => r.RoutingObject is Endpoint)
                            .Select(r => r.RoutingObject as Endpoint)
                            .Where(ep => ep.Properties.ContainsKey(ModelConstants.RoutingProperties))
                            .Select(ep => new
                            {
                                RoutingProperties = ep.Properties[ModelConstants.RoutingProperties] as Dictionary<string, object>
                            })
                            .Union(
                            routingObjects.Where(r => r.RoutingObject is Intermediary)
                            .Select(r => r.RoutingObject as Intermediary)
                            .Where(i => i.Properties.ContainsKey(ModelConstants.RoutingProperties))
                            .Select(i => new
                            {
                                RoutingProperties = i.Properties[ModelConstants.RoutingProperties] as Dictionary<string, object>
                            }));

                        // Generate the routing property config as JSON.
                        var routingConfig =
                            new JObject(
                                new JProperty("routingProperties",
                                new JArray(
                                    from scenarioStepRoute in scenarioStepRoutes
                                    from routingProperty in scenarioStepRoute.RoutingProperties
                                    select new JObject(
                                        new JProperty("propertyName", routingProperty.Key),
                                        new JProperty("propertyType", "property"),
                                        new JProperty("propertyValue", routingProperty.Value)
                                        )
                                    )
                                ));

                        var conversionPath = Context.ConversionFolder;

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

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

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

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

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : AP007ProcessManagerRoutingSlipGenerator.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(AP007ProcessManagerRoutingSlipGenerator));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningGenerator, RuleName, nameof(AP007ProcessManagerRoutingSlipGenerator));

                // 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))
                        )
                    {
                        // Get scenario name.
                        var scenarioName = initiatingProcessManager.Properties[ModelConstants.ScenarioName].ToString();

                        // Walk the intermediaries starting at the activating process manager.
                        var routingObjects = _routeWalker.WalkProcessManagerRoute(RuleName, scenarioName, initiatingProcessManager, 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)
                            {
                                _logger.LogDebug(TraceMessages.BuildRoutingSlipAddRoute, scenarioStepName, logicAppResource?.ResourceName);
                                // 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 = initiatingProcessManager.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, initiatingProcessManager.Name);
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceTemplateForMessagingObject, ModelConstants.ResourceTypeRoutingSlip, initiatingProcessManager.Name)));
                        }
                    }
                }

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

            await Task.CompletedTask.ConfigureAwait(false);
        }

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

private IList<(Intermediary Intermediary, Channel OutputChannel)> DiscoverIntermediariesRecursively(IEnumerable<Intermediary> intermediaries, IEnumerable<Channel> channels, string inputChannelKey)
        {
            var discoveredIntermediaries = new List<(Intermediary, Channel)>();

            var discoveredIntermediary = intermediaries.FirstOrDefault(i => i.InputChannelKeyRefs.Contains(inputChannelKey));

            // Get the channel for the intermediary.
            var discoveredChannel = channels.FirstOrDefault(c => c.Key == inputChannelKey);

            if (discoveredIntermediary != null)
            {
                // A topic channel indicates the end of the configuration, only continue if this is not a topic channel.
                if (!(discoveredChannel is TopicChannel))
                {
                    discoveredIntermediaries.Add((discoveredIntermediary, discoveredChannel));

                    // Loop through all of the output channels.
                    foreach (var outputChannelRef in discoveredIntermediary.OutputChannelKeyRefs)
                    {
                        discoveredIntermediaries.AddRange(DiscoverIntermediariesRecursively(intermediaries, channels, outputChannelRef));
                    }
                }
            }
            else
            {
                _logger.LogError(ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKey);
                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKey)));
            }

            return discoveredIntermediaries;
        }

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

private IList<(MessagingObject RoutingObject, Channel InputChannel)> WalkReceiveRouteRecursively(string rule, string scenario, IEnumerable<Intermediary> intermediaries, IEnumerable<Channel> channels, string inputChannelKeyRef)
        {
            var discoveredIntermediaries = new List<(MessagingObject, Channel)>();

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

            // Get the channel for the intermediary.
            var discoveredChannel = channels.FirstOrDefault(c => c.Key == inputChannelKeyRef);
            if (discoveredChannel != null)
            {
                // Only follow channels that are part of the route.
                if (discoveredChannel.Properties.ContainsKey(ModelConstants.RouteLabel))
                {
                    var discoveredIntermediary = intermediaries.FirstOrDefault(i => i.InputChannelKeyRefs.Contains(inputChannelKeyRef));
                    if (discoveredIntermediary != null)
                    {
                        _logger.LogTrace(TraceMessages.FoundIntermediaryAttachedToChannel, rule, discoveredIntermediary.Name, discoveredChannel.Name);

                        discoveredIntermediaries.Add((discoveredIntermediary, discoveredChannel));

                        // Loop through all of the output channels.
                        foreach (var outputChannelRef in discoveredIntermediary.OutputChannelKeyRefs)
                        {
                            discoveredIntermediaries.AddRange(WalkReceiveRouteRecursively(rule, scenario, intermediaries, channels, outputChannelRef));
                        }
                    }
                    else
                    {
                        _logger.LogError(ErrorMessages.UnableToFindAnIntermediaryWithTheKeyInTargetModel, inputChannelKeyRef);
                        _context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindAnIntermediaryWithTheKeyInTargetModel, inputChannelKeyRef)));
                    }
                }
                else
                {
                    _logger.LogDebug(TraceMessages.IgnoringChannel, rule, discoveredChannel.Name);
                }
            }
            else
            {
                _logger.LogError(ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKeyRef);
                _context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindAChannelWithTheKeyInTargetModel, inputChannelKeyRef)));
            }

            return discoveredIntermediaries;
        }

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

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "This is by design")]
        private void DiscoverreplacedemblyContents(AzureIntegrationServicesModel model, MigrationContext context)
        {
            // Iterate through the applications and discover the contents of the replacedemblies.
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingDiscoveryAsTheSourceModelIsMissing, nameof(replacedemblyDiscoverer));
            }
            else
            { 
                foreach (var application in group.Applications)
                {
                    _logger.LogDebug(TraceMessages.DiscoveringreplacedemblyContentsInResourceContainer, application.ResourceContainerKey);

                    // Find replacedemblies replacedociated with this application
                    var replacedemblies = from msiResourceContainer in model.MigrationSource.ResourceContainers
                                     from cabResourceContainer in msiResourceContainer.ResourceContainers
                                     from replacedemblyResourceContainers in cabResourceContainer.ResourceContainers
                                     from replacedembly in application.Application.replacedemblies
                                     where replacedembly.ResourceContainerKey == replacedemblyResourceContainers.Key &&                                        
                                        replacedemblyResourceContainers.Type == ModelConstants.ResourceContainerreplacedembly
                                     select replacedemblyResourceContainers;

                    // Iterate through the replacedemblies discovered for each application.
                    foreach (var replacedembly in replacedemblies)
                    {
                        try
                        { 
                            _logger.LogDebug(TraceMessages.DiscoveringTheResourcesInreplacedemblyCointainer, replacedembly.Name);

                            // Check to ensure the replacedembly is a managed (.Net) replacedembly
                            if (IsManagedreplacedembly(replacedembly.ContainerLocation))
                            {
                                using (var replacedemblyDefinition = replacedemblyDefinition.Readreplacedembly(replacedembly.ContainerLocation))
                                {
                                    // Loads the components that are packaged into a BizTalk replacedembly, adding them to the replacedembly container.
                                    LoadSchemas(replacedemblyDefinition, application, replacedembly);
                                    LoadTransforms(replacedemblyDefinition, application, replacedembly);
                                    LoadReceivePipelines(replacedemblyDefinition, application, replacedembly);
                                    LoadSendPipelines(replacedemblyDefinition, application, replacedembly);
                                    LoadOrchestrations(replacedemblyDefinition, application, replacedembly);
                                }
                            }
                            else
                            {
                                // Log and skip
                                _logger.LogInformation(InformationMessages.UnmanagedreplacedemblyDiscovered, replacedembly.Name);
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToLoadreplacedembly, replacedembly.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }
            }
        }

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

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "This is by design")]
        private void UnpackMsiFiles(AzureIntegrationServicesModel model, MigrationContext context)
        {
            // Create new migration source object model
            var group = new ParsedBizTalkApplicationGroup();

            // Get MSI containers
            var msiContainers = model.MigrationSource.ResourceContainers.Where(c => c.Type == ModelConstants.ResourceContainerMsi).ToArray();

            foreach (var msiContainer in msiContainers)
            {
                if (_fileRepository.CheckFileExists(msiContainer.ContainerLocation))
                {
                    _logger.LogDebug(TraceMessages.UnpackingTheMsi, msiContainer.ContainerLocation);

                    try
                    {
                        // Create application in source model
                        var application = new ParsedBizTalkApplication();
                        group.Applications.Add(application);

                        // Set new working folder
                        var appWorkingFolder = Path.Combine(context.WorkingFolder, msiContainer.Name);

                        // Create a folder for the application
                        application.WorkingFolder = _fileRepository.CreateApplicationWorkingFolder(appWorkingFolder, application.Id.ToString()).FullName;

                        // Set resource container reference
                        application.ResourceContainerKey = msiContainer.Key;

                        // Extract files in MSI file
                        var msiFiles = _fileRepository.ExtractFilesInMsi(msiContainer.ContainerLocation, application.WorkingFolder);
                        foreach (var msiFile in msiFiles.Select(f => new FileInfo(f)).GroupBy(f => f.FullName).Select(f => f.First()))
                        {
                            var resourceName = Path.GetFileNameWithoutExtension(msiFile.Name);
                            var resourceKey = string.Concat(msiContainer.Name, ":", resourceName);

                            if (msiFile.Extension == MsiDiscoverer.ApplicationDefinitionFileExtension)
                            {
                                // Application definition file
                                var adfFileContents = _fileRepository.ReadAdfFile(msiFile.FullName);
                                var adfResourceDefinition = new ResourceDefinition() { Key = resourceKey, Name = resourceName, Type = ModelConstants.ResourceDefinitionApplicationDefinition, ResourceContent = adfFileContents };
                                msiContainer.ResourceDefinitions.Add(adfResourceDefinition);

                                // Set resource container and definition references
                                application.Application.ApplicationDefinition = new ApplicationDefinitionFile(msiContainer.Key, adfResourceDefinition.Key);

                                _logger.LogDebug(TraceMessages.CreatedTheApplicationResourceDefinition, application.Application.ApplicationDefinition.ResourceDefinitionKey);

                            }
                            else if (msiFile.Extension != MsiDiscoverer.CabinetFileExtension)
                            {
                                // Any other file, just add as a file resource
                                var resourceDefinition = new ResourceDefinition() { Key = resourceKey, Name = resourceName, Type = ModelConstants.ResourceDefinitionFile, ResourceContent = msiFile.FullName };
                                msiContainer.ResourceDefinitions.Add(resourceDefinition);

                                _logger.LogDebug(TraceMessages.CreatedTheResourceDefinition, resourceDefinition.Key);
                            }
                        }

                        // Get CAB files
                        var cabFiles = _fileRepository.GetCabFiles(application.WorkingFolder);
                        foreach (var cabFile in cabFiles.Select(f => new FileInfo(f)).GroupBy(f => f.FullName).Select(f => f.First()))
                        {
                            // Add resource container
                            var containerName = Path.GetFileNameWithoutExtension(cabFile.Name);
                            var containerKey = string.Concat(msiContainer.Key, ":", containerName);
                            var cabContainer = new ResourceContainer() { Key = containerKey, Name = containerName, Type = ModelConstants.ResourceContainerCab, ContainerLocation = cabFile.FullName };
                            msiContainer.ResourceContainers.Add(cabContainer);

                            // Set resource container reference
                            application.Application.ResourceContainerKeys.Add(cabContainer.Key);

                            // Now extract files in Cabinet file
                            var cabPath = Path.Combine(application.WorkingFolder, Path.GetFileNameWithoutExtension(cabFile.Name));

                            _logger.LogDebug(TraceMessages.ExtractingCabFilesFromPath, cabPath);

                            var files = _fileRepository.ExtractFilesInCab(cabFile.FullName, cabPath);
                            foreach (var file in files.Select(f => new FileInfo(f)).GroupBy(f => f.FullName).Select(f => f.First()))
                            {
                                var name = Path.GetFileNameWithoutExtension(file.Name);
                                var key = string.Concat(cabContainer.Key, ":", name);

                                if (file.Name == MsiDiscoverer.BindingFileName)
                                {
                                    // Binding file
                                    var bindingFileContents = _fileRepository.ReadBindingFile(file.FullName);
                                    var bindingResourceDefinition = new ResourceDefinition() { Key = key, Name = name, Type = ModelConstants.ResourceDefinitionBindings, ResourceContent = bindingFileContents };
                                    cabContainer.ResourceDefinitions.Add(bindingResourceDefinition);

                                    // Set resource container and definition references
                                    application.Application.Bindings = new BindingFile(cabContainer.Key, bindingResourceDefinition.Key);

                                    _logger.LogDebug(TraceMessages.DiscoveredTheBindingFile, bindingResourceDefinition.Key);
                                }
                                else if (file.Extension == MsiDiscoverer.replacedemblyFileExtension)
                                {
                                    // replacedembly file
                                    var asmContainer = new ResourceContainer() { Key = key, Name = name, Type = ModelConstants.ResourceContainerreplacedembly, ContainerLocation = file.FullName };
                                    cabContainer.ResourceContainers.Add(asmContainer);

                                    // Set resource container.
                                    application.Application.replacedemblies.Add(new replacedemblyFile(asmContainer.Key));

                                    _logger.LogDebug(TraceMessages.DiscoveredThereplacedembly, asmContainer.Key);
                                }
                                else
                                {
                                    // Any other file, just add as a file resource
                                    cabContainer.ResourceDefinitions.Add(new ResourceDefinition() { Key = key, Name = name, Type = ModelConstants.ResourceDefinitionFile, ResourceContent = file.FullName });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorProcessingMSIFile, msiContainer.ContainerLocation, ex.ToString());
                        context.Errors.Add(new ErrorMessage(message));
                        _logger.LogError(message);
                    }
                }
                else
                {
                    var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorMsiNotFound, msiContainer.ContainerLocation);
                    context.Errors.Add(new ErrorMessage(message));
                    _logger.LogError(message);
                }
            }

            model.MigrationSource.MigrationSourceModel = group;
        }

19 View Source File : ApplicationDefinitionParser.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(ApplicationDefinitionParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(ApplicationDefinitionParser));

                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.ParsingBizTalkApplicationDefinitionFileFromResourceContainer, 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 adfResourceDefinition = adf.Single();
                        var applicationDefinition = ApplicationDefinition.FromXml((string)adfResourceDefinition.ResourceContent);
                        application.Application.ApplicationDefinition.ApplicationDefinition = applicationDefinition;
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorReadingApplicationDefinition, application.Application.Name, ex.Message);
                        context.Errors.Add(new ErrorMessage(message));
                        _logger.LogError(message);
                    }
                }
                
                _logger.LogDebug(TraceMessages.CompletedParser, nameof(ApplicationDefinitionParser));
            }
        }

19 View Source File : BindingFileParser.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)
        {
            // Null check
            _ = context ?? throw new ArgumentNullException(nameof(context));

            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

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

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

                        _logger.LogDebug(TraceMessages.ParsingBizTalkBindingFileFromResourceContainer, application.Application.Bindings.ResourceContainerKey);

                        var bindingResourceDefinition = model.FindResourceDefinitionByKey(application.Application.Bindings.ResourceDefinitionKey, ModelConstants.ResourceDefinitionBindings);

                        if (bindingResourceDefinition != null)
                        {
                            var bindingInfo = BindingInfo.FromXml((string)bindingResourceDefinition.ResourceContent);
                            application.Application.Bindings.BindingInfo = bindingInfo;

                            ParseServiceBindings(bindingInfo, bindingResourceDefinition);
                        }
                        else
                        {
                            var error = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceDefinition, ModelConstants.ResourceDefinitionBindings, application.Application.Bindings.ResourceDefinitionKey);
                            _logger.LogError(error);
                            context.Errors.Add(new ErrorMessage(error));
                        }
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.ErrorReadingBindingInfo, application.Application.Name, ex.Message);
                        context.Errors.Add(new ErrorMessage(message));
                        _logger.LogError(message);
                    }
                }

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

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 : 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 : OrchestrationPortTypeParser.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(OrchestrationPortTypeParser));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningParser, nameof(OrchestrationPortTypeParser));

                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 portType in orchestration.FindPortTypes())
                            {
                                var resourceName = portType.FindPropertyValue(MetaModelConstants.PropertyKeyName);
                                var resourceKey = string.Concat(moduleResource.Key, ":", resourceName);

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

                                portType.Resource = portTypeResource; // Maintain pointer to resource.
                                portTypeResource.SourceObject = portType; // Maintain backward pointer.
                                moduleResource.Resources.Add(portTypeResource);
                                _logger.LogTrace(TraceMessages.ResourceCreated, nameof(OrchestrationPortTypeParser), portTypeResource.Key, portTypeResource.Name, portTypeResource.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(OrchestrationPortTypeParser));
            }
        }

See More Examples