public void LoadAssembly()
        {
            ModuleDefinition module = ModuleDefinition.ReadModule(FullPath, App.CurrentProject.ReaderParams);
            if (module != null)
            {
                // Add the assembly module to our dictionary
                assemblyData = new AssemblyData(FullPath, module);

                // Create global namespace
                assemblyData.AddNamespace("", new NamespaceData("-"));
                NamespaceData namespaceData;

                // Find namespaces in the loaded assembly
                foreach (TypeDefinition type in module.Types)
                {
                    bool existingNamespace = assemblyData.Namespaces.TryGetValue(type.Namespace, out namespaceData);
                    if (!existingNamespace)
                    {
                        namespaceData = new NamespaceData(type.Namespace);
                        assemblyData.AddNamespace(type.Namespace, namespaceData);
                    }
                    namespaceData.Add(type);
                }
            }
        }
        private void PopulateAssemblyNode(TreeNode root, NamespaceData namespacedata, bool isglobal = false)
        {
            // Add global namespace node if needed
            TreeNode typeparent;

            if (isglobal)
            {
                typeparent                  = new TreeNode("global");
                typeparent.ImageKey         = "namespace.png";
                typeparent.SelectedImageKey = "namespace.png";
                root.Nodes.Add(typeparent);
            }
            else
            {
                typeparent = root;
            }

            // Add all namespaces
            NamespaceData[] namespaces = namespacedata.ChildNamespaces.ToArray();
            Array.Sort(namespaces, (a, b) => Comparer <string> .Default.Compare(a.Name, b.Name));
            for (int i = 0; i < namespaces.Length; i++)
            {
                // Get namespace
                NamespaceData data    = namespaces[i];
                string[]      spl     = data.Name.Split('.');
                string        subname = spl[spl.Length - 1];

                // Create a node for it
                TreeNode namespacenode = new TreeNode(subname);
                namespacenode.ImageKey         = "namespace.png";
                namespacenode.SelectedImageKey = "namespace.png";
                root.Nodes.Add(namespacenode);

                // Recursively fill in children
                PopulateAssemblyNode(namespacenode, data);
            }

            // Add all types
            TypeDefinition[] typedefs = namespacedata.ChildTypes.ToArray();
            Array.Sort(typedefs, (a, b) => Comparer <string> .Default.Compare(a.Name, b.Name));
            for (int i = 0; i < typedefs.Length; i++)
            {
                // Get type
                TypeDefinition typedef = typedefs[i];
                if (!typedef.IsNested)
                {
                    // Create a node for it
                    TreeNode typenode = new TreeNode(typedef.Name);
                    string   img      = SelectIcon(typedef);
                    typenode.ImageKey         = img;
                    typenode.SelectedImageKey = img;
                    typenode.Tag = typedef;
                    typeparent.Nodes.Add(typenode);

                    // Populate any nested types
                    PopulateAssemblyNode(typenode, typedef);
                }
            }
        }
Exemple #3
0
        public void TestAssemblyDataNamespaces()
        {
            string       expected              = "Reflection";
            Assembly     assembly              = Assembly.LoadFrom(dllTestPath);
            AssemblyData m_AssemblyModel       = new AssemblyData(assembly, log);
            IEnumerable <NamespaceData> m_Meta = m_AssemblyModel.Namespaces;
            IEnumerator enumerator             = m_Meta.GetEnumerator();

            enumerator.MoveNext();
            NamespaceData actual = (NamespaceData)enumerator.Current;

            Assert.AreEqual(expected, actual.Name);
        }
Exemple #4
0
        AttachedProperty <T> CreateAttachedPropertyForNamespace <T>(string propertyName)
        {
            return(new AttachedProperty <T>
            {
                Getter = (modelItem) =>
                {
                    NamespaceData data = modelItem.GetCurrentValue() as NamespaceData;
                    if (data == null)
                    {
                        return default(T);
                    }

                    IDictionary <string, object> properties;
                    if (!this.attachedPropertiesForNamespace.TryGetValue(data.Namespace, out properties))
                    {
                        return default(T);
                    }

                    object propertyValue;
                    if (!properties.TryGetValue(propertyName, out propertyValue))
                    {
                        return default(T);
                    }

                    return (T)propertyValue;
                },

                Setter = (modelItem, propertyValue) =>
                {
                    NamespaceData data = modelItem.GetCurrentValue() as NamespaceData;
                    if (data == null)
                    {
                        return;
                    }

                    IDictionary <string, object> properties;
                    if (!this.attachedPropertiesForNamespace.TryGetValue(data.Namespace, out properties))
                    {
                        properties = new Dictionary <string, object>();
                        this.attachedPropertiesForNamespace[data.Namespace] = properties;
                    }

                    properties[propertyName] = propertyValue;
                },
                Name = propertyName,
                OwnerType = typeof(NamespaceData),
                IsBrowsable = true,
            });
        }
