Exemple #1
0
        private Base buildInternal(ISourceNode source, Type typeToBuild)
        {
            if (source is IExceptionSource)
            {
                using (source.Catch((o, a) => ExceptionHandler.NotifyOrThrow(o, a)))
                {
                    return(build());
                }
            }
            else
            {
                return(build());
            }

            Base build()
            {
                var settings = new ParserSettings
                {
                    AcceptUnknownMembers   = _settings.IgnoreUnknownMembers,
                    AllowUnrecognizedEnums = _settings.AllowUnrecognizedEnums
                };

                return(typeToBuild.CanBeTreatedAsType(typeof(Resource))
                    ? new ResourceReader(source, settings).Deserialize()
                    : new ComplexTypeReader(source, settings).Deserialize(typeToBuild));
            }
        }
Exemple #2
0
        public Base BuildFrom(ISourceNode source, Type dataType = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull(nameof(source));
            }

            if (dataType != null)
            {
                return(buildInternal(source, dataType));
            }
            else
            {
                var rti = source.GetResourceTypeIndicator();
                if (rti == null)
                {
                    ExceptionHandler.NotifyOrThrow(this,
                                                   ExceptionNotification.Error(new StructuralTypeException($"No type indication on source to build POCO's for.")));
                    return(null);
                }
                else
                {
                    return(BuildFrom(source, rti));
                }
            }
        }
        /// <summary>Harvest specific summary information from a <see cref="StructureDefinition"/> resource.</summary>
        /// <returns><c>true</c> if the current target represents a <see cref="StructureDefinition"/> resource, or <c>false</c> otherwise.</returns>
        /// <remarks>The <see cref="ArtifactSummaryGenerator"/> calls this method from a <see cref="ArtifactSummaryHarvester"/> delegate.</remarks>
        public static bool Harvest(ISourceNode nav, ArtifactSummaryPropertyBag properties)
        {
            if (IsStructureDefinitionSummary(properties))
            {
                // [WMR 20171218] Harvest global core extensions, e.g. MaturityLevel
                nav.HarvestExtensions(properties, harvestExtension);

                // Explicit extractor chaining
                if (ConformanceSummaryProperties.Harvest(nav, properties))
                {
                    nav.HarvestValue(properties, FhirVersionKey, "fhirVersion");
                    nav.HarvestValue(properties, KindKey, "kind");
                    nav.HarvestValue(properties, ConstrainedTypeKey, "constrainedType");
                    nav.HarvestValue(properties, ContextTypeKey, "contextType");
                    // [WMR 20180919] NEW: Extension Context
                    nav.HarvestValues(properties, ContextKey, "context");
                    nav.HarvestValue(properties, BaseKey, "base");

                    // [WMR 20180725] Also harvest definition property from (first) root element in snapshot/differential
                    // HL7 FHIR website displays this text as introduction on top of each resource/datatype page
                    var elementNode = nav.Children("snapshot").FirstOrDefault() ?? nav.Children("differential").FirstOrDefault();
                    if (elementNode != null)
                    {
                        var childNode = elementNode.Children("element").FirstOrDefault();
                        if (childNode != null && Navigation.ElementDefinitionNavigator.IsRootPath(childNode.Name))
                        {
                            childNode.HarvestValue(properties, RootDefinitionKey, "definition");
                        }
                    }
                }
                return(true);
            }
            return(false);
        }
Exemple #4
0
        /// <summary>
        /// Build a POCO from an ISourceNode.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="mapping">Optional. The <see cref="ClassMapping" /> for the POCO to build. </param>
        /// <returns></returns>
        /// <remarks>If <paramref name="mapping"/> is not supplied, or is <code>Resource</code> or <code>DomainResource</code>,
        /// the builder will try to determine the actual type to create from the <paramref name="source"/>. </remarks>
        public Base BuildFrom(ISourceNode source, ClassMapping mapping = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull(nameof(source));
            }
            TypedElementSettings typedSettings = new TypedElementSettings
            {
                ErrorMode = _settings.IgnoreUnknownMembers ?
                            TypedElementSettings.TypeErrorMode.Ignore
                    : TypedElementSettings.TypeErrorMode.Report
            };

            string dataType;

            // If dataType is an abstract resource superclass -> ToTypedElement(with type=null) will figure it out;
            if (mapping == null)
            {
                dataType = null;
            }
            else if (mapping.IsResource && mapping.NativeType.GetTypeInfo().IsAbstract)
            {
                dataType = null;
            }
            else
            {
                dataType = mapping.Name;
            }

            var typedSource = source.ToTypedElement(_inspector, dataType, typedSettings);

            return(BuildFrom(typedSource));
        }
