Пример #1
0
        public void OneControllers_Returns_OneControllerMetadata()
        {
            var mockControllerDesc = repo.Stub <HttpControllerDescriptor>();

            mockControllerDesc.ControllerName = "Test";

            var mockAction = repo.Stub <HttpActionDescriptor>();

            mockAction.ControllerDescriptor = mockControllerDesc;
            mockAction.ReturnType.Stub(type => typeof(TestReturnType));

            var mockApi = repo.Stub <ApiDescription>();

            mockApi.ActionDescriptor = mockAction;


            var apis = new List <ApiDescription>()
            {
                mockApi
            };
            var factory = new MetadataFactory(apis);

            var meta = factory.CreateMetadata();

            Assert.AreEqual(1, meta.Count(), "metadata items");
        }
Пример #2
0
        public void NoControllers_Returns_EmptyMetadata()
        {
            var apis    = new List <ApiDescription>();
            var factory = new MetadataFactory(apis);

            var meta = factory.CreateMetadata();

            Assert.AreEqual(0, meta.Count(), "metadata items");
        }
Пример #3
0
 public static Metadata TryCreateMetadata(RawModuleBytes moduleData, bool isFileLayout)
 {
     try {
         return(MetadataFactory.CreateMetadata(new PEImage((IntPtr)moduleData.Pointer, (uint)moduleData.Size, isFileLayout ? ImageLayout.File : ImageLayout.Memory, verify: true)));
     }
     catch (IOException) {
     }
     catch (BadImageFormatException) {
     }
     return(null);
 }
Пример #4
0
        /// <summary>
        /// Add a new channel with the given name to the presentation's channel manager.
        /// </summary>
        //sdk2
        //internal Channel AddChannel(string name)
        //{
        //    Channel channel = getChannelFactory().createChannel();
        //    channel.setName(name);
        //    getChannelsManager().addChannel(channel);
        //    return channel;
        //}

        /// <summary>
        /// Convenience method to create a new metadata object with a name/value pair.
        /// Skip it if there is no value (the toolkit doesn't like it.)
        /// </summary>
        private urakawa.metadata.Metadata AddMetadata(string name, string value)
        {
            if (value != null)
            {
                urakawa.metadata.Metadata meta = MetadataFactory.CreateMetadata();
                meta.NameContentAttribute       = new MetadataAttribute();
                meta.NameContentAttribute.Name  = name;
                meta.NameContentAttribute.Value = value;
                AddMetadata(meta);
                return(meta);
            }
            else
            {
                return(null);
            }
        }
Пример #5
0
        static string GetId(byte[] module)
        {
            var md       = MetadataFactory.CreateMetadata(new PEImage(module));
            var assembly = new AssemblyNameInfo();

            if (md.TablesStream.TryReadAssemblyRow(1, out var assemblyRow))
            {
                assembly.Name             = md.StringsStream.ReadNoNull(assemblyRow.Name);
                assembly.Culture          = md.StringsStream.ReadNoNull(assemblyRow.Locale);
                assembly.PublicKeyOrToken = new PublicKey(md.BlobStream.Read(assemblyRow.PublicKey));
                assembly.HashAlgId        = (AssemblyHashAlgorithm)assemblyRow.HashAlgId;
                assembly.Version          = new Version(assemblyRow.MajorVersion, assemblyRow.MinorVersion, assemblyRow.BuildNumber, assemblyRow.RevisionNumber);
                assembly.Attributes       = (AssemblyAttributes)assemblyRow.Flags;
            }
            return(GetId(assembly));
        }
Пример #6
0
        static void InitializeExeFieldsFrom(IPEImage peImage, out bool isExe, out bool isDll, out DateTime?timestamp, ref string version, out string assemblySimpleName)
        {
            isExe = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0;
            isDll = !isExe;

            // Roslyn sets bit 31 if /deterministic is used (the low 31 bits is not a timestamp)
            if (peImage.ImageNTHeaders.FileHeader.TimeDateStamp < 0x80000000 && peImage.ImageNTHeaders.FileHeader.TimeDateStamp != 0)
            {
                timestamp = Epoch.AddSeconds(peImage.ImageNTHeaders.FileHeader.TimeDateStamp);
            }
            else
            {
                timestamp = null;
            }

            try {
                if (string.IsNullOrEmpty(version))
                {
                    using (var mod = ModuleDefMD.Load(peImage)) {
                        if (string.IsNullOrEmpty(version))
                        {
                            version = mod.Assembly?.Version.ToString();
                        }
                        assemblySimpleName = UTF8String.ToSystemString(mod.Assembly?.Name);
                    }
                }
                else
                {
                    using (var md = MetadataFactory.CreateMetadata(peImage)) {
                        if (!md.TablesStream.TryReadAssemblyRow(1, out var row))
                        {
                            assemblySimpleName = null;
                        }
                        else
                        {
                            assemblySimpleName = md.StringsStream.Read(row.Name);
                        }
                    }
                }
            }
            catch {
                assemblySimpleName = null;
            }
        }
Пример #7
0
        private void Check(MetadataFactory sitePlugin)
        {
            var optionsMock = sitePlugin.OptionsMock;

            optionsMock.Setup(s => s.IsUserNameWrapping).Returns(false);

            var options  = optionsMock.Object;
            var userMock = new Mock <IUser>();
            var metadata = sitePlugin.CreateMetadata();

            //変更前
            Assert.IsFalse(metadata.IsNameWrapping);

            //変更
            optionsMock.Setup(s => s.IsUserNameWrapping).Returns(true);

            //変更通知
            optionsMock.Raise(o => o.PropertyChanged += null, new PropertyChangedEventArgs(nameof(options.IsUserNameWrapping)));

            //テスト
            Assert.IsTrue(metadata.IsNameWrapping);
        }