Exemple #5
0
        void CommitImportNamespace(string addedNamespace)
        {
            ModelItem importItem;

            if (!TryGetWrapper(addedNamespace, out importItem))
            {
                NamespaceData newImport = new NamespaceData {
                    Namespace = addedNamespace
                };
                importItem = this.importsModelItem.Add(newImport);
            }
            this.importedNamespacesDataGrid.SelectedItem = importItem;
            this.importedNamespacesDataGrid.ScrollIntoView(importItem);
            this.textBox.Text = string.Empty;
        }
Exemple #6
0
        public Func <ITestContext, InterfaceData[]> GetInheritedInterfaces(ITestInterfaceGenerationOptions options, int count)
        {
            return(context =>
            {
                var interfaces = Enumerable.Range(context.NextId(), count).Select(_ => GetInheritedInterfaceData(_, context)).ToArray();
                foreach (var @interface in interfaces)
                {
                    var namespaceData = new NamespaceData(@interface.Namespace, @interface);
                    var compilationEntryData = new CompilationEntryData(options.UsingNamespaces, namespaceData);
                    context.AddCompilationEntry(compilationEntryData);
                }

                return interfaces;
            });
        }
Exemple #7
0
        bool TryGetWrapper(string imported, out ModelItem importItem)
        {
            importItem = null;
            foreach (ModelItem item in this.importsModelItem)
            {
                NamespaceData importedNamespace = item.GetCurrentValue() as NamespaceData;
                Fx.Assert(importedNamespace != null, "element of import list model has to be NamespaceData");
                if (importedNamespace.Namespace == imported)
                {
                    importItem = item;
                    return(true);
                }
            }

            return(false);
        }
        public string GetClass(List <SchemaTableRow> parameters, string className, NamespaceData namespaceData)
        {
            var result = new StringBuilder();

            result.Append(Templates.ClassTemplate.Replace(Templates.ClassTag, className)
                          .Replace(Templates.NamespaceTag, namespaceData.Interfaces))
            .Replace("    ", "\t");
            var parametersSection = new StringBuilder();

            parameters.ForEach(p =>
            {
                parametersSection.AppendLine($"\t\tpublic {_cSharpClassNameConverter.GetCSharpName(p.DataType, p.AllowDBNull)} {FirstCharToUpper(p.ColumnName)} {{ get; set; }}");
            });

            return(result.ToString().Replace(Templates.PropertiesTag, parametersSection.ToString()));
        }
        /// <summary>Extract the resource file from an <seealso cref="Assembly"/> and returns the content as an <seealso cref="Image"/>.</summary>
        /// <param name="assembly">The main assembly for the resources.</param>
        /// <param name="resourceBasePath">The resource base path to the file with its namespaces.</param>
        /// <exception cref="BadImageFormatException">Thrown when the resource base path cannot be found.</exception>
        public static Image ExtractToImage(Assembly assembly, string resourceBasePath)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly), @"The assembly cannot be null.");
            }

            if (!File.Exists(assembly.Location))
            {
                throw new ArgumentNullException(nameof(assembly.Location), @"The assembly location cannot be found.");
            }

            if (string.IsNullOrEmpty(resourceBasePath))
            {
                throw new ArgumentNullException(nameof(resourceBasePath), @"The resource base path cannot be null or empty.");
            }

            if (!NamespaceData.IsValidNamespace(resourceBasePath))
            {
                throw new BadImageFormatException(@"Invalid operation when extracting image from resources, possibly invalid namespace path.", resourceBasePath);
            }

            Image  extractedImage = null;
            string fileName       = ResourceFactory.CreateResourceFileName(assembly, resourceBasePath);

            if (assembly.ContainsResourceFile(fileName))
            {
                using (Stream resourceStream = assembly.GetManifestResourceStream(resourceBasePath))
                {
                    if (resourceStream == null)
                    {
                        throw new FileNotFoundException(@"Cannot find the resource name in the manifest stream.", fileName);
                    }

                    if (!resourceStream.CanRead)
                    {
                        throw new ArgumentNullException(nameof(resourceStream), @"The resource stream is not readable.");
                    }

                    extractedImage = Image.FromStream(resourceStream);
                }
            }

            return(extractedImage);
        }