Exemple #5
0
 public NavigatorPosition(ISourceNode current, IElementDefinitionSummary info, string name, string instanceType)
 {
     SerializationInfo = info;
     Node         = current ?? throw Error.ArgumentNull(nameof(current));
     InstanceType = instanceType;
     Name         = name ?? throw Error.ArgumentNull(nameof(name));
 }
        private static SourceNode buildNode(ISourceNode node)
        {
            var me = new SourceNode(node.Name, node.Text);

            me.AddRange(node.Children().Select(c => buildNode(c)));
            return(me);
        }
Exemple #7
0
        private static Bundle ParseJSON(string content, bool permissive)
        {
            Bundle bundle = null;

            // Grab all errors found by visiting all nodes and report if not permissive
            if (!permissive)
            {
                List <string> entries = new List <string>();
                ISourceNode   node    = FhirJsonNode.Parse(content, "Bundle", new FhirJsonParsingSettings {
                    PermissiveParsing = permissive
                });
                foreach (Hl7.Fhir.Utility.ExceptionNotification problem in node.VisitAndCatch())
                {
                    entries.Add(problem.Message);
                }
                if (entries.Count > 0)
                {
                    throw new System.ArgumentException(String.Join("; ", entries).TrimEnd());
                }
            }
            // Try Parse
            try
            {
                FhirJsonParser parser = new FhirJsonParser(GetParserSettings(permissive));
                bundle = parser.Parse <Bundle>(content);
            }
            catch (Exception e)
            {
                throw new System.ArgumentException(e.Message);
            }

            return(bundle);
        }
Exemple #8
0
        private void WriteNode(ISourceNode node, TextWriter writer)
        {
            bool isFlat = node.GetType().GetCustomAttribute <FlatAttribute>() != null;

            foreach (var line in node.Prefix())
            {
                writer.Write(styleStack.Peek());
                writer.WriteLine(line);
            }

            if (!isFlat)
            {
                styleStack.Push(styleStack.Peek() + indent);
            }

            foreach (var child in node.Children())
            {
                WriteNode(child, writer);
            }

            if (!isFlat)
            {
                styleStack.Pop();
            }

            foreach (var line in node.Suffix())
            {
                writer.Write(styleStack.Peek());
                writer.WriteLine(line);
            }
        }
Exemple #9
0
        public static void ElementNavPerformance(ISourceNode nav)
        {
            // run extraction once to allow for caching
            extract();

            //System.Threading.Thread.Sleep(20000);

            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < 5_000; i++)
            {
                extract();
            }
            sw.Stop();

            Debug.WriteLine($"Navigating took {sw.ElapsedMilliseconds / 5 } micros");

            void extract()
            {
                var usual = nav.Children("identifier").First().Children("use").First().Text;

                Assert.IsNotNull(usual);
                var phone = nav.Children("telecom").First().Children("system").First().Text;

                Assert.IsNotNull(usual);
                var prefs = nav.Children("communication").Where(c => c.Children("preferred").Any(pr => pr.Text == "true")).Count();

                Assert.AreNotEqual(0, prefs);
                var link = nav.Children("link").Children("other").Children("reference");

                Assert.IsNotNull(link);
            }
        }
Exemple #10
0
        public void KeepsAnnotations()
        {
            ISourceNode firstIdNode = patient[1][0];

            Assert.Equal("a string annotation", firstIdNode.Annotation <string>());
            Assert.Equal("a string annotation", patient["active"]["id"].First().Annotation <string>());
        }
