コード例 #1
0
        private IItemContainer GetUnfoldParent(IProductElement element, VsTemplateType templateType)
        {
            var parentWithArtifactLink = element.Traverse(
                x => x.GetParent(),
                x => x.TryGetReference(ReferenceKindConstants.SolutionItem) != null);

            if (parentWithArtifactLink != null)
            {
                var referencedItems = SolutionArtifactLinkReference.GetResolvedReferences(parentWithArtifactLink, this.uriService);

                if (templateType == VsTemplateType.Project || templateType == VsTemplateType.ProjectGroup)
                {
                    var parentItem = referencedItems.FirstOrDefault(item => item.Kind == ItemKind.Solution || item.Kind == ItemKind.SolutionFolder);
                    if (parentItem != null)
                        return parentItem;
                }
                else if (templateType == VsTemplateType.Item)
                {
                    var parentItem = referencedItems.FirstOrDefault(item => item.Kind == ItemKind.Project || item.Kind == ItemKind.Folder);
                    if (parentItem != null)
                        return parentItem;
                }

                // Why not continue up??? For extension points it makes perfect sense!
                if (!(parentWithArtifactLink is IProduct))
                {
                    // The Traverse at the top first checks the stop condition on the source element itself, 
                    // meaning in our case that we would enter an infinite loop if were to get here again
                    // and pass ourselves up. So we travel one element up for the traversal.
                    return GetUnfoldParent(parentWithArtifactLink.GetParent(), templateType);
                }
            }

            return GetUnfoldParent(this.solution, templateType);
        }
コード例 #2
0
        /// <summary>
        /// Sets an existing <see cref="IReference"/> in the References of this element, or creates if not exist.
        /// </summary>
        public static IReference SetReference(IProductElement element, TValue value)
        {
            Guard.NotNull(() => element, element);
            Guard.NotNull(() => value, value);

            return(element.AddReference(typeIdFromKind, GetStringValue(new ElementDescriptorContext(element), value), true));
        }
コード例 #3
0
 /// <summary>
 /// Creates a new instance of the <see cref="WindowsFileImporter"/> class.
 /// </summary>
 public WindowsFileImporter(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, string targetPath)
 {
     this.solution = solution;
     this.uriService = uriService;
     this.currentElement = currentElement;
     this.targetPath = targetPath;
 }
コード例 #4
0
        /// <summary>
        /// Gets the path to the guidance document from the current element.
        /// </summary>
        /// <remarks>
        /// Returns the first artifact link with a *.doc extension of the current element.
        /// </remarks>
        public static string GetDocumentPath(ITracer tracer, IProductElement element, IUriReferenceService uriService)
        {
            // Return path of first reference
            var references = SolutionArtifactLinkReference.GetResolvedReferences(element, uriService);

            if (!references.Any())
            {
                tracer.Warn(String.Format(CultureInfo.CurrentCulture,
                                          Resources.GuidanceDocumentPathProvider_NoLinksFound, element.InstanceName));
                return(string.Empty);
            }
            else
            {
                var reference = references.FirstOrDefault(r => r.PhysicalPath.EndsWith(GuidanceDocumentExtension));
                if (reference == null)
                {
                    tracer.Warn(String.Format(CultureInfo.CurrentCulture,
                                              Resources.GuidanceDocumentPathProvider_NoDocumentLinkFound, element.InstanceName));
                    return(string.Empty);
                }
                else
                {
                    tracer.Info(String.Format(CultureInfo.CurrentCulture,
                                              Resources.GuidanceDocumentPathProvider_LinkFound, element.InstanceName, reference.PhysicalPath));
                    return(reference.PhysicalPath);
                }
            }
        }
コード例 #5
0
ファイル: Helpers.cs プロジェクト: slamj1/ServiceMatrix
        public static IComponent GetComponentFromLinkedElement(IProductElement currentElement)
        {
            IComponent component = null;

            if (currentElement.As<IComponent>() != null)
            {
                return currentElement.As<IComponent>();
            }

            var subscribedEventLink = currentElement.As<ISubscribedEventLink>();
            var processedCommandLink = currentElement.As<IProcessedCommandLink>();
            var eventLink = currentElement.As<IEventLink>();
            var commandLink = currentElement.As<ICommandLink>();

            if (subscribedEventLink != null)
            {
                component = subscribedEventLink.Parent.Parent;
            }
            else if (processedCommandLink != null)
            {
                component = processedCommandLink.Parent.Parent;
            }
            else if (eventLink != null)
            {
                component = eventLink.Parent.Parent;
            }
            else if (commandLink != null)
            {
                component = commandLink.Parent.Parent;
            }

            return component;
        }
コード例 #6
0
        public void Initialize()
        {
            this.manager = new Mock<IPatternManager>();
            this.current = Mock.Of<IProductElement>();

            this.publisher = new OnElementActivatedEvent(this.manager.Object, this.current);
        }
コード例 #7
0
ファイル: Component.cs プロジェクト: fsimonazzi/ServiceMatrix
        public void RemoveLinks(IAbstractEndpoint endpoint)
        {
            var project = endpoint.Project;

            if (project == null)
            {
                return;
            }

            // 1. Remove Links for References
            foreach (var libraryLink in this.LibraryReferences.LibraryReference)
            {
                IProductElement element = null;

                if (libraryLink.Library != null)
                {
                    if (libraryLink.Library.As <IProductElement>().References.Any(r => r.Kind == ReferenceKindConstants.ArtifactLink))
                    {
                        element = libraryLink.Library.As <IProductElement>();
                    }
                }
                else
                {
                    if (libraryLink.ServiceLibrary.As <IProductElement>().References.Any(r => r.Kind == ReferenceKindConstants.ArtifactLink))
                    {
                        element = libraryLink.ServiceLibrary.As <IProductElement>();
                    }
                }

                var suggestedPath = endpoint.CustomizationFuncs().BuildPathForComponentCode(endpoint, this.Parent.Parent, null, false);
                RemoveLinkFromProject(project, element.InstanceName + ".cs", suggestedPath);
            }
        }