Exemple #10
0
        public void TestAssemblyDataTypes()
        {
            string       expected              = "AssemblyData";
            Assembly     assembly              = Assembly.LoadFrom(dllTestPath);
            AssemblyData m_AssemblyModel       = new AssemblyData(assembly, log);
            IEnumerable <NamespaceData> m_Meta = m_AssemblyModel.Namespaces;
            IEnumerator namespaces             = m_Meta.GetEnumerator();

            namespaces.MoveNext();
            NamespaceData          firstNamespace = (NamespaceData)namespaces.Current;
            IEnumerable <TypeData> m_Meta2        = firstNamespace.Types;
            IEnumerator            types          = m_Meta2.GetEnumerator();

            types.MoveNext();
            TypeData actual = (TypeData)types.Current;

            Assert.AreEqual(expected, actual.Name);
        }
Exemple #11
0
        private void ValidateNamespaceModelAndUpdateContextItem(ModelItem namespaceModel)
        {
            NamespaceData namespaceData = namespaceModel.GetCurrentValue() as NamespaceData;

            Fx.Assert(namespaceData != null, "added item has to be NamespaceData");

            if (!this.availableNamespaces.ContainsKey(namespaceData.Namespace))
            {
                namespaceModel.Properties[ErrorMessagePropertyName].SetValue(string.Format(CultureInfo.CurrentCulture, SR.CannotResolveNamespace, namespaceData.Namespace));
                namespaceModel.Properties[IsInvalidPropertyName].SetValue(true);
            }
            else
            {
                namespaceModel.Properties[ErrorMessagePropertyName].SetValue(string.Empty);
                namespaceModel.Properties[IsInvalidPropertyName].SetValue(false);
                this.importedNamespacesItem.ImportedNamespaces.Add(namespaceData.Namespace);
            }
        }
        public IEnumerable <Func <ITestContext, IEnumerable <AttributeData> > > GetPossibleCombinations(ITestInterfaceGenerationOptions options)
        {
            var attributeToInheritInterfacesNumbers = Enumerable.Range(0, 2);

            foreach (var attributeToInheritInterfacesNumber in attributeToInheritInterfacesNumbers)
            {
                yield return(context =>
                {
                    var interfacesToInherit = Enumerable.Range(context.NextId(), attributeToInheritInterfacesNumber)
                                              .Select(GetBaseTypeInterfaceData).ToArray();

                    foreach (var interfaceToInherit in interfacesToInherit)
                    {
                        var namespaceData = new NamespaceData(interfaceToInherit.Namespace, interfaceToInherit);
                        var compilationEntryData = new CompilationEntryData(options.UsingNamespaces, namespaceData);
                        context.AddCompilationEntry(compilationEntryData);
                    }

                    return new AttributeData[] { new LoggerInterfaceAttributeData(interfacesToInherit) };
                });
            }
        }
Exemple #13
0
        void OnImportsModelItemCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (ModelItem namespaceModel in e.NewItems)
                {
                    ValidateNamespaceModelAndUpdateContextItem(namespaceModel);
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (ModelItem namespaceModel in e.OldItems)
                {
                    NamespaceData namespaceData = namespaceModel.GetCurrentValue() as NamespaceData;
                    Fx.Assert(namespaceData != null, "added item has to be NamespaceData");

                    this.importedNamespacesItem.ImportedNamespaces.Remove(namespaceData.Namespace);
                    this.attachedPropertiesForNamespace.Remove(namespaceData.Namespace);
                }
            }

            UpdateExpressionEditors();
        }
Exemple #14
0
        private void PopulateAssemblyNode(TreeNode root, NamespaceData namespacedata, bool isglobal = false)
        {
            // Add global namespace node if needed
            TreeNode typeparent;
            if (isglobal)
            {
                typeparent = new TreeNode("global");
                typeparent.ImageKey = "namespace.png";
                typeparent.SelectedImageKey = "namespace.png";
                root.Nodes.Add(typeparent);
            }
            else
                typeparent = root;

            // Add all namespaces
            NamespaceData[] namespaces = namespacedata.ChildNamespaces.ToArray();
            Array.Sort(namespaces, (a, b) => Comparer<string>.Default.Compare(a.Name, b.Name));
            for (int i = 0; i < namespaces.Length; i++)
            {
                // Get namespace
                NamespaceData data = namespaces[i];
                string[] spl = data.Name.Split('.');
                string subname = spl[spl.Length - 1];

                // Create a node for it
                TreeNode namespacenode = new TreeNode(subname);
                namespacenode.ImageKey = "namespace.png";
                namespacenode.SelectedImageKey = "namespace.png";
                root.Nodes.Add(namespacenode);

                // Recursively fill in children
                PopulateAssemblyNode(namespacenode, data);
            }

            // Add all types
            TypeDefinition[] typedefs = namespacedata.ChildTypes.ToArray();
            Array.Sort(typedefs, (a, b) => Comparer<string>.Default.Compare(a.Name, b.Name));
            for (int i = 0; i < typedefs.Length; i++)
            {
                // Get type
                TypeDefinition typedef = typedefs[i];
                if (!typedef.IsNested)
                {
                    // Create a node for it
                    TreeNode typenode = new TreeNode(typedef.Name);
                    string img = SelectIcon(typedef);
                    typenode.ImageKey = img;
                    typenode.SelectedImageKey = img;
                    typenode.Tag = typedef;
                    typeparent.Nodes.Add(typenode);

                    // Populate any nested types
                    PopulateAssemblyNode(typenode, typedef);
                }
            }
        }