Exemple #11
0
        /// <summary>
        /// Build a POCO from an ISourceNode.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dataType">Optional. Type of POCO to build. Should be one of the generated POCO classes.</param>
        /// <returns></returns>
        /// <remarks>If <paramref name="dataType"/> is not supplied, or is <code>Resource</code> or <code>DomainResource</code>,
        /// the builder will try to determine the actual type to create from the <paramref name="source"/>. </remarks>
        public Base BuildFrom(ISourceNode source, Type dataType = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull(nameof(source));
            }

            return(BuildFrom(source, dataType != null ?
                             findMappingOrReport(dataType) : null));

            ClassMapping findMappingOrReport(Type t)
            {
                var typeFound = _inspector.FindClassMapping(dataType);

                if (typeFound == null)
                {
                    ExceptionHandler.NotifyOrThrow(this,
                                                   ExceptionNotification.Error(
                                                       new StructuralTypeException($"While building a POCO: The .NET type '{dataType.Name}' does not represent a FHIR type.")));

                    return(null);
                }

                return(typeFound);
            }
        }
Exemple #12
0
        internal RepeatingElementReader(ISourceNode reader, ParserSettings settings)
        {
            _current   = reader;
            _inspector = BaseFhirParser.Inspector;

            Settings = settings;
        }
Exemple #13
0
        private NavigatorPosition buildRootPosition(ISourceNode element, string type, IStructureDefinitionSummaryProvider provider)
        {
            var rootType = type ?? element.GetResourceTypeIndicator();

            if (rootType == null)
            {
                if (_settings.ErrorMode == TypedElementSettings.TypeErrorMode.Report)
                {
                    throw Error.Argument(nameof(type), $"Cannot determine the type of the root element at '{element.Location}', " +
                                         $"please supply a type argument.");
                }
                else
                {
                    return(NavigatorPosition.ForRoot(element, null, element.Name));
                }
            }

            var elementType = provider.Provide(rootType);

            if (elementType == null)
            {
                if (_settings.ErrorMode == TypedElementSettings.TypeErrorMode.Report)
                {
                    throw Error.Argument(nameof(type), $"Cannot locate type information for type '{rootType}'");
                }
                else
                {
                    return(NavigatorPosition.ForRoot(element, null, element.Name));
                }
            }

            return(NavigatorPosition.ForRoot(element, elementType, element.Name));
        }
Exemple #14
0
        /// <summary>Harvest the value of a child element into a property bag.</summary>
        /// <param name="nav">An <see cref="ISourceNode"/> instance.</param>
        /// <param name="properties">A property bag to store harvested summary information.</param>
        /// <param name="key">A property key.</param>
        /// <param name="element">An element name.</param>
        /// <param name="childElement">A child element name.</param>
        public static bool HarvestValue(this ISourceNode nav, IDictionary <string, object> properties, string key, string element, string childElement)
        {
            var elementNode = nav.Children(element).FirstOrDefault();
            var childNode   = elementNode?.Children(childElement).FirstOrDefault();

            return(childNode != null && HarvestValue(childNode, properties, key));
        }
Exemple #15
0
        private static SourceNode buildNode(ISourceNode node, bool recursive, IEnumerable <Type> annotationsToCopy)
        {
            var me = new SourceNode(node.Name, node.Text);

            var rts = node.Annotation <IResourceTypeSupplier>();

            if (rts != null)
            {
                me.ResourceType = rts.ResourceType;
            }

            foreach (var t in annotationsToCopy ?? Enumerable.Empty <Type>())
            {
                foreach (var ann in node.Annotations(t))
                {
                    me.AddAnnotation(ann);
                }
            }

            if (recursive)
            {
                me.AddRange(node.Children().Select(c => buildNode(c, recursive: true, annotationsToCopy: annotationsToCopy)));
            }

            return(me);
        }
