Example #1
0
        /// <summary>
        /// Clone Properties between Containers.
        /// </summary>
        /// <param name="target">Target Container.</param>
        /// <param name="source">Source Container.</param>
        public static void MergeProperties(this IPropertiesContainer target,
                                           [NotNull] IPropertiesContainer source)
        {
            var properties = source?.Properties?.ToArray();

            if ((properties?.Any() ?? false) &&
                source is IThreatModelChild sourceChild &&
                sourceChild.Model is IThreatModel sourceModel &&
                target is IThreatModelChild targetChild &&
                targetChild.Model is IThreatModel targetModel)
            {
                foreach (var property in properties)
                {
                    var sourcePropertyType = property.PropertyType;
                    if (sourcePropertyType != null)
                    {
                        var sourceSchema = sourceModel.GetSchema(sourcePropertyType.SchemaId);
                        if (sourceSchema != null)
                        {
                            var targetSchema = targetModel.GetSchema(sourceSchema.Name, sourceSchema.Namespace) ??
                                               sourceSchema.Clone(targetModel);

                            var targetPropertyType = targetSchema.GetPropertyType(sourcePropertyType.Name) ??
                                                     sourcePropertyType.Clone(targetSchema);

                            var targetProperty = target.GetProperty(targetPropertyType);
                            if (targetProperty == null)
                            {
                                target.AddProperty(targetPropertyType, property.StringValue);
                            }
                        }
                    }
                }
            }
        }