コード例 #8
0
ファイル: Component.cs プロジェクト: fsimonazzi/ServiceMatrix
        public void AddLinks(IAbstractEndpoint endpoint)
        {
            var project = endpoint.Project;

            // 1. Add Links for References
            foreach (var libraryLink in this.LibraryReferences.LibraryReference)
            {
                IProductElement element = null;

                if (libraryLink.Library != null)
                {
                    if (libraryLink.Library.As <IProductElement>().References.Any(r => r.Kind == ReferenceKindConstants.ArtifactLink))
                    {
                        element = libraryLink.Library.As <IProductElement>();
                    }
                }
                else
                {
                    if (libraryLink.ServiceLibrary.As <IProductElement>().References.Any(r => r.Kind == ReferenceKindConstants.ArtifactLink))
                    {
                        element = libraryLink.ServiceLibrary.As <IProductElement>();
                    }
                }

                var suggestedPath = endpoint.CustomizationFuncs().BuildPathForComponentCode(endpoint, this.Parent.Parent, null, true);

                AddLinkToProject(project, element, suggestedPath, i => i.First());
            }
        }
コード例 #9
0
        internal void ValidateArtifactReferences(ValidationContext context, IProductElement element)
        {
            if (this.UriReferenceService == null)
            {
                return;
            }

            try
            {
                var references = SolutionArtifactLinkReference.GetReferenceValues(element);

                foreach (var reference in references)
                {
                    if (this.UriReferenceService.TryResolveUri<IItemContainer>(reference) == null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.InvariantCulture,
                                Properties.Resources.Validate_ArtifactReferenceNotFound,
                                element.InstanceName, reference.ToString(), ReflectionExtensions.DisplayName(typeof(SolutionArtifactLinkReference))),
                            Properties.Resources.Validate_ArtifactReferenceNotFoundCode,
                            element as ModelElement);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector<ArtifactReferenceValidation>.GetMethod(n => n.ValidateArtifactReferences(context, element)).Name);

                throw;
            }
        }
コード例 #10
0
ファイル: UseCase.cs プロジェクト: nanohex/ServiceMatrix
        public void RemoveRelatedElement(IProductElement element)
        {
            var command   = element.As <ICommand>();
            var @event    = element.As <IEvent>();
            var endpoint  = element.As <IAbstractEndpoint>();
            var component = element.As <IComponent>();
            var link      = this.UseCaseLinks.FirstOrDefault(l => l.LinkedElementId == element.Id);

            if (link != null)
            {
                link.Delete();
            }

            if (command != null && relatedCommands.Contains(command))
            {
                this.relatedCommands.Remove(command);
            }
            else if (@event != null && this.relatedEvents.Contains(@event))
            {
                this.relatedEvents.Remove(@event);
            }
            else if (endpoint != null && this.relatedEndpoints.Contains(endpoint))
            {
                this.relatedEndpoints.Remove(endpoint);
            }
            else if (component != null && this.relatedComponents.Contains(component))
            {
                this.relatedComponents.Remove(component);
            }
        }
コード例 #11
0
        public void Initialize()
        {
            this.manager = new Mock <IPatternManager>();
            this.current = Mock.Of <IProductElement>();

            this.publisher = new OnElementActivatedEvent(this.manager.Object, this.current);
        }
コード例 #12
0
        /// <summary>
        /// Adds the interface layer for the given instance to the dynamic binding context.
        /// </summary>
        public static void AddInterfaceLayer(this IDynamicBindingContext context, IProductElement element)
        {
            Guard.NotNull(() => context, context);
            Guard.NotNull(() => element, element);

            //TODO: If we ever allow automation to be defined on an extension point,
            // then for every pattern that implments and extension point, we must add a key to the cache for that extensionPoint.DefinitionId
            var layer = default(object);
            var key   = new ToolkitInterfaceLayerCacheKey(element, element.DefinitionId);

            if (element.Root != null &&
                element.Root.ProductState != null &&
                element.Root.ProductState.PropertyBag != null &&
                !element.Root.ProductState.PropertyBag.TryGetValue(key, out layer))
            {
                layer = GetInterfaceLayer(element);
                if (layer != null)
                {
                    element.Root.ProductState.PropertyBag[key] = layer;
                }
            }

            if (layer != null)
            {
                context.AddExportsFromInterfaces(layer);
            }
        }
コード例 #13
0
        internal static void SetValue <TInterface, TProperty>(IProductElement target, Expression <Func <TProperty> > propertyExpresion, TProperty value)
        {
            Guard.NotNull(() => target, target);
            Guard.NotNull(() => propertyExpresion, propertyExpresion);

            var member   = GetExpressionPropertyOrThrow <TProperty>(propertyExpresion);
            var property = GetInterfacePropertyOrThrow <TInterface>(member);

            var variableProperty = target.Properties.FirstOrDefault(prop => prop.DefinitionName == property.Name);

            if (variableProperty != null)
            {
                // The descriptor associated with the property will do the conversion already if supported.
                variableProperty.Value = value;
            }
            else
            {
                var elementProperty = TypeDescriptor.GetProperties(target).Find(property.Name, false);
                if (elementProperty == null)
                {
                    throw new NotSupportedException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        Resources.ToolkitInterfaceLayer_InstancePropertyNotFound,
                                                        target.GetType().Name,
                                                        property.Name));
                }

                // We don't do type conversion from element (reflection) properties as they will already be typed accesses.
                elementProperty.SetValue(target, value);
            }
        }