Exemple #16
0
        internal static BundleWrapper ReadEmbeddedSearchParameters(
            string embeddedResourceName,
            IModelInfoProvider modelInfoProvider,
            string embeddedResourceNamespace = null,
            Assembly assembly = null)
        {
            using Stream stream         = modelInfoProvider.OpenVersionedFileStream(embeddedResourceName, embeddedResourceNamespace, assembly);
            using TextReader reader     = new StreamReader(stream);
            using JsonReader jsonReader = new JsonTextReader(reader);
            try
            {
                ISourceNode sourceNode = FhirJsonNode.Read(jsonReader);
                return(new BundleWrapper(modelInfoProvider.ToTypedElement(sourceNode)));
            }
            catch (FormatException ex)
            {
                var issue = new OperationOutcomeIssue(
                    OperationOutcomeConstants.IssueSeverity.Fatal,
                    OperationOutcomeConstants.IssueType.Invalid,
                    ex.Message);

                throw new InvalidDefinitionException(
                          Core.Resources.SearchParameterDefinitionContainsInvalidEntry,
                          new OperationOutcomeIssue[] { issue });
            }
        }
 /// <summary>
 /// Visit all nodes in a tree while invoking the <see cref="ISourceNode.Text" /> getter. />
 /// </summary>
 /// <param name="root">The root of the tree to visit.</param>
 /// <remarks>Since implementations of ISourceNode will report parsing errors when enumerating
 /// children and getting their <see cref="ISourceNode.Text"/> getter, this will trigger all
 /// parsing errors to be reported by the source.</remarks>
 public static void VisitAll(this ISourceNode root)
 {
     if (root == null)
     {
         throw Error.ArgumentNull(nameof(root));
     }
     root.Visit((_, n) => { var dummy = n.Text; });
 }
 /// <summary>
 /// Returns a node and all descendants of that node.
 /// </summary>
 /// <param name="node">A node.</param>
 /// <returns>The node and descendants (children and by recursion all children of the children) of the node passed into
 /// <paramref name="node"/></returns>
 public static IEnumerable <ISourceNode> DescendantsAndSelf(this ISourceNode node)
 {
     if (node == null)
     {
         throw Error.ArgumentNull(nameof(node));
     }
     return((new[] { node }).Concat(node.Descendants()));
 }
Exemple #19
0
        public MockStructureDefinitionSummaryProvider(ISourceNode node, HashSet <string> seenTypes)
        {
            EnsureArg.IsNotNull(node, nameof(node));
            EnsureArg.IsNotNull(seenTypes, nameof(seenTypes));

            SeenTypes = seenTypes;
            _node     = node;
        }
 private static void visit(this ISourceNode navigator, Action <int, ISourceNode> visitor, int depth = 0)
 {
     visitor(depth, navigator);
     foreach (var child in navigator.Children())
     {
         visit(child, visitor, depth + 1);
     }
 }
Exemple #21
0
        internal DispatchingReader(ISourceNode data, ParserSettings settings, bool arrayMode)
        {
            _current   = data;
            _inspector = BaseFhirParser.Inspector;
            _arrayMode = arrayMode;

            Settings = settings;
        }
        // GET: /sourcenode/

        public sourcenodeController(ISourceNode sourceNodeService)
        {
            if (sourceNodeService == null)
            {
                throw new Exception("source Node Injection failed.");
            }
            _sourceNodeService = sourceNodeService;
        }
 /// <summary>Harvest specific summary information from a <see cref="NamingSystem"/> resource.</summary>
 /// <returns><c>true</c> if the current target represents a <see cref="NamingSystem"/> resource, or <c>false</c> otherwise.</returns>
 /// <remarks>The <see cref="ArtifactSummaryGenerator"/> calls this method through a <see cref="ArtifactSummaryHarvester"/> delegate.</remarks>
 public static bool Harvest(ISourceNode nav, ArtifactSummaryPropertyBag properties)
 {
     if (IsNamingSystemSummary(properties))
     {
         nav.HarvestValues(properties, UniqueIdKey, "uniqueId", "value");
         return(true);
     }
     return(false);
 }
        private void _DumpNode(ISourceNode node)
        {
            Console.WriteLine($"{node.Location,70} {node.Name,20} {node.Text}");

            foreach (ISourceNode child in node.Children())
            {
                _DumpNode(child);
            }
        }
Exemple #25
0
 static bool HarvestPatientSummary(ISourceNode nav, ArtifactSummaryPropertyBag properties)
 {
     if (properties.GetTypeName() == ResourceType.Patient.GetLiteral())
     {
         nav.HarvestValues(properties, PatientFamilyNameKey, "name", "family");
         return(true);
     }
     return(false);
 }
        public SourceNodeToTypedElementAdapter(ISourceNode node)
        {
            Current = node ?? throw Error.ArgumentNull(nameof(node));

            if (node is IExceptionSource ies && ies.ExceptionHandler == null)
            {
                ies.ExceptionHandler = (o, a) => ExceptionHandler.NotifyOrThrow(o, a);
            }
        }
 private TypedElementOnSourceNode(TypedElementOnSourceNode parent, ISourceNode source, IElementDefinitionSummary definition, string instanceType, string prettyPath)
 {
     _source          = source;
     ShortPath        = prettyPath;
     Provider         = parent.Provider;
     ExceptionHandler = parent.ExceptionHandler;
     Definition       = definition;
     InstanceType     = instanceType;
     _settings        = parent._settings;
 }
 // Callback for HarvestExtensions, called for each individual extension entry
 static void harvestExtension(ISourceNode nav, IDictionary <string, object> properties, string url)
 {
     if (StringComparer.Ordinal.Equals(FmmExtensionUrl, url))
     {
         var child = nav.Children("valueInteger").FirstOrDefault();
         if (child != null)
         {
             properties[MaturityLevelKey] = child.Text;
         }
     }
 }