Example #2
0
        private void AddItem([NotNull] IQualityAnalyzer analyzer,
                             [NotNull] IPropertiesContainer container,
                             [NotNull] IPropertyType propertyType)
        {
            var property = container.GetProperty(propertyType) as IPropertyJsonSerializableObject;

            if (property != null)
            {
                var list    = property.Value as FalsePositiveList;
                var finding = list?.FalsePositives.FirstOrDefault(x =>
                                                                  string.CompareOrdinal(x.QualityInitializerId, analyzer.GetExtensionId()) == 0);

                if (finding != null)
                {
                    _falsePositives.PrimaryGrid.Rows.Add(new GridRow(container.ToString(), finding.Reason, finding.Author, finding.Timestamp)
                    {
                        Tag = container
                    });
                }
            }

            if (container is IThreatEventsContainer threatEventsContainer)
            {
                var threatEvents = threatEventsContainer.ThreatEvents?.ToArray();
                if (threatEvents?.Any() ?? false)
                {
                    foreach (var te in threatEvents)
                    {
                        AddItem(analyzer, te, propertyType);
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Verifies if the object should be picked, based on the filter passed as argument.
        /// </summary>
        /// <param name="container">Object to be analyzed.</param>
        /// <param name="description">Optional description to be searched.</param>
        /// <param name="filter">Filter to be applied.</param>
        /// <returns>True if any string in the filter is present in any text field of the object.</returns>
        /// <remarks>It analyzes the Name, the Description and eventual Text properties.
        /// <para>The search is case-insensitive.</para></remarks>
        public static bool Filter(this IPropertiesContainer container, string description, [Required] string filter)
        {
            var name   = container.ToString();
            var result = (!string.IsNullOrWhiteSpace(name) &&
                          name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) ||
                         (!string.IsNullOrWhiteSpace(description) &&
                          description.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0);

            if (!result)
            {
                var properties = container.Properties?.ToArray();
                if (properties?.Any() ?? false)
                {
                    foreach (var property in properties)
                    {
                        var stringValue = property.StringValue;
                        if ((!string.IsNullOrWhiteSpace(stringValue) &&
                             stringValue.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0))
                        {
                            result = true;
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Example #4
0
 public void CopyPropertiesFrom(IPropertiesContainer properties)
 {
     foreach (KeyValuePair <string, string> pair in properties)
     {
         this[pair.Key] = pair.Value;
     }
 }
Example #5
0
        private void _objects_SelectedIndexChanged(object sender, EventArgs e)
        {
            _annotationLayoutControlItem.Visible = false;
            ChangeCustomActionStatus?.Invoke("RemoveReviewNote", false);
            RemoveButtons();

            if (_objects.SelectedItems.Count == 1 && _objects.SelectedItems[0].Tag is IPropertiesContainer container)
            {
                _selected        = container;
                _properties.Item = _selected;
                ChangeCustomActionStatus?.Invoke("AddReviewNote", true);

                _right.SuspendLayout();
                var reviewNotes = _schemaManager.GetAnnotations(container)?
                                  .Where(x => x is ReviewNote).ToArray();
                if (reviewNotes?.Any() ?? false)
                {
                    foreach (var reviewNote in reviewNotes)
                    {
                        AddButton(reviewNote);
                    }
                }

                _right.ResumeLayout();
            }
            else
            {
                _selected        = null;
                _properties.Item = null;
                ChangeCustomActionStatus?.Invoke("AddReviewNote", false);
            }
        }
 private void PropertyUpdated(IPropertiesContainer container, IProperty property)
 {
     if (property.PropertyTypeId == _propertyType.Id)
     {
         Update();
     }
 }
Example #7
0
        public void SetProperty([NotNull] IPropertiesContainer container, [Required] string propertyName,
                                [NotNull] IEnumerable <string> values, [Required] string value)
        {
            var schema = GetSchema();

            if (schema != null)
            {
                var propertyType = schema.GetPropertyType(propertyName);

                if (propertyType == null)
                {
                    propertyType = schema.AddPropertyType(propertyName, PropertyValueType.List);
                    if (propertyType is IListPropertyType listPropertyType)
                    {
                        listPropertyType.SetListProvider(new ListProvider());
                        listPropertyType.Context = values?.TagConcat();
                    }
                }

                var property = container.GetProperty(propertyType);

                if (property == null)
                {
                    container.AddProperty(propertyType, value);
                }
                else
                {
                    property.StringValue = value;
                }
            }
        }
        public void AddAnnotation([NotNull] IPropertiesContainer container, [NotNull] Annotation annotation)
        {
            var propertyType = GetAnnotationsPropertyType();

            if (propertyType != null)
            {
                var property = container.GetProperty(propertyType);
                if (property == null)
                {
                    property = container.AddProperty(propertyType, null);
                    if (property is IPropertyJsonSerializableObject jsonSerializableObject)
                    {
                        var annotations = new Annotations.Annotations();
                        annotations.Add(annotation);
                        jsonSerializableObject.Value = annotations;
                    }
                }
                else if (property is IPropertyJsonSerializableObject jsonSerializableObject)
                {
                    if (!(jsonSerializableObject.Value is Annotations.Annotations annotations))
                    {
                        annotations = new Annotations.Annotations();
                        jsonSerializableObject.Value = annotations;
                    }
                    annotations.Add(annotation);
                }
            }
        }
Example #9
0
        private static void AddProperties([NotNull] IThreatModel model,
                                          [NotNull] IPropertySchema baseSchema, IPropertySchema secondarySchema,
                                          IPropertiesContainer container, [NotNull] IEnumerable <Property> properties)
        {
            foreach (var property in properties)
            {
                if (!string.IsNullOrWhiteSpace(property.Name))
                {
                    var propertyType = baseSchema.GetPropertyType(property.Name) ??
                                       secondarySchema?.GetPropertyType(property.Name);

                    if (propertyType != null && container != null)
                    {
                        var value = property.Value;
                        if (string.IsNullOrWhiteSpace(value) && propertyType is IListPropertyType listPropertyType)
                        {
                            value = listPropertyType.Values.FirstOrDefault()?.Id;
                        }

                        var containerProperty = container.GetProperty(propertyType);
                        if (containerProperty == null)
                        {
                            container.AddProperty(propertyType, value);
                        }
                        else
                        {
                            containerProperty.StringValue = value;
                        }
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Writes out the block properties of a block.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="propertiesContainer">The block.</param>
        private static void WriteProperties(
            XmlWriter writer,
            IPropertiesContainer propertiesContainer)
        {
            // If we don't have properties, then don't write out anything.
            if (propertiesContainer.Properties.Count <= 0)
            {
                return;
            }

            // Write out the start element for the properties list.
            writer.WriteStartElement("properties", ProjectNamespace);

            // Go through all the properties, in order, and write it out.
            var propertyPaths = new List <HierarchicalPath>();

            propertyPaths.AddRange(propertiesContainer.Properties.Keys);
            propertyPaths.Sort();

            foreach (HierarchicalPath propertyPath in propertyPaths)
            {
                writer.WriteStartElement("property");
                writer.WriteAttributeString("path", propertyPath.ToString());
                writer.WriteString(propertiesContainer.Properties[propertyPath]);
                writer.WriteEndElement();
            }

            // Finish up the properties element.
            writer.WriteEndElement();
        }
Example #11
0
 public void CopyPropertiesFrom(IPropertiesContainer properties)
 {
     foreach (var pair in properties)
     {
         this[pair.Key] = pair.Value;
     }
 }
Example #12
0
        public bool Execute(IPropertiesContainer container)
        {
            bool result = false;

            if (container != null)
            {
                var dialog = new RemoveSchemaDialog();
                dialog.Initialize(container);
                if (dialog.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                {
                    var schema = dialog.SelectedSchema;
                    if (schema != null && MessageBox.Show($"You are about to remove Schema '{schema.ToString()}' from the selected object. Do you confirm?",
                                                          "Remove Schema", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        var properties = container.Properties?
                                         .Where(x => (x.PropertyType?.SchemaId ?? Guid.Empty) == schema.Id)
                                         .ToArray();

                        if (properties?.Any() ?? false)
                        {
                            foreach (var property in properties)
                            {
                                container.RemoveProperty(property.PropertyTypeId);
                            }

                            result = true;
                        }
                    }
                }
            }

            return(result);
        }
Example #13
0
        private bool ApplyGenRule([NotNull] IPropertiesContainer container, string value)
        {
            var result = false;

            if (container is IThreatModelChild child)
            {
                var propertyType = new AutoGenRulesPropertySchemaManager(child.Model).GetPropertyType();
                if (propertyType != null)
                {
                    var property = container.GetProperty(propertyType);
                    if (property != null)
                    {
                        property.StringValue = value;
                    }
                    else
                    {
                        container.AddProperty(propertyType, value);
                    }

                    result = true;
                }
            }

            return(result);
        }
Example #14
0
        public AnnotationPropertyViewerBlock([NotNull] IPropertiesContainer container, [NotNull] Annotation annotation)
        {
            _annotation = annotation;
            _container  = container;

            if (container is IThreatModelChild child)
            {
                _model = child.Model;
            }

            if (annotation is TopicToBeClarified topicToBeClarified)
            {
                Image = topicToBeClarified.Answered
                    ? Properties.Resources.speech_balloon_answer_big
                    : Properties.Resources.speech_balloon_question_big;
                BlockType = PropertyViewerBlockType.ImageButton;
            }
            else if (annotation is Highlight highlight)
            {
                Image     = Properties.Resources.marker_big;
                BlockType = PropertyViewerBlockType.ImageButton;
            }
            else if (annotation is ReviewNote reviewNote)
            {
                Image     = Properties.Resources.clipboard_check_edit_big;
                BlockType = PropertyViewerBlockType.ImageButton;
            }
            else
            {
                Image     = Properties.Resources.note_text_big;
                BlockType = PropertyViewerBlockType.String;
            }
        }
Example #15
0
        public static new IProperties FromValue(object context)
        {
            if (context == null)
            {
                return(Properties.Null);
            }

            IProperties pp = context as IProperties;

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

            IPropertiesContainer container = context as IPropertiesContainer;

            if (container != null)
            {
                return(container.Properties);
            }

            NameValueCollection nvc = context as NameValueCollection;

            if (nvc != null)
            {
                return(new NameValueCollectionAdapter(nvc));
            }

            return(MakeDictionaryProperties(context)
                   ?? ReflectionPropertiesUsingIndexer.TryCreate(context)
                   ?? new ReflectionProperties(context));
        }
 public static bool HasNotesWithText(this IPropertiesContainer container, [NotNull] AnnotationsPropertySchemaManager schemaManager, string filter)
 {
     return(string.IsNullOrWhiteSpace(filter) ||
            (schemaManager.GetAnnotations(container)?
             .Any(x => x.Text != null && x.Text.ToLower().Contains(filter.ToLower()) ||
                  (x is TopicToBeClarified topic &&
                   (topic.Answers?.Any(y => y.Text != null && y.Text.ToLower().Contains(filter.ToLower())) ?? false))) ?? false));
 }
Example #17
0
        public string GetInstanceId([NotNull] IPropertiesContainer container)
        {
            var schema       = GetSchema();
            var propertyType = schema.GetPropertyType(ThreatModelInstanceId);
            var property     = container.GetProperty(propertyType);

            return(property?.StringValue);
        }
Example #18
0
 public static PropertyValue GetProperty(this IPropertiesContainer propContainer, string key)
 {
     if (propContainer.Properties.TryGetValue(key, out var value))
     {
         return(value);
     }
     return(PropertyValue.Empty);
 }
Example #19
0
 public static void OvertakeAllProperties(
     this IPropertiesContainer targetContainer,
     IPropertiesContainer sourceContainer)
 {
     foreach (var actKey in sourceContainer.Properties.Keys)
     {
         targetContainer.SetProperty(actKey, sourceContainer.GetProperty(actKey));
     }
 }
Example #20
0
        public AddReviewNoteButtonPropertyViewerBlock([NotNull] IPropertiesContainer container, [NotNull] IProperty property)
        {
            _container = container;
            _property  = property;

            if (container is IThreatModelChild child)
            {
                _model = child.Model;
            }
        }
Example #21
0
        private static void ParseStream(TextReader stream, IPropertiesContainer properties)
        {
            string line;
            int    i = 1;

            while ((line = stream.ReadLine()) != null)
            {
                ParseLine(line, i++, properties);
            }
        }
Example #22
0
        public void Initialize([NotNull] IPropertiesContainer container)
        {
            IThreatModel model = null;

            if (container is IThreatModelChild child)
            {
                model = child.Model;
            }

            if (model != null)
            {
                if (container is IIdentity identity)
                {
                    string text   = identity.Name;
                    int    height = (int)(21 * Dpi.Factor.Height);
                    var    image  = identity.GetImage(ImageSize.Small);
                    if (image != null)
                    {
                        height           = image.Height + 10;
                        text             = "      " + text;
                        _container.Image = image;
                    }
                    _container.Text = text;
                }
                else
                {
                    if (container is IThreatTypeMitigation ttm)
                    {
                        _container.Text = ttm.Mitigation.Name;
                    }
                    else if (container is IThreatEventMitigation tte)
                    {
                        _container.Text = tte.Mitigation.Name;
                    }
                    else if (container is IWeaknessMitigation wm)
                    {
                        _container.Text = wm.Mitigation.Name;
                    }
                    else if (container is IVulnerabilityMitigation vm)
                    {
                        _container.Text = vm.Mitigation.Name;
                    }
                }

                var schemas = model.Schemas?
                              .Where(x => x.Visible && x.AppliesTo.HasFlag(container.PropertiesScope) &&
                                     !(container.Properties?.Any(y => (y.PropertyType?.SchemaId ?? Guid.Empty) == x.Id) ?? false))
                              .ToArray();

                if (schemas?.Any() ?? false)
                {
                    _schemas.Items.AddRange(schemas);
                }
            }
        }
Example #23
0
        private static void AddProperties([NotNull] IPropertySchema schema,
                                          IPropertiesContainer container, [NotNull] IEnumerable <Property> properties)
        {
            foreach (var property in properties)
            {
                if (!string.IsNullOrWhiteSpace(property.Name))
                {
                    var propertyType = schema.GetPropertyType(property.Name);
                    if (propertyType == null)
                    {
                        switch (property.Type)
                        {
                        case PropertyType.String:
                            propertyType = schema.AddPropertyType(property.Name,
                                                                  PropertyValueType.String);
                            break;

                        case PropertyType.Boolean:
                            propertyType = schema.AddPropertyType(property.Name,
                                                                  PropertyValueType.Boolean);
                            break;

                        case PropertyType.List:
                            propertyType =
                                schema.AddPropertyType(property.Name, PropertyValueType.List);
                            if (propertyType is IListPropertyType listPropertyType)
                            {
                                listPropertyType.Context = property.Values.TagConcat();
                                listPropertyType.SetListProvider(new ListProviderExtension());
                            }
                            break;
                        }
                    }

                    if (propertyType != null && container != null)
                    {
                        var value = property.Value;
                        if (string.IsNullOrWhiteSpace(value) && propertyType is IListPropertyType listPropertyType)
                        {
                            value = listPropertyType.Values.FirstOrDefault()?.Id;
                        }

                        var containerProperty = container.GetProperty(propertyType);
                        if (containerProperty == null)
                        {
                            container.AddProperty(propertyType, value);
                        }
                        else
                        {
                            containerProperty.StringValue = value;
                        }
                    }
                }
            }
        }
Example #24
0
 public static void SetProperty(this IPropertiesContainer propContainer, string key, PropertyValue value)
 {
     if (value.IsEmpty)
     {
         propContainer.Properties.Remove(key);
     }
     else
     {
         propContainer.Properties[key] = value;
     }
 }
Example #25
0
 private void Generate([NotNull] Question question, [NotNull] IPropertiesContainer container,
                       [NotNull] AnnotationsPropertySchemaManager schemaManager)
 {
     if (question.Rule?.Evaluate(container) ?? false)
     {
         schemaManager.AddAnnotation(container, new TopicToBeClarified()
         {
             Text = question.Text
         });
     }
 }
        private int Count(IPropertiesContainer container)
        {
            var result = 0;

            if (container != null)
            {
                result = _schemaManager.GetAnnotations(container)?.Count(x => (x is TopicToBeClarified topic) && !topic.Answered) ?? 0;
            }

            return(result);
        }
        private int Count(IPropertiesContainer container)
        {
            var result = 0;

            if (container != null)
            {
                result = _schemaManager.GetAnnotations(container)?.Count(x => x is Highlight) ?? 0;
            }

            return(result);
        }
        private static int GetCount(
            IPropertiesContainer propertiesContainer,
            HierarchicalPath rootPath,
            string countType)
        {
            var    path = new HierarchicalPath(countType, rootPath);
            string count;

            return(propertiesContainer.Properties.TryGetValue(path, out count)
                                ? Convert.ToInt32(count)
                                : 0);
        }
Example #29
0
        private bool Execute([NotNull] IPropertiesContainer container)
        {
            bool result = false;

            if (container is IThreatModelChild child)
            {
                var schemaManager = new AnnotationsPropertySchemaManager(child.Model);
                result = schemaManager.EnableAnnotations(container);
            }

            return(result);
        }
Example #30
0
        private int Count(IPropertiesContainer container)
        {
            var result = 0;

            if (container != null)
            {
                result = _schemaManager.GetAnnotations(container)?
                         .Count(x => !(x is AnnotationAnswer || x is Highlight || x is ReviewNote || x is TopicToBeClarified)) ?? 0;
            }

            return(result);
        }
        /// <summary>
        /// Updates the properties inside the block with the given deltas.
        /// </summary>
        /// <param name="propertiesContainer">The block.</param>
        /// <param name="deltas">The deltas.</param>
        /// <param name="multiplier">The multiplier.</param>
        private void UpdateDeltas(
			IPropertiesContainer propertiesContainer,
			IDictionary<HierarchicalPath, int> deltas,
			int multiplier = 1)
        {
            foreach (HierarchicalPath path in deltas.Keys)
            {
                int delta = deltas[path] * multiplier;
                Log("  Update Delta: {0}: {1} += {2}", propertiesContainer, path, delta);
                propertiesContainer.Properties.AdditionOrAdd(path, delta);
            }
        }
 public void CopyPropertiesFrom(IPropertiesContainer properties)
 {
     foreach (KeyValuePair<string, string> pair in properties)
         this[pair.Key] = pair.Value;
 }
 public void CopyPropertiesFrom(IPropertiesContainer properties)
 {
     throw new Exception("The method or operation is not implemented.");
 }
        private static void ParseLine(string line, int lineNumber, IPropertiesContainer properties)
        {
            if (line.Trim() == "" || line.StartsWith("#"))
                return;

            int index = line.IndexOf('=');
            if (index == -1)
            {
                logger.Error("Could not parse line " + lineNumber + ": " + line);
                throw new Exception("Could not parse line " + lineNumber + ": " + line);
            }

            string propKey = line.Substring(0, index).Trim();
            string propValue = line.Substring(index + 1).Trim();

            properties[propKey] = propValue;
        }
 private static void ParseStream(TextReader stream, IPropertiesContainer properties)
 {
     string line;
     int i = 1;
     while ((line = stream.ReadLine()) != null)
         ParseLine(line, i++, properties);
 }
        private void ParseFile(string filename, IPropertiesContainer properties)
        {
            if (logger.IsInfoEnabled)
                logger.Info("Parsing file: " + filename);

            StreamReader stream = File.OpenText(filename);
            ParseStream(stream, properties);
            stream.Close();
            stream.Dispose();
        }
        private static int GetCount(
			IPropertiesContainer propertiesContainer,
			HierarchicalPath rootPath,
			string countType)
        {
            var path = new HierarchicalPath(countType, rootPath);
            string count;

            return propertiesContainer.Properties.TryGetValue(path, out count)
                ? Convert.ToInt32(count)
                : 0;
        }