コード例 #14
0
        internal void ValidateGuidanceReference(ValidationContext context, IProductElement element)
        {
            try
            {
                if (this.GuidanceManager == null)
                {
                    return;
                }

                var reference = element.TryGetReference(ReferenceKindConstants.GuidanceTopic);
                if (!string.IsNullOrEmpty(reference))
                {
                    var uri = GuidanceReference.GetResolvedReferences(element, this.GuidanceManager).FirstOrDefault();
                    if (uri == null)
                    {
                        context.LogError(
                            string.Format(CultureInfo.InvariantCulture,
                                Properties.Resources.Validate_GuidanceReferenceNotFound,
                                element.InstanceName, reference, ReflectionExtensions.DisplayName(typeof(GuidanceReference))),
                            Properties.Resources.Validate_GuidanceReferenceNotFoundCode,
                            element as ModelElement);
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Properties.Resources.ValidationMethodFailed_Error,
                    Reflector<GuidanceReferenceValidation>.GetMethod(n => n.ValidateGuidanceReference(context, element)).Name);

                throw;
            }
        }
コード例 #15
0
        /// <summary>
        /// Gets a strong typed interface layer for a collection or element.
        /// </summary>
        public static TInterface As <TInterface>(this IProductElement element)
            where TInterface : class, IToolkitInterface
        {
            Guard.NotNull(() => element, element);

            var typed = element as TInterface;

            if (typed != null)
            {
                return(typed);
            }

            var product = element as IProduct;

            if (product != null)
            {
                return(GetInterfaceLayer <TInterface, IProduct>(product));
            }

            var abstractElement = element as IAbstractElement;

            if (abstractElement != null)
            {
                return(GetInterfaceLayer <TInterface, IAbstractElement>(abstractElement));
            }

            return(default(TInterface));
        }
コード例 #16
0
        internal static TProperty GetValue <TInterface, TProperty>(IProductElement target, Expression <Func <TProperty> > propertyExpresion)
        {
            Guard.NotNull(() => target, target);
            Guard.NotNull(() => propertyExpresion, propertyExpresion);

            var member   = GetExpressionPropertyOrThrow <TProperty>(propertyExpresion);
            var property = GetInterfacePropertyOrThrow <TInterface>(member);

            var variableProperty = target.Properties.FirstOrDefault(prop => prop.DefinitionName == property.Name);

            if (variableProperty != null)
            {
                var value = variableProperty.Value;
                if (value != null && !typeof(TProperty).IsAssignableFrom(value.GetType()))
                {
                    return((TProperty)property.Converter.ConvertFrom(value));
                }

                return((TProperty)value);
            }

            var elementProperty = TypeDescriptor.GetProperties(target).Find(property.Name, false);

            if (elementProperty == null)
            {
                throw new NotSupportedException(string.Format(
                                                    CultureInfo.CurrentCulture,
                                                    Resources.ToolkitInterfaceLayer_InstancePropertyNotFound,
                                                    target.GetType().Name,
                                                    property.Name));
            }

            // We don't do type conversion from element (reflection) properties as they will already be typed accesses.
            return((TProperty)elementProperty.GetValue(target));
        }
コード例 #17
0
 public UnfoldParentResolver(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, IVsTemplate template)
 {
     this.solution = solution;
     this.uriService = uriService;
     this.currentElement = currentElement;
     this.theTemplate = template;
 }
コード例 #18
0
        public static bool RenameElement(this IProductElement element, IToolkitElement toolkitElement, IUriReferenceService uriService, RefactoringManager refactoringManager)
        {
            using (new MouseCursor(System.Windows.Input.Cursors.Wait))
            {
                var renameRefactoring = toolkitElement as IRenameRefactoring;
                if (renameRefactoring != null)
                {
                    refactoringManager.RenameClass(renameRefactoring.Namespace, renameRefactoring.OriginalInstanceName, renameRefactoring.InstanceName);
                    element.RenameArtifactLinks(uriService, renameRefactoring.OriginalInstanceName, renameRefactoring.InstanceName);
                    return(true);
                }

                var renameRefactoringNamespace = toolkitElement as IRenameRefactoringNamespace;
                if (renameRefactoringNamespace != null && toolkitElement.InstanceName != "" && toolkitElement is IService)
                {
                    var service = toolkitElement as IService;
                    service.Rename(uriService, refactoringManager);

                    //MessageBox.Show("The Service renaming is almost done. Please, re-open the solution to finish with the renaming.", "Rename Service", MessageBoxButton.OK);
                    return(true);
                }

                var renameRefactoringNotSupported = toolkitElement as IRenameRefactoringNotSupported;
                if (renameRefactoringNotSupported != null && toolkitElement.InstanceName != "")
                {
                    var result = MessageBox.Show("This element doesn't support code refactoring, you will need to update your code manually. Do you want to do the renaming anyway?", "Rename element", MessageBoxButton.YesNo);
                    return(result == MessageBoxResult.Yes);
                }

                return(true);
            }
        }
コード例 #19
0
 /// <summary>
 /// Creates a new instance of the <see cref="WindowsFileImporter"/> class.
 /// </summary>
 public WindowsFileImporter(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, string targetPath)
 {
     this.solution       = solution;
     this.uriService     = uriService;
     this.currentElement = currentElement;
     this.targetPath     = targetPath;
 }
コード例 #20
0
ファイル: Helpers.cs プロジェクト: nanohex/ServiceMatrix
        public static GenerateProductCodeCommand CreateTempGenerateCodeCommand(this IProductElement element,
                                                                               IServiceProvider sp
                                                                               , string targetFileName
                                                                               , string targetPath
                                                                               , string templateUri
                                                                               , string namePrefix  = "GenerateCode"
                                                                               , string buildAction = "Compile")
        {
            var                  guid           = Guid.NewGuid();
            ISolution            solution       = sp.TryGetService <ISolution>();
            IPatternManager      patternManager = sp.TryGetService <IPatternManager>();
            IUriReferenceService uriService     = sp.TryGetService <IUriReferenceService>();
            var                  command        = new GenerateProductCodeCommand
            {
                TargetBuildAction  = buildAction,
                TargetCopyToOutput = CopyToOutput.DoNotCopy,
                Settings           = new EmptySettings {
                    Name = String.Format("{0}{1}", namePrefix, guid.ToString()), Id = guid
                },
                PatternManager  = patternManager,
                UriService      = uriService,
                Solution        = solution,
                ServiceProvider = sp,
                TargetFileName  = targetFileName,
                TargetPath      = targetPath,
                CurrentElement  = element,
                TemplateUri     = new Uri(templateUri)
            };

            return(command);
        }
コード例 #21
0
        public static string GetMessageConventions(this IProductElement endpoint)
        {
            var generatedConventions = string.Empty;

            try
            {
                var app = endpoint.Root.As <IApplication>();

                var rootNameSpace           = string.Empty;
                var applicationName         = app.InstanceName;
                var projectNameForInternal  = app.ProjectNameInternalMessages;
                var projectNameForContracts = app.ProjectNameContracts;

                var project = endpoint.As <IAbstractEndpoint>().As <IProductElement>().GetProject();
                if (project != null)
                {
                    rootNameSpace = project.Data.RootNamespace;
                }

                generatedConventions =
                    app.TargetNsbVersion == TargetNsbVersion.Version4
                    ? GetMessageConventionsV4(rootNameSpace, applicationName, projectNameForInternal, projectNameForContracts)
                    : GetMessageConventionsV5(rootNameSpace, applicationName, projectNameForInternal, projectNameForContracts);
            }
            catch (Exception ex)
            {
                //TODO: Why are we catching the exception here??
            }

            return(generatedConventions);
        }
コード例 #22
0
        private void AddDecendantsEntries(IProductElement element)
        {
            Guard.NotNull(() => element, element);

            var product = element as IProduct;

            if (product != null)
            {
                // Skip to views
                foreach (var view in product.Views)
                {
                    AddSelfEntries(view, view.DefinitionName);
                    AddDecendantElementsEntries(view, view.DefinitionName);
                }
            }
            else
            {
                var container = element as IElementContainer;
                if (container != null)
                {
                    AddDecendantElementsEntries(container, null);
                }
                else
                {
                    throw new NotImplementedException(
                              string.Format(CultureInfo.CurrentCulture, Resources.ProductElementDictionaryConverter_ErrorElementNotSupportDescendants, element));
                }
            }
        }
コード例 #23
0
        public static void RemoveArtifactLinks(this IProductElement element, IUriReferenceService uriService, ISolution solution)
        {
            using (new MouseCursor(System.Windows.Input.Cursors.Wait))
            {
                foreach (var referenceLink in element.References)
                {
                    var item = default(IItemContainer);
                    try
                    {
                        item = uriService.ResolveUri <IItemContainer>(new Uri(referenceLink.Value));
                    }
                    catch { }

                    if (item != null)
                    {
                        var physicalPath = item.PhysicalPath;

                        if (item.Kind == ItemKind.Project)
                        {
                            solution.As <Solution>().Remove(item.As <Project>());
                            System.IO.Directory.Delete(Path.GetDirectoryName(physicalPath), true);
                        }
                        else if (item.Kind == ItemKind.Item)
                        {
                            item.As <ProjectItem>().Delete();
                            System.IO.File.Delete(physicalPath);
                        }
                    }
                }
            }
        }
コード例 #24
0
ファイル: UseCase.cs プロジェクト: nanohex/ServiceMatrix
        public void InternalAddRelatedElement(IProductElement element, bool isStarting = false, bool createLink = false)
        {
            if (element != null)
            {
                var command   = element.As <ICommand>();
                var @event    = element.As <IEvent>();
                var endpoint  = element.As <IAbstractEndpoint>();
                var component = element.As <IComponent>();

                IUseCaseLink link = null;

                if (createLink)
                {
                    link = this.CreateUseCaseLink(element.Id.ToString());
                    link.LinkedElementId = element.Id;
                    if (command != null)
                    {
                        link.ElementType = "Command";
                    }
                    else if (@event != null)
                    {
                        link.ElementType = "Event";
                    }
                    else if (endpoint != null)
                    {
                        link.ElementType = "Endpoint";
                    }
                    else if (component != null)
                    {
                        link.ElementType = "Component";
                    }

                    link.StartsUseCase = isStarting;
                }

                if (command != null && !this.relatedCommands.Contains(command))
                {
                    this.relatedCommands.Add(command);
                }
                else if (@event != null && !this.relatedEvents.Contains(@event))
                {
                    this.relatedEvents.Add(@event);
                }
                else if (endpoint != null)
                {
                    if (isStarting && !this.endpointsStartingUseCases.Contains(endpoint))
                    {
                        this.endpointsStartingUseCases.Add(endpoint);
                    }
                    else if (!this.relatedEndpoints.Contains(endpoint) && !this.endpointsStartingUseCases.Contains(endpoint))
                    {
                        this.relatedEndpoints.Add(endpoint);
                    }
                }
                else if (component != null && !this.relatedComponents.Contains(component))
                {
                    this.relatedComponents.Add(component);
                }
            }
        }
コード例 #25
0
ファイル: UseCase.cs プロジェクト: nanohex/ServiceMatrix
 public void AddRelatedElement(IProductElement element)
 {
     this.EnsureRelatedElementListsExist();
     if (!this.UseCaseLinks.Any(l => l.LinkedElementId == element.Id))
     {
         this.InternalAddRelatedElement(element, false, true);
     }
 }
コード例 #26
0
        public static IEnumerable <Guid> GetResolvedReferences(IProductElement element, IUriReferenceService uriService, Func <IReference, bool> whereFilter)
        {
            Guard.NotNull(() => element, element);
            Guard.NotNull(() => uriService, uriService);
            Guard.NotNull(() => whereFilter, whereFilter);

            return(Enumerable.Empty <Guid>());
        }
コード例 #27
0
ファイル: Form1.cs プロジェクト: HaiAnhLe2910/Design-pattern
 private void AddProductToOrderList(IProductElement element)
 {
     for (int i = 0; i < numericUpDownAll.Value; i++)
     {
         //order.Add(element);
         supermarket.AddElement(element);
     }
 }
コード例 #28
0
ファイル: MenuCommand.cs プロジェクト: nanohex/ServiceMatrix
 public MenuCommand(IProductElement owner, string text, Action execute)
 {
     this.Owner   = owner;
     this.Name    = "MenuAutomation-" + Guid.NewGuid().ToString();
     this.Visible = this.Enabled = true;
     this.Text    = text;
     this.execute = execute;
 }
コード例 #29
0
ファイル: MenuCommand.cs プロジェクト: slamj1/ServiceMatrix
 public MenuCommand(IProductElement owner, string text, Action execute)
 {
     this.Owner = owner;
     this.Name = "MenuAutomation-" + Guid.NewGuid().ToString();
     this.Visible = this.Enabled = true;
     this.Text = text;
     this.execute = execute;
 }
コード例 #30
0
 /// <summary>
 /// Compares the <see cref="IProductElement.InstanceOrder"/> of two elements.
 /// </summary>
 /// <param name="x">The first element</param>
 /// <param name="y">The second element</param>
 /// <returns>A value that determines if the first element is less than, greater than or equal to the second element</returns>
 public override int Compare(IProductElement x, IProductElement y)
 {
     if (x.InstanceOrder == y.InstanceOrder) return 0;
     if (x.InstanceOrder < y.InstanceOrder)
         return -1;
     else
         return 1;
 }
コード例 #31
0
        /// <summary>
        /// Returns all the <see cref="IReference"/>s for the current element that can be converted to the given type and are not empty,
        /// for the specified filter.
        /// </summary>
        public static IEnumerable <IReference> GetReferences(IProductElement element, Func <IReference, bool> whereFilter)
        {
            Guard.NotNull(() => element, element);
            Guard.NotNull(() => whereFilter, whereFilter);

            return(element.References
                   .Where(r => r.Kind == typeIdFromKind && !string.IsNullOrEmpty(r.Value))
                   .Where(whereFilter));
        }
コード例 #32
0
        /// <summary>
        /// Returns the <see cref="IReference"/> for the current element that can be converted to the given type and match the specified value.
        /// </summary>
        public static IReference GetReference(IProductElement element, TValue value)
        {
            Guard.NotNull(() => element, element);
            Guard.NotNull(() => value, value);

            return(element.References
                   .Where(r => r.Kind == typeIdFromKind && !string.IsNullOrEmpty(r.Value))
                   .FirstOrDefault(r => r.Value.Equals(GetStringValue(new ElementDescriptorContext(element), value), StringComparison.OrdinalIgnoreCase)));
        }
コード例 #33
0
ファイル: Helpers.cs プロジェクト: nanohex/ServiceMatrix
        public static void Execute(this IProductElement product, string automation)
        {
            var command = product.AutomationExtensions.FirstOrDefault(x => x.Name == automation);

            if (command != null)
            {
                command.Execute();
            }
        }
コード例 #34
0
        /// <summary>
        /// Activates the specified element.
        /// </summary>
        public virtual void ActivateElement(IProductElement element)
        {
            Guard.NotNull(() => element, element);

            // Nothing to do here.

            // Raise the event
            this.ElementActivated(this, new ValueEventArgs <IProductElement>(element));
        }
コード例 #35
0
        private static IProductElement LocateHierarchyContext(IProductElement context, string path)
        {
            var currentContext = context;

            // Ensure we have a navigation expression up or down the hierarchy
            if (path.Contains(ResolveArtifactLinkCharacter))
            {
                var parts = path.Split(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);
                foreach (var part in parts)
                {
                    // Check if we reached the resolve character
                    if (part.StartsWith(PathResolver.ResolveArtifactLinkCharacter))
                    {
                        break;
                    }

                    // Check for a navigate up the hierarchy to a parent element
                    if (part.Equals(NavigateUpCharacters, StringComparison.Ordinal))
                    {
                        currentContext = currentContext.GetParent();

                        tracer.Verbose(
                            Resources.PathResolver_TraceLocateParentResolvingElement, part, currentContext.GetSafeInstanceName());

                        if (currentContext == null)
                        {
                            break;
                        }

                        continue;
                    }

                    // Check for a navigate to current element
                    if (part.Equals(NavigateCurrentCharacters, StringComparison.Ordinal))
                    {
                        // Ignore this part
                        continue;
                    }

                    // Check for a navigate down hierarchy to a child element
                    var childElement = GetChildElement(currentContext, part);
                    if (childElement != null)
                    {
                        currentContext = childElement;

                        tracer.Verbose(
                            Resources.PathResolver_TraceLocateParentResolvingElement, part, currentContext.GetSafeInstanceName());

                        continue;
                    }

                    break;
                }
            }

            return(currentContext);
        }
コード例 #36
0
        private static IItem FindSourceItemForElement(IProductElement element, Func <IEnumerable <IItem>, IItem> filter)
        {
            var references = ServiceProviderExtensions
                             .GetService <IUriReferenceService>(element.Product.ProductState);

            var sourceFile = filter(SolutionArtifactLinkReference.GetResolvedReferences(element, references).OfType <IItem>());

            return(sourceFile);
        }
コード例 #37
0
        private static Property CreateProperty(IProductElement element, string propertyName, string value)
        {
            var property = (Property)element.CreateProperty();

            property.Info     = Mock.Of <IPropertyInfo>(pi => pi.Name == propertyName && pi.CodeIdentifier == propertyName && pi.Type == "System.String");
            property.RawValue = value;

            return(property);
        }
コード例 #38
0
        public void Select(IProductElement element)
        {
            var selection = this.TopLevelNodes.FirstOrDefault(x => x.Data == element);

            if (selection != null)
            {
                selection.IsSelected = true;
            }
        }
コード例 #39
0
        internal void BuildDetailsForLibrary(IProductElement library, ISolutionBuilderViewModel solutionBuilderModel)
        {
            var application = library.Root.As <IApplication>();

            this.CleanDetails();

            // Components
            this.CreateComponentsForLibrary(solutionBuilderModel, application, library, 1);
        }
コード例 #40
0
        public IDictionary<string, string> ConvertToDictionary(IProductElement element)
        {
            // Add entries for this element
            AddSelfEntries(element, null);

            // Add entries for all descendant elements (down the tree)
            AddDecendantsEntries(element);

            // Add entries for alll ancestor elements (up the tree)
            AddAncestorsEntries(element);

            return this.dictionary;
        }
コード例 #41
0
        private void AddAncestorsEntries(IProductElement element)
        {
            Guard.NotNull(() => element, element);

            var product = element as IProduct;
            if (product != null)
            {
                // no parent elements
                return;
            }
            else
            {
                AddAncestorElementsEntries(element);
            }
        }
コード例 #42
0
ファイル: Helpers.cs プロジェクト: slamj1/ServiceMatrix
        public static INServiceBusMVC GetMvcEndpointFromLinkedElement(IProductElement currentElement)
        {
            var currentComponent = currentElement.As<NServiceBusStudio.IComponent>();
            var app = currentElement.Root.As<IApplication>();

            foreach (var endpoint in app.Design.Endpoints.GetMvcEndpoints())
            {
                var componentLinks = endpoint.EndpointComponents.AbstractComponentLinks;
                if (componentLinks.Select(link => link.ComponentReference.Value).Any(component => component == currentComponent))
                {
                    return endpoint;
                }
            }

            return null;
        }
コード例 #43
0
 public static IProductElementViewModel SearchInNodes(IEnumerable<IProductElementViewModel> nodesCollection, IProductElement target)
 {
     foreach (IProductElementViewModel model in nodesCollection)
     {
         if (model.Data == target)
         {
             return model;
         }
         IProductElementViewModel model2 = SearchInNodes(model.ChildNodes, target);
         if (model2 != null)
         {
             return model2;
         }
     }
     return null;
 }
コード例 #44
0
        // Initialization
        public void Initialize(IApplication app, IProductElement infrastructure, IServiceProvider serviceProvider, IPatternManager patternManager)
        {
            this.PatternManager = patternManager;
            UpdateElementsForUseCase(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);

            var handler = new EventHandler((s, e) =>
            {
                UpdateElementsForUseCase(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
            });

            // Listen for a new endpoint initialization
            // in order to add the required artifacts (typically menu items)
            app.OnInitializingEndpoint += handler;
            Command.ElementInitialized += handler;
            Event.ElementInitialized += handler;
            Component.ElementInitialized += handler;
        }
        /// <summary>
        /// Compares the string value of the first property of the two elements for equality.
        /// </summary>
        public override int Compare(IProductElement x, IProductElement y)
        {
            var value1 = string.Empty;
            var value2 = string.Empty;

            var property1 = x.Properties.FirstOrDefault();
            if (property1 != null)
            {
                value1 = property1.Value.ToString();
            }

            var property2 = y.Properties.FirstOrDefault();
            if (property2 != null)
            {
                value2 = property2.Value.ToString();
            }

            return String.Compare(value1, value2, true);
        }
コード例 #46
0
        /// <summary>
        /// Compares elements for ordering.
        /// </summary>
        /// <remarks></remarks>
        public override int Compare(IProductElement x, IProductElement y)
        {
            // Make initial trace statement for this comparer
            tracer.Info(
                "Comparer $safeitemname$ between element '{0}' and element '{1}'", x.InstanceName, y.InstanceName);

            // TODO: Implement comparison automation code to determine the result
            var result = String.Compare(x.InstanceName, y.InstanceName, StringComparison.OrdinalIgnoreCase);

            // TODO: Use tracer.Warn() to note expected and recoverable errors
            // TODO: Use tracer.Verbose() to note internal execution logic decisions
            // TODO: Use tracer.Info() to note key results of execution
            // TODO: Raise exceptions for all other errors

            // Make resulting trace statement for this comparer
            tracer.Info(
                "Compared $safeitemname$ between element '{0}' and element '{1}', as '{2}'", x.InstanceName, y.InstanceName, result);

            return result;
        }
コード例 #47
0
ファイル: UseCase.cs プロジェクト: nulltoken/ServiceMatrix
 public void AddRelatedElement(IProductElement element)
 {
     this.EnsureRelatedElementListsExist();
     if (!this.UseCaseLinks.Any(l => l.LinkedElementId == element.Id))
     {
         this.InternalAddRelatedElement(element, false, true);
     }
 }
コード例 #48
0
ファイル: UseCase.cs プロジェクト: nulltoken/ServiceMatrix
        public void InternalAddRelatedElement(IProductElement element, bool isStarting = false, bool createLink = false)
        {
            if (element != null)
            {
                var command = element.As<ICommand>();
                var @event = element.As<IEvent>();
                var endpoint = element.As<IAbstractEndpoint>();
                var component = element.As<IComponent>();

                IUseCaseLink link = null;

                if (createLink)
                {
                    link = this.CreateUseCaseLink(element.Id.ToString());
                    link.LinkedElementId = element.Id;
                    if (command != null)
                    {
                        link.ElementType = "Command";
                    }
                    else if (@event != null)
                    {
                        link.ElementType = "Event";
                    }
                    else if (endpoint != null)
                    {
                        link.ElementType = "Endpoint";
                    }
                    else if (component != null)
                    {
                        link.ElementType = "Component";
                    }

                    link.StartsUseCase = isStarting;
                }

                if (command != null && !this.relatedCommands.Contains(command))
                {
                    this.relatedCommands.Add(command);
                }
                else if (@event != null && !this.relatedEvents.Contains(@event))
                {
                    this.relatedEvents.Add(@event);
                }
                else if (endpoint != null)
                {
                    if (isStarting && !this.endpointsStartingUseCases.Contains(endpoint))
                    {
                        this.endpointsStartingUseCases.Add(endpoint);
                    }
                    else if (!this.relatedEndpoints.Contains(endpoint) && !this.endpointsStartingUseCases.Contains(endpoint))
                    {
                        this.relatedEndpoints.Add(endpoint);
                    }
                }
                else if (component != null && !this.relatedComponents.Contains(component))
                {
                    this.relatedComponents.Add(component);
                }
            }
        }
コード例 #49
0
 private IProductElementViewModel SearchInNodes(ObservableCollection<IProductElementViewModel> observableCollection, IProductElement target)
 {
     foreach (IProductElementViewModel model in observableCollection)
     {
         if (model.Data == target)
         {
             return model;
         }
         IProductElementViewModel model2 = this.SearchInNodes(model.ChildNodes, target);
         if (model2 != null)
         {
             return model2;
         }
     }
     return null;
 }
コード例 #50
0
 /// <summary>
 /// Creates the runtime automation element for this setting element.
 /// </summary>
 public IAutomationExtension CreateAutomation(IProductElement owner)
 {
     return new TemplateAutomation(owner, this);
 }
コード例 #51
0
 public void Select(IProductElement element)
 {
 }
コード例 #52
0
        private void CreateComponentsForLibrary(ISolutionBuilderViewModel solutionBuilderModel, IApplication application, IProductElement library, int position)
        {
            var componentsVM = new InnerPanelViewModel();
            componentsVM.Title = "Used By Components";

            foreach (var service in application.Design.Services.Service
                                        .Where(s => s.Components.Component
                                            .Any(c => c.LibraryReferences.LibraryReference
                                                .Any(lr => lr.LibraryId == library.Id))))
            {
                componentsVM.Items.Add(new InnerPanelTitle
                {
                    Product = service.As<IProductElement>(),
                    Text = service.InstanceName,
                    ForceText = true,
                    MenuFilters = new string[] { },
                    IconPath = solutionBuilderModel.FindNodeFor(service.As<IProductElement>()).IconPath
                });
                foreach (var component in service.Components.Component
                                            .Where(c => c.LibraryReferences.LibraryReference
                                                .Any(lr => lr.LibraryId == library.Id)))
                {
                    componentsVM.Items.Add(new InnerPanelItem
                    {
                        Product = component.As<IProductElement>(),
                        Text = component.InstanceName
                    });
                }
            }

            this.SetPanel(position, new LogicalView(new LogicalViewModel(solutionBuilderModel, componentsVM)));
        }
コード例 #53
0
 private void CreateEventsPanel(ISolutionBuilderViewModel solutionBuilderModel, IEnumerable<IComponent> components, int position
     , IProductElement published = null, IProductElement subscribed = null)
 {
     var eventsVM = new InnerPanelViewModel();
     eventsVM.Title = "Events";
     eventsVM.Items.Add(new InnerPanelTitle { Text = "Published", Product = published, MenuFilters = new string[] { "Publish Event" }, ForceText = true });
     foreach (var publish in components.SelectMany(c => c.Publishes.EventLinks.Select(cl => cl.EventReference.Value)).Distinct())
     {
         eventsVM.Items.Add(new InnerPanelItem { Product = publish.As<IProductElement>(), Text = publish.InstanceName });
     }
     eventsVM.Items.Add(new InnerPanelTitle { Text = "Subscribed", Product = subscribed, MenuFilters = new string[] { "Process Messages…" }, ForceText = true });
     foreach (var subscribe in components.SelectMany(c => c.Subscribes.SubscribedEventLinks.Select(cl => cl.EventReference.Value)).Distinct())
     {
         if (subscribe != null)
         {
             eventsVM.Items.Add(new InnerPanelItem { Product = subscribe.As<IProductElement>(), Text = subscribe.InstanceName });
         }
         else
         {
             eventsVM.Items.Add(new InnerPanelItem { Product = null, Text = "[All the messages]" });
         }
     }
     this.SetPanel(position, new LogicalView(new LogicalViewModel(solutionBuilderModel, eventsVM)));
 }
コード例 #54
0
 private void CreateLibrariesPanel(ISolutionBuilderViewModel solutionBuilderModel, IProductElement product, IApplication application, int position)
 {
     var commandsVM = new InnerPanelViewModel();
     commandsVM.Title = "Libraries";
     var globalLibraries = application.Design.Libraries.Library.Where(l =>
                                     product.As<IComponent>().LibraryReferences.LibraryReference
                                             .Any(lr => lr.LibraryId == l.As<IProductElement>().Id))
                                     .Select(l => l.As<IProductElement>());
     commandsVM.Items.Add(new InnerPanelTitle { Text = "Global Libraries", Product = null, MenuFilters = new string[] { }, ForceText = true });
     foreach (var gl in globalLibraries)
     {
         commandsVM.Items.Add(new InnerPanelItem { Product = gl, Text = gl.InstanceName });
     }
     var serviceLibraries = product.As<IComponent>().Parent.Parent.ServiceLibraries.ServiceLibrary.Where(l =>
                                     product.As<IComponent>().LibraryReferences.LibraryReference
                                             .Any(lr => lr.LibraryId == l.As<IProductElement>().Id))
                                     .Select(l => l.As<IProductElement>());
     commandsVM.Items.Add(new InnerPanelTitle { Text = "Service Libraries", Product = null, MenuFilters = new string[] { }, ForceText = true });
     foreach (var sl in serviceLibraries)
     {
         commandsVM.Items.Add(new InnerPanelItem { Product = sl, Text = sl.InstanceName });
     }
     this.SetPanel(position, new LogicalView(new LogicalViewModel(solutionBuilderModel, commandsVM)));
 }
コード例 #55
0
        private void CreateUseCasesPanel(ISolutionBuilderViewModel solutionBuilderModel, IProductElement product, IApplication application, int position)
        {
            var commandsVM = new InnerPanelViewModel();
            commandsVM.Title = "Use Cases";
            var useCases = application.Design.UseCases.UseCase.Where(uc => uc.UseCaseLinks.Any(ul => ul.LinkedElementId == product.Id))
                .Union(application.Design.UseCases.UseCase.Where(uc => uc.RelatedEndpoints.Any(ep => ep.As<IProductElement>().Id == product.Id)))
                .Distinct();

            commandsVM.Items.Add(new InnerPanelTitle { Text = "Participates in", Product = null, MenuFilters = new string[] { }, ForceText = true });
            foreach (var usecase in useCases)
            {
                commandsVM.Items.Add(new InnerPanelItem { Product = usecase.As<IProductElement>(), Text = usecase.InstanceName });
            }
            this.SetPanel(position, new LogicalView(new LogicalViewModel(solutionBuilderModel, commandsVM)));
        }
コード例 #56
0
ファイル: Application.cs プロジェクト: slamj1/ServiceMatrix
 public string GetTargetNsbVersion(IProductElement element)
 {
     // TODO retrieve from element
     return TargetNsbVersion;
 }
コード例 #57
0
ファイル: UseCase.cs プロジェクト: nulltoken/ServiceMatrix
        public void RemoveRelatedElement(IProductElement element)
        {
            var command = element.As<ICommand>();
            var @event = element.As<IEvent>();
            var endpoint = element.As<IAbstractEndpoint>();
            var component = element.As<IComponent>();
            var link = this.UseCaseLinks.FirstOrDefault(l => l.LinkedElementId == element.Id);
            if (link != null)
            {
                link.Delete();
            }

            if (command != null && relatedCommands.Contains(command))
            {
                this.relatedCommands.Remove(command);
            }
            else if (@event != null && this.relatedEvents.Contains(@event))
            {
                this.relatedEvents.Remove(@event);
            }
            else if (endpoint != null && this.relatedEndpoints.Contains(endpoint))
            {
                this.relatedEndpoints.Remove(endpoint);
            }
            else if (component != null && this.relatedComponents.Contains(component))
            {
                this.relatedComponents.Remove(component);
            }
        }
コード例 #58
0
 /// <summary>
 /// Creates a new instance of the <see cref="VsTemplateFileImporter"/> class.
 /// </summary>
 public VsTemplateFileImporter(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, string targetPath)
     : base(solution, uriService, currentElement, targetPath)
 {
     this.currentElement = currentElement;
 }
コード例 #59
0
        // This feature requires:
        // 1. A menu "Add Authentication" that generates Infrastructure\Security\Authentication Code.
        // 2. Add references to the infrastructure project from all the endpoints
        // 3. Also, add a new reference when a new endpoint has been instantiated
        // 4. Add a menu option for "Customize Authentication" on each endpoint
        // This should exist only if the endpoint doesn't have custom authentication already.
        // Initialization
        public void Initialize(IApplication app, IProductElement infrastructure, IServiceProvider serviceProvider, IPatternManager patternManager)
        {
            // InitializeAuthenticationValues
            InitializeAuthenticationValues(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);

            // Listen for a new endpoint initialization
            // in order to add the required artifacts (typically menu items)
            app.OnInitializingEndpoint += (s, e) =>
            {
                UpdateEndpointsForAuthentication(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
            };

            // Listen for endpoint instantiated, in order to generate
            // associated code.
            app.OnInstantiatedEndpoint += (s, e) =>
            {
                GenerateAuthenticationCodeOnEndpoints(app, serviceProvider);
            };

            app.OnApplicationLoaded += (s, e) =>
            {
                GenerateAuthenticationCodeOnEndpoints(app, serviceProvider);
            };
        }
コード例 #60
-1
 /// <summary>
 /// Gets the path to the guidance document from the current element.
 /// </summary>
 /// <remarks>
 /// Returns the first artifact link with a *.doc extension of the current element.
 /// </remarks>
 public static string GetDocumentPath(ITracer tracer, IProductElement element, IUriReferenceService uriService)
 {
     // Return path of first reference
     var references = SolutionArtifactLinkReference.GetResolvedReferences(element, uriService);
     if (!references.Any())
     {
         tracer.Warn(String.Format(CultureInfo.CurrentCulture,
             Resources.GuidanceDocumentPathProvider_NoLinksFound, element.InstanceName));
         return string.Empty;
     }
     else
     {
         var reference = references.FirstOrDefault(r => r.PhysicalPath.EndsWith(GuidanceDocumentExtension));
         if (reference == null)
         {
             tracer.Warn(String.Format(CultureInfo.CurrentCulture,
                 Resources.GuidanceDocumentPathProvider_NoDocumentLinkFound, element.InstanceName));
             return string.Empty;
         }
         else
         {
             tracer.Info(String.Format(CultureInfo.CurrentCulture,
                 Resources.GuidanceDocumentPathProvider_LinkFound, element.InstanceName, reference.PhysicalPath));
             return reference.PhysicalPath;
         }
     }
 }