Exemple #29
0
        public static NavigatorPosition ForRoot(ISourceNode element, IStructureDefinitionSummary elementType, string elementName)
        {
            if (elementName == null)
            {
                throw Error.ArgumentNull(nameof(elementName));
            }

            var rootElement = elementType != null?ElementDefinitionSummary.ForRoot(elementName, elementType) : null;

            return(new NavigatorPosition(element, rootElement, elementName, elementType?.TypeName));
        }
        // Generate summary for a single artifact
        static ArtifactSummary generate(
            ArtifactSummaryPropertyBag props,
            ISourceNode nav,
            ArtifactSummaryHarvester[] harvesters)
        {
            Exception error = null;

            // [WMR 20180419] Support empty harvester list (harvest only default props, no custom props)
            if (harvesters != null && harvesters.Length > 0)
            {
                try
                {
                    // Harvest summary information via specified harvesters
                    // Top-level harvesters receive navigator positioned on the first child element level

                    // Catch individual exceptions inside loop, return as AggregateException
                    var errors = new List <Exception>();
                    if (nav.Children().Any())
                    {
                        foreach (var harvester in harvesters)
                        {
                            try
                            {
                                if (harvester != null && harvester.Invoke(nav, props))
                                {
                                    break;
                                }
                            }
                            // TODO Catch specific exceptions
                            // catch (FormatException)
                            catch (Exception ex)
                            {
                                errors.Add(ex);
                            }
                        }
                    }

                    // Combine all errors into single AggregateException
                    error = errors.Count > 0 ? new AggregateException(errors) : null;
                }
                // TODO Catch specific exceptions
                // catch (FormatException)
                // catch (NotSupportedException)
                catch (Exception ex)
                {
                    // Error in summary factory?
                    // Make sure we always return a valid summary
                    error = ex;
                }
            }

            // Create final summary from harvested properties and optional error
            return(new ArtifactSummary(props, error));
        }
Exemple #31
0
        public void AddResource(SourceCategory category, ISourceNode node, bool selectAfterOperation)
        {
            if (category.Resources != null)
                if (!category.Resources.Contains(node))
                    category.Resources.Add(node);

            if (categories.ContainsKey(category))
            {
                categories[category].AddResourceNode(node, selectAfterOperation);
                if(!itemsByViews.ContainsKey(node))
                itemsByViews.Add(node, categories[category]);
            }
        }
Exemple #32
0
 public void SetSelectedItem(ISourceNode node)
 {
     for (int i = 0; i < this.GroupBarItems.Count; i++)
     {
         GroupView view = (this.GroupBarItems[i].Client as GroupView);
         for(int j = 0; j < view.GroupViewItems.Count; j++)
             if (view.GroupViewItems[j].Text == node.Name)
             {
                 this.SelectedItem = i;
                 view.SelectedItem = j;
             }
     }
 }