Пример #8
0
        public void NGユーザに指定されたら非表示になる(MetadataFactory sitePlugin)
        {
            var optionsMock = new Mock <ICommentOptions>();
            var userMock    = new Mock <IUser>();

            var options   = optionsMock.Object;
            var user      = userMock.Object;
            var metadata  = sitePlugin.CreateMetadata(options, user);
            var isVisible = true;

            metadata.PropertyChanged += (s, e) =>
            {
                switch (e.PropertyName)
                {
                case nameof(metadata.IsVisible):
                    isVisible = metadata.IsVisible;
                    break;
                }
            };
            //NGユーザに指定されたら非表示になる
            userMock.Setup(u => u.IsNgUser).Returns(true);
            userMock.Raise(c => c.PropertyChanged += null, new PropertyChangedEventArgs(nameof(user.IsNgUser)));
            Assert.IsFalse(isVisible);
        }
Пример #9
0
        static DmdEcma335MetadataReader Create(DmdModuleImpl module, IPEImage peImage)
        {
            var metadata = MetadataFactory.CreateMetadata(peImage);

            return(new DmdEcma335MetadataReader(module, metadata));
        }
Пример #10
0
        public override bool Execute()
        {
            if (string.IsNullOrWhiteSpace(IVTString))
            {
                Log.LogMessageFromText(nameof(IVTString) + " is an empty string", MessageImportance.High);
                return(false);
            }

            if (string.IsNullOrWhiteSpace(DestinationDirectory))
            {
                Log.LogMessageFromText(nameof(DestinationDirectory) + " is an empty string", MessageImportance.High);
                return(false);
            }

            var assembliesToFix = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var tmp in AssembliesToMakePublic.Split(';'))
            {
                var asmName       = tmp.Trim();
                var asmSimpleName = asmName;
                int index         = asmSimpleName.IndexOf(',');
                if (index >= 0)
                {
                    asmSimpleName = asmSimpleName.Substring(0, index).Trim();
                }
                if (asmSimpleName.Length == 0)
                {
                    continue;
                }
                assembliesToFix.Add(asmSimpleName);
            }

            OutputReferencePath = new ITaskItem[ReferencePath.Length];
            byte[] ivtBlob = null;
            for (int i = 0; i < ReferencePath.Length; i++)
            {
                var file = ReferencePath[i];
                OutputReferencePath[i] = file;
                var filename      = file.ItemSpec;
                var fileExt       = Path.GetExtension(filename);
                var asmSimpleName = Path.GetFileNameWithoutExtension(filename);
                if (!assembliesToFix.Contains(asmSimpleName))
                {
                    continue;
                }
                if (!File.Exists(filename))
                {
                    Log.LogMessageFromText($"File does not exist: {filename}", MessageImportance.High);
                    return(false);
                }

                var patchDir = DestinationDirectory;
                Directory.CreateDirectory(patchDir);

                var  fileInfo  = new FileInfo(filename);
                long filesize  = fileInfo.Length;
                long writeTime = fileInfo.LastWriteTimeUtc.ToBinary();

                var extraInfo       = $"_{VERSION} {filesize} {writeTime}_";
                var patchedFilename = Path.Combine(patchDir, asmSimpleName + extraInfo + fileExt);
                if (StringComparer.OrdinalIgnoreCase.Equals(patchedFilename, filename))
                {
                    continue;
                }

                if (!File.Exists(patchedFilename))
                {
                    if (ivtBlob == null)
                    {
                        ivtBlob = CreateIVTBlob(IVTString);
                    }
                    var data = File.ReadAllBytes(filename);
                    try {
                        using (var peImage = new PEImage(data, filename, ImageLayout.File, verify: true)) {
                            using (var md = MetadataFactory.CreateMetadata(peImage, verify: true)) {
                                var result = new IVTPatcher(data, md, ivtBlob).Patch();
                                if (result != IVTPatcherResult.OK)
                                {
                                    string errMsg;
                                    switch (result)
                                    {
                                    case IVTPatcherResult.NoCustomAttributes:
                                        errMsg = $"Assembly '{asmSimpleName}' has no custom attributes";
                                        break;

                                    case IVTPatcherResult.NoIVTs:
                                        errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttributes";
                                        break;

                                    case IVTPatcherResult.IVTBlobTooSmall:
                                        errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttribute blob that is big enough to store '{IVTString}'. Use a shorter assembly name and/or a shorter public key, or skip PublicKey=xxxx... altogether (if it's a C# assembly)";
                                        break;

                                    default:
                                        Debug.Fail($"Unknown error result: {result}");
                                        errMsg = "Unknown error";
                                        break;
                                    }
                                    Log.LogMessageFromText(errMsg, MessageImportance.High);
                                    return(false);
                                }
                                try {
                                    File.WriteAllBytes(patchedFilename, data);
                                }
                                catch {
                                    try { File.Delete(patchedFilename); } catch { }
                                    throw;
                                }
                            }
                        }
                    }
                    catch (Exception ex) when(ex is IOException || ex is BadImageFormatException)
                    {
                        Log.LogMessageFromText($"File '{filename}' is not a .NET file", MessageImportance.High);
                        return(false);
                    }

                    var xmlDocFile = Path.ChangeExtension(filename, "xml");
                    if (File.Exists(xmlDocFile))
                    {
                        var newXmlDocFile = Path.ChangeExtension(patchedFilename, "xml");
                        if (File.Exists(newXmlDocFile))
                        {
                            File.Delete(newXmlDocFile);
                        }
                        File.Copy(xmlDocFile, newXmlDocFile);
                    }
                }

                OutputReferencePath[i] = new TaskItem(patchedFilename);
            }

            return(true);
        }