Exemple #15
0
        private void PopulateAssemblyNode(TreeNode root, AssemblyDefinition definition)
        {
            // Build collection of all types
            HashSet<TypeDefinition> alltypes = new HashSet<TypeDefinition>(definition.Modules.SelectMany((x) => x.GetTypes()));

            // Sort types into their namespaces
            Dictionary<string, NamespaceData> namespaces = new Dictionary<string, NamespaceData>();
            NamespaceData globalnamespace = new NamespaceData("");
            namespaces.Add("", globalnamespace);
            foreach (TypeDefinition typedef in alltypes)
            {
                NamespaceData nspcdata;
                if (!namespaces.TryGetValue(typedef.Namespace, out nspcdata))
                {
                    nspcdata = new NamespaceData(typedef.Namespace);
                    namespaces.Add(nspcdata.Name, nspcdata);
                }
                if (typedef.Namespace == "") globalnamespace = nspcdata;
                nspcdata.ChildTypes.Add(typedef);
            }

            // Setup namespace hierarchy
            bool done = false;
            while (!done)
            {
                done = true;
                foreach (var pair in namespaces)
                {
                    if (pair.Value.Parent == null && pair.Value != globalnamespace)
                    {
                        if (pair.Key.Contains('.'))
                        {
                            string[] spl = pair.Key.Split('.');
                            string[] splm = new string[spl.Length - 1];
                            Array.Copy(spl, splm, splm.Length);
                            string parent = string.Concat(splm);
                            NamespaceData parentnamespace;
                            if (!namespaces.TryGetValue(parent, out parentnamespace))
                            {
                                parentnamespace = new NamespaceData(parent);
                                namespaces.Add(parent, parentnamespace);
                                parentnamespace.ChildNamespaces.Add(pair.Value);
                                pair.Value.Parent = parentnamespace;
                                done = false;
                                break;
                            }
                            parentnamespace.ChildNamespaces.Add(pair.Value);
                            pair.Value.Parent = parentnamespace;
                        }
                        else
                        {
                            globalnamespace.ChildNamespaces.Add(pair.Value);
                            pair.Value.Parent = globalnamespace;
                        }
                    }
                }
            }

            // Populate tree
            PopulateAssemblyNode(root, globalnamespace, true);
        }
 internal NamespaceDefinition(NamespaceData data)
 {
     Debug.Assert(data != null);
     _data = data;
 }
        public string GetCriteria(List <ParameterInfo> parameters, string criteriaClassName, NamespaceData namespaceData)
        {
            var result = new StringBuilder();

            result.Append(Templates.ClassTemplate.Replace(Templates.ClassTag, criteriaClassName)
                          .Replace(Templates.NamespaceTag, namespaceData.Interfaces))
            .Replace("    ", "\t");
            var parametersSection = new StringBuilder();

            parameters.ForEach(p =>
            {
                parametersSection.AppendLine($"\t\tpublic {_cSharpClassNameConverter.GetCSharpName(p.DotNetType, p.IsNullable)} {FirstCharToUpper(p.ParameterName)} {{ get; set; }}");
            });

            return(result.ToString().Replace(Templates.PropertiesTag, parametersSection.ToString()));
        }
        public string GetMapperInterface(List <SchemaTableRow> parameters, string className, NamespaceData namespaceData)
        {
            var result = new StringBuilder();

            result.Append(Templates.IMapperTemplate.Replace(Templates.ClassTag, className)
                          .Replace(Templates.NamespaceTag, namespaceData.Interfaces))
            .Replace("    ", "\t");
            var parametersSection = new StringBuilder();

            return(result.ToString());
        }
        public string GetMapperClass(List <SchemaTableRow> parameters, string className, NamespaceData namespaceData)
        {
            var result = new StringBuilder();

            result.Append(Templates.MapperTemplate.Replace(Templates.ClassTag, className)
                          .Replace(Templates.NamespaceTag, namespaceData.Classes)
                          .Replace(Templates.InterfaceNamespaceTag, namespaceData.Interfaces))
            .Replace("    ", "\t");
            var parametersSection = new StringBuilder();

            parameters.ForEach(p =>
            {
                var reader = _cSharpClassNameConverter.GetReaderName(p.DataType);
                if (p.DataType == typeof(byte[]))
                {
                    if (p.AllowDBNull)
                    {
                        parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? null : (byte[])reader[{p.ColumnOrdinal}];");
                    }
                    else
                    {
                        parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = (byte[])reader[{p.ColumnOrdinal}];");
                    }
                }
                else if (p.DataType == typeof(int) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (int?)null : reader.{reader}({p.ColumnOrdinal});");
                }
                else if (p.DataType == typeof(short) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (short?)null : reader.{reader}({p.ColumnOrdinal});");
                }
                else if (p.DataType == typeof(long) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (long?)null : reader.{reader}({p.ColumnOrdinal});");
                }
                else if (p.DataType == typeof(DateTime) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (DateTime?)null : reader.{reader}({p.ColumnOrdinal});");
                }
                else if (p.DataType == typeof(bool) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (bool?)null : reader.{reader}({p.ColumnOrdinal});");
                }

                else if (p.DataType == typeof(decimal) && p.AllowDBNull)
                {
                    parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? (decimal?)null : reader.{reader}({p.ColumnOrdinal});");
                }
                else
                {
                    if (p.AllowDBNull)
                    {
                        parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.IsDBNull({p.ColumnOrdinal}) ? null : reader.{reader}({p.ColumnOrdinal});");
                    }
                    else
                    {
                        parametersSection.AppendLine($"\t\t\tresult.{p.ColumnName} = reader.{reader}({p.ColumnOrdinal});");
                    }
                }
            });
            result = result.Replace(Templates.PropertiesTag, parametersSection.ToString());
            return(result.ToString());
        }