Exemple #33
0
 public void SelectSource(ISourceNode node, bool isLocal)
 {
     if (isLocal)
     {
         mainTabControl.SelectedIndex = 0;
         SelectLocalSource();
     }
     else
     {
         mainTabControl.SelectedIndex = 1;
         SelectGlobalSource();
     }
     SourceGroupBar bar = isLocal ? presentationSourceGroupBar : globalSourceGroupBar;
     bar.SetSelectedItem(node);
 }
 public void CopySourceToGlobal(ISourceNode node)
 {
     MakeResourceCopy(node, false);
 }
 public void CopySourceToPresentation(ISourceNode node)
 {
     MakeResourceCopy(node, true);
 }
        void MakeResourceCopy(ISourceNode node, bool Local)
        {
            localResourceCopying = true;
            try
            {
                ResourceDescriptor descriptor = null;
                if (Local)
                    descriptor = DesignerClient.Instance.PresentationWorker.CopySourceFromGlobalToLocal(node.Mapping, m_presentation.UniqueName);
                else
                {
                    bool isUnique = true;
                    foreach (var resource in resourceNodes)
                    {
                        if (!resource.Key.IsLocal && ResourceInfoEquals(resource.Key.ResourceInfo, node.Mapping.ResourceInfo))
                        {
                            isUnique = false;
                            break;
                        }
                    }

                    if (isUnique)
                    {
                        //SourcesController.Instance.SavePresentationSources();
                        descriptor = DesignerClient.Instance.PresentationWorker.CopySourceFromLocalToGlobal(node.Mapping);
                    }
                }

                if (descriptor != null)
                {
                    descriptor.Created = true;
                    ResourceInfo resource = descriptor.ResourceInfo;
                    SourceWindow clone = new SourceWindow(descriptor) { SourceType = node.SourceType };
                    resourceNodes.Add(descriptor, clone);
                    _view.AddResourceToCategory(Local ? local_categories[resource.Type] : global_categories[resource.Type], clone, !Local);

                }
                else
                {
                    StringBuilder sb = new StringBuilder("Источник уже добавлен к ");

                    if (Local) sb.Append("источникам сценария"); else sb.Append("общим источникам");
                    MessageBoxExt.Show(sb.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                localResourceCopying = false;
            }
        }
Exemple #37
0
        void Global_OnNodeSelected(ISourceNode node)
        {
            globalSelectedNode = node;
            SourceCategory c = SourcesController.Instance.GetSourceCategory(globalSourceGroupBar.SelectedItemText, false);
            EnableGlobalSourceOperations(node != null);

            if (node != null)
            {
                globalSourcePropertyButton.Enabled = true;
                globalSourceRemoveStripButton.Enabled = !c.IsHardware;
                copyToPresentationStripButton.Enabled = !c.IsHardware;
                GlobalSourceOperationsEnabled = !c.IsHardware;
            }

            toolStripExGlobal.Invoke(new MethodInvoker(() =>
            {
                if (c != null)
                    addGlobalSourceStripButton.Enabled = !c.IsHardware;

                globalPreviewStripButton.Enabled = node != null && node.SourceType.IsSupportPreview;
            }));
        }
Exemple #38
0
 public void RemoveSourceFromCategory(SourceCategory sourceCategory, ISourceNode node, bool Global)
 {
     if (Global)
         globalSourceGroupBar.RemoveNode(sourceCategory, node);
     else
         presentationSourceGroupBar.RemoveNode(sourceCategory, node);
 }
        void PresentationNotifier_OnResourceDeleted(object sender, NotifierEventArg<ResourceDescriptor> e)
        {
            if ((nodeToRemove != null && nodeToRemove.Mapping != e.Data) || nodeToRemove == null)
            {
                if (resourceNodes.Keys.Any(k => k.Equals(e.Data)))
                {
                    foreach (var n in resourceNodes)
                    {
                        if (n.Key.Equals(e.Data))
                        {
                            bool Global = !e.Data.IsLocal;

                            ISourceNode node = n.Value;
                            node.Mapping.Removed = true;
                            _view.RemoveSourceFromCategory(Global ? global_categories[node.Mapping.ResourceInfo.Type] : local_categories[node.Mapping.ResourceInfo.Type], node, Global);

                            if (serviceContainer != null)
                                serviceContainer.Remove(node.Mapping);

                            resourceNodes.Remove(node.Mapping);
                            nodeToRemove = null;

                            break;
                        }
                    }
                }
            }
        }
Exemple #40
0
        void Local_OnNodeSelected(ISourceNode node)
        {
            localSelectedNode = node;
            EnablePresentationSourceOperations(node != null);

            toolStripExPresentation.Invoke(new MethodInvoker(() =>
            {
                previewPresentationSourceStripButton.Enabled = node != null && node.SourceType.IsSupportPreview;
            }));
        }
Exemple #41
0
 public void RefreshSourceName(ISourceNode source)
 {
     if (itemsByViews.ContainsKey(source))
         itemsByViews[source].RefreshSourceName(source);
 }
Exemple #42
0
 public void RemoveNode(SourceCategory sourceCategory, ISourceNode node)
 {
     categories[sourceCategory].RemoveNode(node);
     sourceCategory.Resources.Remove(node);
 }
Exemple #43
0
 public void OnHardwareStateChanged(ISourceNode node, bool? online)
 {
     if(itemsByViews.ContainsKey(node))
         itemsByViews[node].OnHardwareStateChanged(node, online);
 }
        public void RemoveResource(ISourceNode node, bool Global)
        {
            nodeToRemove = node;
            //проверим, не использован ли источник в несохраненном сценарии
            // сначала надо проверять локально потом на сервере
            //https://sentinel2.luxoft.com/sen/issues/browse/PMEDIAINFOVISDEV-1041
            bool weContains = PresentationController.Instance.Presentation.SlideList.Any(s => s.SourceList.Any(n => n.ResourceDescriptor.ResourceInfo.Equals(node.Mapping.ResourceInfo)));

            RemoveResult removeResult = RemoveResult.LinkedToPresentation;
            if (!weContains)
            {
                removeResult =
                    DesignerClient.Instance.PresentationWorker.DeleteSource(node.Mapping);
            }

            if (RemoveResult.Ok == removeResult && !weContains)
            {
                node.Mapping.Removed = true;
                _view.RemoveSourceFromCategory(Global ? global_categories[node.Mapping.ResourceInfo.Type] : local_categories[node.Mapping.ResourceInfo.Type], node, Global);

                if (serviceContainer != null)
                    serviceContainer.Remove(node.Mapping);

                //if (Global)
                //{
                resourceNodes.Remove(node.Mapping);
                //}
                //else
                //    PresentationController.Instance.PresentationChanged = true;
                nodeToRemove = null;
            }
            else
            {
                string message = (removeResult == RemoveResult.LinkedToPresentation || weContains)
                                     ?
                                         "Удаление источника невозможно. Он используется в сценариях"
                                     :
                                         "Удаление источника невозможно. Он уже удален";
                MessageBoxExt.Show(message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 public void PreviewSource(ISourceNode node)
 {
     IDesignerModule module = DesignerClient.Instance.GetDesignerModule(node.SourceType.GetType());
     String file = String.Empty;
     if (ClientResourceCRUDForGet.GetSource(node.Mapping, true))
         file = DesignerClient.Instance.SourceDAL.GetResourceFileName(node.Mapping);
     if (!String.IsNullOrEmpty(file) && module != null && node.Mapping.ResourceInfo is ResourceFileInfo)
     {
         try
         {
             string newName = Path.ChangeExtension(file, Path.GetExtension((node.Mapping.ResourceInfo as ResourceFileInfo).MasterResourceProperty.ResourceFileName));   //ResourceFullFileName
             // Удаляем существующую копию, иначе File.Move вылетит
             try
             {
                 if (File.Exists(newName)) File.Delete(newName);
             }
             catch (IOException ex)
             {
                 _config.EventLog.WriteError(ex.ToString());
                 throw;
             }
             File.Copy(file, newName);
             //// если автономный режим, то надо файл копировать
             //if (DesignerClient.Instance.IsStandAlone)
             //else
             //    File.Move(file, newName);
             module.Preview(newName);
         }
         catch (FileNotFoundException /*ex*/)
         {
             MessageBoxExt.Show(
                 String.Format("Просмотр источника {0} невозможен: в хранилище нет файла", node.Mapping.ResourceInfo.Name),
                 "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         catch (Exception ex)
         {
             MessageBoxExt.Show(ex.Message, "Ошибка просмотра", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemple #46
0
 public void OnHardwareStateChanged(ISourceNode node, bool? online)
 {
     if (node.Mapping.IsLocal)
         presentationSourceGroupBar.OnHardwareStateChanged(node, online);
     else
         globalSourceGroupBar.OnHardwareStateChanged(node, online);
 }
Exemple #47
0
 internal void SelectItem(ISourceNode node)
 {
     if (OnResourceSelected != null)
         OnResourceSelected(node);
 }
Exemple #48
0
 public void AddResourceToCategory(SourceCategory category, ISourceNode resource, bool Global)
 {
     if (!Global)
         presentationSourceGroupBar.AddResource(category, resource, true);
     else
     {
         globalSourceGroupBar.AddResource(category, resource, true);
     }
 }