Exemple #20
0
 internal NamespaceDefinition(NamespaceData data)
 {
     DebugCorlib.Assert(data != null);
     this.data = data;
 }
        private void PopulateAssemblyNode(TreeNode root, AssemblyDefinition definition)
        {
            // Build collection of all types
            HashSet <TypeDefinition> alltypes = new HashSet <TypeDefinition>(definition.Modules.SelectMany((x) => x.GetTypes()));

            // Sort types into their namespaces
            Dictionary <string, NamespaceData> namespaces = new Dictionary <string, NamespaceData>();
            NamespaceData globalnamespace = new NamespaceData("");

            namespaces.Add("", globalnamespace);
            foreach (TypeDefinition typedef in alltypes)
            {
                NamespaceData nspcdata;
                if (!namespaces.TryGetValue(typedef.Namespace, out nspcdata))
                {
                    nspcdata = new NamespaceData(typedef.Namespace);
                    namespaces.Add(nspcdata.Name, nspcdata);
                }
                if (typedef.Namespace == "")
                {
                    globalnamespace = nspcdata;
                }
                nspcdata.ChildTypes.Add(typedef);
            }

            // Setup namespace hierarchy
            bool done = false;

            while (!done)
            {
                done = true;
                foreach (var pair in namespaces)
                {
                    if (pair.Value.Parent == null && pair.Value != globalnamespace)
                    {
                        if (pair.Key.Contains('.'))
                        {
                            string[] spl  = pair.Key.Split('.');
                            string[] splm = new string[spl.Length - 1];
                            Array.Copy(spl, splm, splm.Length);
                            string        parent = string.Concat(splm);
                            NamespaceData parentnamespace;
                            if (!namespaces.TryGetValue(parent, out parentnamespace))
                            {
                                parentnamespace = new NamespaceData(parent);
                                namespaces.Add(parent, parentnamespace);
                                parentnamespace.ChildNamespaces.Add(pair.Value);
                                pair.Value.Parent = parentnamespace;
                                done = false;
                                break;
                            }
                            parentnamespace.ChildNamespaces.Add(pair.Value);
                            pair.Value.Parent = parentnamespace;
                        }
                        else
                        {
                            globalnamespace.ChildNamespaces.Add(pair.Value);
                            pair.Value.Parent = globalnamespace;
                        }
                    }
                }
            }

            // Populate tree
            PopulateAssemblyNode(root, globalnamespace, true);
        }