GetPublicKeyToken() public method

public GetPublicKeyToken ( ) : byte[]
return byte[]
        private void RoundTrip(AssemblyName name, bool testFullName = true)
        {
            AssemblyName rtName;
            FusionAssemblyIdentity.IAssemblyName obj;

            if (testFullName)
            {
                string fullName = name.FullName;

                obj = FusionAssemblyIdentity.ToAssemblyNameObject(fullName);
                rtName = ToAssemblyName(obj);
                Assert.Equal(name.Name, rtName.Name);
                Assert.Equal(name.Version, rtName.Version);
                Assert.Equal(name.CultureInfo, rtName.CultureInfo);
                Assert.Equal(name.GetPublicKeyToken(), rtName.GetPublicKeyToken());
                Assert.Equal(name.Flags, rtName.Flags);
                Assert.Equal(name.ContentType, rtName.ContentType);

                string displayName = FusionAssemblyIdentity.GetDisplayName(obj, FusionAssemblyIdentity.ASM_DISPLAYF.FULL);
                Assert.Equal(fullName, displayName);
            }

            obj = FusionAssemblyIdentity.ToAssemblyNameObject(name);
            rtName = ToAssemblyName(obj);
            Assert.Equal(name.Name, rtName.Name);
            Assert.Equal(name.Version, rtName.Version);
            Assert.Equal(name.CultureInfo, rtName.CultureInfo);
            Assert.Equal(name.GetPublicKeyToken(), rtName.GetPublicKeyToken());
            Assert.Equal(name.Flags, rtName.Flags);
            Assert.Equal(name.ContentType, rtName.ContentType);
        }
Exemplo n.º 2
0
        private static IEnumerable<Assembly> FilterOnPkt(IEnumerable<Assembly> assemblies, AssemblyName assmName)
        {
            if (assmName.GetPublicKeyToken() != null)
            {
                var r = assemblies.Where(a => a.GetName().GetPublicKeyToken().SequenceEqual(assmName.GetPublicKeyToken()));
                if (!r.Any())
                    return assemblies;
                else
                    return r;
            }

            return assemblies;
        }
Exemplo n.º 3
0
        static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (!args.Name.StartsWith(prefix))
                return null;

            var name = new AssemblyName(args.Name.Substring(prefix.Length));
            if (name.GetPublicKeyToken() != null && name.GetPublicKeyToken().Length > 0)
                return null;
            name.SetPublicKeyToken(publicKeyToken);
            name.Version = vsVersion;
            Debug.WriteLine("Ref12: Redirecting load of " + args.Name + ",\tfrom " + (args.RequestingAssembly == null ? "(unknown)" : args.RequestingAssembly.FullName));

            return Assembly.Load(name);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Returns pregenerated interop code for given PInvoke method if one exist
        /// </summary>
        public static MethodDesc TryGetPregeneratedPInvoke(MethodDesc method)
        {
            Debug.Assert(method.IsPInvoke);

            var metadataType = (MetadataType)method.OwningType;
            var module = metadataType.Module;

            var assemblyName = ((IAssemblyDesc)module).GetName();

            var interopAssemblyName = new AssemblyName();

            interopAssemblyName.Name = assemblyName.Name + AssemblyNameSuffix;
            interopAssemblyName.Version = assemblyName.Version;
            interopAssemblyName.SetPublicKeyToken(interopAssemblyName.GetPublicKeyToken());
            interopAssemblyName.CultureName = assemblyName.CultureName;
            interopAssemblyName.ContentType = assemblyName.ContentType;

            var interopModule = module.Context.ResolveAssembly(interopAssemblyName, false);
            if (interopModule == null)
                return null;

            var pregeneratedMethod = GetMatchingMethod(interopModule, method);
            if (pregeneratedMethod == null)
            {
                // TODO: Better error message
                throw new MissingMemberException("Missing method in " + interopAssemblyName.Name + ":" + method.ToString());
            }
            return pregeneratedMethod;
        }
Exemplo n.º 5
0
        public void AddName(AssemblyName name)
        {
            ListViewItem item = new ListViewItem(name.Name);

            item.SubItems.Add(name.Version.ToString());

            StringBuilder builder = new StringBuilder();

            byte[] publicKey = name.GetPublicKeyToken();

            if (publicKey == null)
            {
                item.SubItems.Add("null");
            }
            else
            {
                foreach (byte b in publicKey)
                {
                    builder.AppendFormat("{0:X02}", b);
                }
                item.SubItems.Add(builder.ToString());
            }

            item.Tag = name;

            Items.Add(item);
        }
 internal static bool AssemblyQualifiedNameEquals(Type t1, Type t2)
 {
     if (object.ReferenceEquals(t1, null))
     {
         return object.ReferenceEquals(t2, null);
     }
     if (object.ReferenceEquals(t2, null))
     {
         return false;
     }
     if (t1.FullName != t2.FullName)
     {
         return false;
     }
     if (t1.Assembly.FullName == t2.Assembly.FullName)
     {
         return true;
     }
     AssemblyName name = new AssemblyName(t1.Assembly.FullName);
     AssemblyName name2 = new AssemblyName(t2.Assembly.FullName);
     if (!(name.Name == name2.Name))
     {
         return IsWindowsBaseToSystemXamlComparison(t1.Assembly, t2.Assembly, name, name2);
     }
     return (name.CultureInfo.Equals(name2.CultureInfo) && SafeSecurityHelper.IsSameKeyToken(name.GetPublicKeyToken(), name2.GetPublicKeyToken()));
 }
Exemplo n.º 7
0
 internal static bool PublicKeyMatches(System.Reflection.AssemblyName a1, byte[] publicKeyOrToken)
 {
     if (publicKeyOrToken == null)
     {
         return(a1.GetPublicKey() == null);
     }
     byte[] publicKey = a1.GetPublicKey();
     if (publicKey != null && publicKeyOrToken.Length == publicKey.Length)
     {
         for (int i = 0; i < publicKey.Length; i++)
         {
             if (publicKey[i] != publicKeyOrToken[i])
             {
                 return(false);
             }
         }
         return(true);
     }
     byte[] publicKeyToken = a1.GetPublicKeyToken();
     if (publicKeyOrToken.Length == publicKeyToken.Length)
     {
         for (int i = 0; i < publicKeyToken.Length; i++)
         {
             if (publicKeyToken[i] != publicKeyOrToken[i])
             {
                 return(false);
             }
         }
         return(true);
     }
     return(false);
 }
Exemplo n.º 8
0
 public void SetAssemblyName(AssemblyName assemblyName)
 {
     Name = assemblyName.Name;
     Version = assemblyName.Version.ToString();
     Culture = (assemblyName.CultureInfo == null) ? string.Empty : assemblyName.CultureInfo.Name;
     PublicKeyToken = ToHexString(assemblyName.GetPublicKeyToken());
     ProcessorArchitecture = assemblyName.ProcessorArchitecture;
 }
Exemplo n.º 9
0
		public MonoAssemblyName(string name, string directory)
		{
			AssemblyName assemblyName = new AssemblyName(name);
			this.name = assemblyName.Name;
			version = assemblyName.Version;
			cultureInfo = assemblyName.CultureInfo;
			publicKeyToken = assemblyName.GetPublicKeyToken();
			this.directory = directory;
		}
Exemplo n.º 10
0
 protected string LookupFullName(string name)
 {
     AssemblyName asm = new AssemblyName(name);
     if (asm.Version != null || asm.GetPublicKeyToken() != null || asm.GetPublicKey() != null)
     {
         return name;
     }
     return _assemblyFullNames.ContainsKey(name.ToLower()) ? _assemblyFullNames[name.ToLower()] : name;
 }
 internal static bool AssemblyNameEquals(AssemblyName thisName, AssemblyName thatName)
 {
     if ((thisName.Name == null) || (thatName.Name == null))
     {
         return false;
     }
     if (!thatName.Name.Equals(thisName.Name))
     {
         return false;
     }
     Version version = thatName.Version;
     if (((version != null) && (version != emptyVersion)) && (version != thisName.Version))
     {
         return false;
     }
     CultureInfo cultureInfo = thatName.CultureInfo;
     if ((cultureInfo != null) && !cultureInfo.Equals(CultureInfo.InvariantCulture))
     {
         CultureInfo parent = thisName.CultureInfo;
         if (parent == null)
         {
             return false;
         }
         while (!cultureInfo.Equals(parent))
         {
             parent = parent.Parent;
             if (parent.Equals(CultureInfo.InvariantCulture))
             {
                 return false;
             }
         }
     }
     byte[] publicKeyToken = thatName.GetPublicKeyToken();
     if ((publicKeyToken != null) && (publicKeyToken.Length != 0))
     {
         byte[] buffer2 = thisName.GetPublicKeyToken();
         if (buffer2 == null)
         {
             return false;
         }
         if (publicKeyToken.Length != buffer2.Length)
         {
             return false;
         }
         for (int i = 0; i < publicKeyToken.Length; i++)
         {
             if (publicKeyToken[i] != buffer2[i])
             {
                 return false;
             }
         }
     }
     return true;
 }
Exemplo n.º 12
0
        private static bool TryRedirect(AssemblyName name, byte[] token, int major, int minor, int revision, int build)
        {
            var version = new Version(major, minor, revision, build);
            if (KeysEqual(name.GetPublicKeyToken(), token) && name.Version < version)
            {
                name.Version = version;
                return true;
            }

            return false;
        }
Exemplo n.º 13
0
 internal AssemblyLoader(TypeProvider typeProvider, string filePath)
 {
     this.isLocalAssembly = false;
     this.typeProvider    = typeProvider;
     if (!File.Exists(filePath))
     {
         throw new FileNotFoundException();
     }
     System.Reflection.AssemblyName assemblyName = System.Reflection.AssemblyName.GetAssemblyName(filePath);
     if (assemblyName != null)
     {
         ITypeResolutionService service = (ITypeResolutionService)typeProvider.GetService(typeof(ITypeResolutionService));
         if (service != null)
         {
             try
             {
                 this.assembly = service.GetAssembly(assemblyName);
                 if ((((this.assembly == null) && (assemblyName.GetPublicKeyToken() != null)) && ((assemblyName.GetPublicKeyToken().GetLength(0) == 0) && (assemblyName.GetPublicKey() != null))) && (assemblyName.GetPublicKey().GetLength(0) == 0))
                 {
                     System.Reflection.AssemblyName name = (System.Reflection.AssemblyName)assemblyName.Clone();
                     name.SetPublicKey(null);
                     name.SetPublicKeyToken(null);
                     this.assembly = service.GetAssembly(name);
                 }
             }
             catch
             {
             }
         }
         if (this.assembly == null)
         {
             try
             {
                 if (MultiTargetingInfo.MultiTargetingUtilities.IsFrameworkReferenceAssembly(filePath))
                 {
                     this.assembly = System.Reflection.Assembly.Load(assemblyName.FullName);
                 }
                 else
                 {
                     this.assembly = System.Reflection.Assembly.Load(assemblyName);
                 }
             }
             catch
             {
             }
         }
     }
     if (this.assembly == null)
     {
         this.assembly = System.Reflection.Assembly.LoadFrom(filePath);
     }
 }
Exemplo n.º 14
0
        static SR.AssemblyName GetPlatformSymbolAssemblyName()
        {
            var cecil_name = new System.Reflection.AssemblyName(typeof(SymbolProvider).Assembly.FullName);

            var name = new SR.AssemblyName {
                Name    = "Mi.Assemblies." + symbol_kind,
                Version = cecil_name.Version,
            };

            name.SetPublicKeyToken(cecil_name.GetPublicKeyToken());

            return(name);
        }
 public DefinitionIdentity(AssemblyName asmName)
 {
     this._idComPtr = System.Deployment.Internal.Isolation.IsolationInterop.IdentityAuthority.CreateDefinition();
     this["name"] = asmName.Name;
     this["version"] = asmName.Version.ToString();
     if (asmName.CultureInfo != null)
     {
         this["culture"] = asmName.CultureInfo.Name;
     }
     byte[] publicKeyToken = asmName.GetPublicKeyToken();
     if ((publicKeyToken != null) && (publicKeyToken.Length > 0))
     {
         this["publicKeyToken"] = HexString.FromBytes(publicKeyToken);
     }
 }
        public AssemblyNameReference ImportAssembly(SR.Assembly asm)
        {
            AssemblyNameReference asmRef = GetAssemblyNameReference(asm.GetName());

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

            SR.AssemblyName asmName = asm.GetName();
            asmRef = new AssemblyNameReference(
                asmName.Name, asmName.CultureInfo.Name, asmName.Version);
            asmRef.PublicKeyToken = asmName.GetPublicKeyToken();
            asmRef.HashAlgorithm  = (AssemblyHashAlgorithm)asmName.HashAlgorithm;
            asmRef.Culture        = asmName.CultureInfo.ToString();
            m_module.AssemblyReferences.Add(asmRef);
            return(asmRef);
        }
Exemplo n.º 17
0
			int IComparer.Compare(object lhs, object rhs)
			{
				AssemblyName assemblyName = new AssemblyName((string)lhs);
				AssemblyName assemblyName2 = (AssemblyName)rhs;
				int num = string.Compare(assemblyName.Name, assemblyName2.Name, StringComparison.OrdinalIgnoreCase);
				if (num != 0)
				{
					return num;
				}
				byte[] publicKeyToken = assemblyName.GetPublicKeyToken();
				byte[] publicKeyToken2 = assemblyName2.GetPublicKeyToken();
				if (publicKeyToken == null)
				{
					return -1;
				}
				if (publicKeyToken2 == null)
				{
					return 1;
				}
				if (publicKeyToken.Length < publicKeyToken2.Length)
				{
					return -1;
				}
				if (publicKeyToken.Length > publicKeyToken2.Length)
				{
					return 1;
				}
				for (int i = 0; i < publicKeyToken.Length; i++)
				{
					byte b = publicKeyToken[i];
					byte b2 = publicKeyToken2[i];
					if (b < b2)
					{
						return -1;
					}
					if (b > b2)
					{
						return 1;
					}
				}
				return 0;
			}
Exemplo n.º 18
0
        public override Assembly Resolve(MetadataLoadContext context, AssemblyName assemblyName)
        {
            Assembly candidateWithSamePkt = null;
            Assembly candidateIgnoringPkt = null;

            if (_fileToPaths.TryGetValue(assemblyName.Name, out List <string> paths))
            {
                ReadOnlySpan <byte> pktFromName = assemblyName.GetPublicKeyToken();

                foreach (string path in paths)
                {
                    Assembly     assemblyFromPath     = context.LoadFromAssemblyPath(path);
                    AssemblyName assemblyNameFromPath = assemblyFromPath.GetName();
                    if (assemblyName.Name.Equals(assemblyNameFromPath.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        ReadOnlySpan <byte> pktFromAssembly = assemblyNameFromPath.GetPublicKeyToken();

                        // Find exact match on PublicKeyToken including treating no PublicKeyToken as its own entry.
                        if (pktFromName.SequenceEqual(pktFromAssembly))
                        {
                            // Pick the highest version.
                            if (candidateWithSamePkt == null || assemblyNameFromPath.Version > candidateWithSamePkt.GetName().Version)
                            {
                                candidateWithSamePkt = assemblyFromPath;
                            }
                        }
                        // If assemblyName does not specify a PublicKeyToken, then still consider those with a PublicKeyToken.
                        else if (candidateWithSamePkt == null && pktFromName.IsEmpty)
                        {
                            // Pick the highest version.
                            if (candidateIgnoringPkt == null || assemblyNameFromPath.Version > candidateIgnoringPkt.GetName().Version)
                            {
                                candidateIgnoringPkt = assemblyFromPath;
                            }
                        }
                    }
                }
            }

            return(candidateWithSamePkt ?? candidateIgnoringPkt);
        }
        public AssemblyNameReference ImportAssembly(SR.Assembly asm)
        {
            ImportCache();

            AssemblyNameReference asmRef = (AssemblyNameReference)m_asmCache [asm.FullName];

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

            SR.AssemblyName asmName = asm.GetName();
            asmRef = new AssemblyNameReference(
                asmName.Name, asmName.CultureInfo.Name, asmName.Version);
            asmRef.PublicKeyToken = asmName.GetPublicKeyToken();
            asmRef.HashAlgorithm  = (Mono.Cecil.AssemblyHashAlgorithm)asmName.HashAlgorithm;
            asmRef.Culture        = asmName.CultureInfo.ToString();
            m_module.AssemblyReferences.Add(asmRef);
            m_asmCache [asm.FullName] = asmRef;
            return(asmRef);
        }
Exemplo n.º 20
0
        bool TryGetAssemblyNameReference(SR.AssemblyName name, out AssemblyNameReference assembly_reference)
        {
            var references = module.AssemblyReferences;

            var pkt = name.GetPublicKeyToken();

            for (int i = 0; i < references.Count; i++)
            {
                var reference = references [i];
                if (name.Name != reference.Name || (pkt != null && pkt.Equals(reference.PublicKeyToken)))                 // TODO compare field by field
                {
                    continue;
                }

                assembly_reference = reference;
                return(true);
            }

            assembly_reference = null;
            return(false);
        }
Exemplo n.º 21
0
        public virtual AssemblyNameReference ImportReference(SR.AssemblyName name)
        {
            Mixin.CheckName(name);

            AssemblyNameReference reference;

            if (TryGetAssemblyNameReference(name, out reference))
            {
                return(reference);
            }

            reference = new AssemblyNameReference(name.Name, name.Version)
            {
                PublicKeyToken = name.GetPublicKeyToken(),
                Culture        = name.CultureInfo.Name,
                HashAlgorithm  = (AssemblyHashAlgorithm)name.HashAlgorithm,
            };

            module.AssemblyReferences.Add(reference);

            return(reference);
        }
        private bool AreWeReferringToTheSameAssembly(AssemblyName simple, AssemblyName fullyQualified)
        {
            var result = simple.Name == fullyQualified.Name;
            if (simple.Version != null)
                result &= simple.Version <= fullyQualified.Version;
            if (simple.ProcessorArchitecture != ProcessorArchitecture.None)
            {
                result &= simple.ProcessorArchitecture == fullyQualified.ProcessorArchitecture;
            }

            if (simple.CultureInfo != null)
            {
                result &= simple.CultureInfo.Equals(fullyQualified.CultureInfo);
            }

            if (simple.GetPublicKeyToken() != null)
            {
                result &= simple.GetPublicKeyToken().SequenceEqual(fullyQualified.GetPublicKeyToken());
            }

            return result;
        }
        /// <summary>
        /// Matches the name of <paramref name="assembly"/> with <paramref name="assemblyNameToMatch"/>.
        /// </summary>
        /// <param name="assembly">The assembly to match.</param>
        /// <param name="assemblyNameToMatch">The assembly name to match.</param>
        /// <returns><see langword="true"/> if the name matches; otherwise <see langword="false"/>.</returns>
        public static bool Matches(Assembly assembly, AssemblyName assemblyNameToMatch)
        {
            if (assembly == null) return false;
            if (assemblyNameToMatch == null) return false;

            var assemblyName = assembly.GetName();

            if (assemblyName.Name == assemblyNameToMatch.Name)
            {
                if (assemblyNameToMatch.Version != null &&
                    assemblyNameToMatch.Version.CompareTo(assemblyName.Version) != 0)
                {
                    return false;
                }
                byte[] requestedAsmPublicKeyToken = assemblyNameToMatch.GetPublicKeyToken();
                if (requestedAsmPublicKeyToken != null)
                {
                    byte[] cachedAssemblyPublicKeyToken = assemblyName.GetPublicKeyToken();

                    if (Convert.ToBase64String(requestedAsmPublicKeyToken) != Convert.ToBase64String(cachedAssemblyPublicKeyToken))
                    {
                        return false;
                    }
                }

                var requestedAssemblyCulture = assemblyNameToMatch.CultureInfo;
                if (requestedAssemblyCulture != null && requestedAssemblyCulture.LCID != CultureInfo.InvariantCulture.LCID)
                {
                    if (assemblyName.CultureInfo.LCID != requestedAssemblyCulture.LCID)
                    {
                        return false;
                    }
                }

                return true;
            }

            return false;
        }
Exemplo n.º 24
0
        public virtual AssemblyNameReference ImportReference(SR.AssemblyName name)
        {
            Root.Code.Libs.Mono.Cecil.Mixin.CheckName(name);

            AssemblyNameReference reference;

            if (TryGetAssemblyNameReference(name, out reference))
            {
                return(reference);
            }

            reference = new AssemblyNameReference(name.Name, name.Version)
            {
                PublicKeyToken = name.GetPublicKeyToken(),
#if !NET_CORE
                Culture       = name.CultureInfo.Name,
                HashAlgorithm = (AssemblyHashAlgorithm)name.HashAlgorithm,
#endif
            };

            module.AssemblyReferences.Add(reference);

            return(reference);
        }
Exemplo n.º 25
0
        public void PrintAssembly(SysRef.AssemblyName assembly)
        {
            _builder.Append(assembly.Name);

            if ((_flags & SignaturePrintingFlags.IgnoreAssemblyStrongName) != SignaturePrintingFlags.IgnoreAssemblyStrongName)
            {
                bool ignoreDefaultValues = (_flags & SignaturePrintingFlags.IgnoreAssemblyStrongNameDefaultValues) == SignaturePrintingFlags.IgnoreAssemblyStrongNameDefaultValues;

                // Version
                if (assembly.Version != null)
                {
                    _builder.AppendFormat(", Version={0}", assembly.Version.ToString());
                }
                else if (!ignoreDefaultValues)
                {
                    _builder.Append(", Version=0.0.0.0");
                }

                // Culture
                var culture = assembly.CultureInfo;
                if (culture != null)
                {
                    _builder.AppendFormat(", Culture={0}", culture.Name);
                }
                else if (!ignoreDefaultValues)
                {
                    _builder.Append(", Culture=neutral");
                }

                // PublicKeyToken
                var publicKeyToken = assembly.GetPublicKeyToken();
                if (publicKeyToken != null && publicKeyToken.Length > 0)
                {
                    _builder.AppendFormat(", PublicKeyToken={0}", ConvertUtils.ToHexString(publicKeyToken).ToLower());
                }
                else if (!ignoreDefaultValues)
                {
                    _builder.Append(", PublicKeyToken=null");
                }

                // ProcessorArchitecture
                string procArchString;
                switch (assembly.ProcessorArchitecture)
                {
                case SysRef.ProcessorArchitecture.MSIL:
                    procArchString = "msil";
                    break;

                case SysRef.ProcessorArchitecture.X86:
                    procArchString = "x86";
                    break;

                case SysRef.ProcessorArchitecture.Amd64:
                    procArchString = "amd64";
                    break;

                case SysRef.ProcessorArchitecture.IA64:
                    procArchString = "ia64";
                    break;

                default:
                    procArchString = null;
                    break;
                }

                if (procArchString != null)
                {
                    _builder.AppendFormat(", ProcessorArchitecture={0}", procArchString);
                }
            }
        }
Exemplo n.º 26
0
		// modified copy from sn
		private static VerificationResult VerifyStrongName (AssemblyName an, string assemblyFile)
		{
			byte [] publicKey = StrongNameManager.GetMappedPublicKey (an.GetPublicKeyToken ());
			if ((publicKey == null) || (publicKey.Length < 12)) {
				// no mapping
				publicKey = an.GetPublicKey ();
				if ((publicKey == null) || (publicKey.Length < 12))
					return VerificationResult.WeakNamed;
			}

			// Note: MustVerify is based on the original token (by design). Public key
			// remapping won't affect if the assembly is verified or not.
			if (StrongNameManager.MustVerify (an)) {
				RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
				StrongName sn = new StrongName (rsa);
				if (sn.Verify (assemblyFile)) {
					return VerificationResult.StrongNamed;
				} else {
					return VerificationResult.DelaySigned;
				}
			} else {
				return VerificationResult.Skipped;
			}
		}
Exemplo n.º 27
0
        /// <summary>
        /// Determins whether the name, culture, and public key token of the given assembly name "suggestedRedirect"
        /// matches the name, culture, and publicKeyToken strings.
        /// </summary>
        private static bool IsMatch(AssemblyName suggestedRedirect, string name, string culture, string publicKeyToken)
        {
            if (String.Compare(suggestedRedirect.Name, name, StringComparison.OrdinalIgnoreCase) != 0)
            {
                return false;
            }

            if (ByteArrayMatchesString(suggestedRedirect.GetPublicKeyToken(), publicKeyToken))
            {
                return false;
            }

            // The binding redirect will be applied if the culture is missing from the "assemblyIdentity" node.
            // So we consider it a match if the existing binding redirect doesn't have culture specified.
            var cultureString = suggestedRedirect.CultureName;
            if (String.IsNullOrEmpty(cultureString))
            {
                // We use "neutral" for "Invariant Language (Invariant Country)" in assembly names.
                cultureString = "neutral";
            }

            if (!String.IsNullOrEmpty(culture) &&
                String.Compare(cultureString, culture, StringComparison.OrdinalIgnoreCase) != 0)
            {
                return false;
            }

            return true;
        }
 public void Case8_SetPublicKeyToken()
 {
     AssemblyName n = new AssemblyName();
     n.SetPublicKeyToken(null);
     Assert.Null(n.GetPublicKeyToken());
 }
Exemplo n.º 29
0
        // IGNORES VERSION
        internal static bool CompareNames(String asmTypeName1,
                                          String typeName2, 
                                          AssemblyName asmName2)
        {
            Contract.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");

            // First, compare type names
            int comma = asmTypeName1.IndexOf(',');
            if (((comma == -1) ? asmTypeName1.Length : comma) != typeName2.Length)
                return false;

            // case sensitive
            if (String.Compare(asmTypeName1, 0, typeName2, 0, typeName2.Length, StringComparison.Ordinal) != 0)
                return false;
            if (comma == -1)
                return true;

            // Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE)
            // also, for  mscorlib ignores everything, since that's what the binder is going to do
            while(Char.IsWhiteSpace(asmTypeName1[++comma]));

            // case insensitive
            AssemblyName an1 = new AssemblyName(asmTypeName1.Substring(comma));
            if (String.Compare(an1.Name, asmName2.Name, StringComparison.OrdinalIgnoreCase) != 0)
                return false;

            // to match IsMscorlib() in VM
            if (String.Compare(an1.Name, "mscorlib", StringComparison.OrdinalIgnoreCase) == 0)
                return true;


            if ((an1.CultureInfo != null) && (asmName2.CultureInfo != null) &&
#if FEATURE_USE_LCID                
                (an1.CultureInfo.LCID != asmName2.CultureInfo.LCID)
#else
                (an1.CultureInfo.Name != asmName2.CultureInfo.Name)
#endif                
                )
                return false;

            byte[] pkt1 = an1.GetPublicKeyToken();
            byte[] pkt2 = asmName2.GetPublicKeyToken();
            if ((pkt1 != null) && (pkt2 != null)) {
                if (pkt1.Length != pkt2.Length)
                    return false;

                for(int i=0; i < pkt1.Length; i++) {
                    if(pkt1[i] != pkt2[i])
                        return false;
                }
            }

            return true;
        }
Exemplo n.º 30
0
            int IComparer.Compare(object /*string*/lhs, object /*AssemblyName*/rhs)
            {
                AssemblyName captcaEntry = new AssemblyName((string)lhs);
                AssemblyName comparand = (AssemblyName)rhs;
                int nameComp = string.Compare(captcaEntry.Name,
                                              comparand.Name,
                                              StringComparison.OrdinalIgnoreCase);
                if (nameComp != 0)
                {
                    return nameComp;
                }

                //simple names match.  Compare public key tokens.
                byte[] lhsKey = captcaEntry.GetPublicKeyToken();
                byte[] rhsKey = comparand.GetPublicKeyToken();

                // We require both sides have a public key token
                if (lhsKey == null)
                {
                    return -1;
                }
                if (rhsKey == null)
                {
                    return 1;
                }
                if (lhsKey.Length < rhsKey.Length)
                {
                    return -1;
                }
                if (lhsKey.Length > rhsKey.Length)
                {
                    return 1;
                }

                // Tokens seem valid - make sure the compare correctly
                for (int i = 0; i < lhsKey.Length; ++i)
                {
                    byte lhsByte = lhsKey[i];
                    byte rhsByte = rhsKey[i];

                    if (lhsByte < rhsByte)
                    {
                        return -1;
                    }
                    if (lhsByte > rhsByte)
                    {
                        return 1;
                    }
                }

                //They match.
                return 0;
            }
Exemplo n.º 31
0
 public string ApplyPolicy(string assemblyName)
 {
     AssemblyName an = new AssemblyName(assemblyName);
     byte[] publicKeyToken = an.GetPublicKeyToken();
     if (publicKeyToken == null)
     {
         publicKeyToken = an.GetPublicKey();
     }
     if ((publicKeyToken != null) && (publicKeyToken.Length != 0))
     {
         return this.nApplyPolicy(an);
     }
     return assemblyName;
 }
Exemplo n.º 32
0
	//
	// Checks whether `invocationAssembly' is same or a friend of the assembly
	//
	public static bool IsThisOrFriendAssembly (Assembly invocationAssembly, Assembly assembly)
	{
		if (assembly == null)
			throw new ArgumentNullException ("assembly");

		// TODO: This can happen for constants used at assembly level and
		// predefined members
		// But there is no way to test for it for now, so it could be abused
		// elsewhere too.
		if (invocationAssembly == null)
			invocationAssembly = CodeGen.Assembly.Builder;

		if (invocationAssembly == assembly)
			return true;

		bool value;
		if (assembly_internals_vis_attrs.TryGetValue (assembly, out value))
			return value;

		object[] attrs = assembly.GetCustomAttributes (typeof (InternalsVisibleToAttribute), false);
		if (attrs.Length == 0) {
			assembly_internals_vis_attrs.Add (assembly, false);
			return false;
		}

		bool is_friend = false;

		AssemblyName this_name = CodeGen.Assembly.Name;
		if (this_name == null)
			return false;

		byte [] this_token = this_name.GetPublicKeyToken ();
		foreach (InternalsVisibleToAttribute attr in attrs) {
			if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
				continue;
			
			AssemblyName aname = null;
			try {
				aname = new AssemblyName (attr.AssemblyName);
			} catch (FileLoadException) {
			} catch (ArgumentException) {
			}

			if (aname == null || aname.Name != this_name.Name)
				continue;
			
			byte [] key_token = aname.GetPublicKeyToken ();
			if (key_token != null) {
				if (this_token.Length == 0) {
					// Same name, but assembly is not strongnamed
					Error_FriendAccessNameNotMatching (aname.FullName, RootContext.ToplevelTypes.Compiler.Report);
					break;
				}
				
				if (!CompareKeyTokens (this_token, key_token))
					continue;
			}

			is_friend = true;
			break;
		}

		assembly_internals_vis_attrs.Add (assembly, is_friend);
		return is_friend;
	}
Exemplo n.º 33
0
        /// <summary>
        /// Processes those AllAssemblies.Xml entries that are our own product assemblies.
        /// </summary>
        private int ProcessAssemblies(Directory wixDirectory, ComponentGroup wixComponentGroup, Component wixComponentRegistry, AllAssembliesXml allassembliesxml, Dictionary <string, string> mapTargetFiles, GuidCacheXml guidcachexml)
        {
            // Collect the assemblies
            int nGeneratedComponents = 0;

            foreach (ItemGroupXml group in allassembliesxml.ItemGroup)
            {
                if (group.AllAssemblies == null)
                {
                    continue;
                }
                foreach (AssemblyXml assemblyxml in group.AllAssemblies)
                {
                    nGeneratedComponents++;
                    FileInfo fiAssembly = FindAssemblyFile(assemblyxml);
                    string   sExtension = fiAssembly.Extension.TrimStart('.');                   // The extension without a dot

                    // Create the component for the assembly (one per assembly)
                    var wixComponent = new Component();
                    wixDirectory.AddChild(wixComponent);
                    wixComponent.Id       = string.Format("{0}.{1}.{2}", FileComponentIdPrefix, assemblyxml.Include, sExtension);
                    wixComponent.Guid     = assemblyxml.MsiGuid;
                    wixComponent.DiskId   = Bag.Get <int>(AttributeName.DiskId);
                    wixComponent.Location = Component.LocationType.local;

                    // Register component in the group
                    var componentref = new ComponentRef();
                    wixComponentGroup.AddChild(componentref);
                    componentref.Id = wixComponent.Id;

                    // Add the assembly file (and make it the key path)
                    var wixFileAssembly = new File();
                    wixComponent.AddChild(wixFileAssembly);
                    wixFileAssembly.Id       = string.Format("{0}.{1}.{2}", FileIdPrefix, assemblyxml.Include, sExtension);
                    wixFileAssembly.Name     = string.Format("{0}.{1}", assemblyxml.Include, sExtension);
                    wixFileAssembly.KeyPath  = YesNoType.yes;
                    wixFileAssembly.Checksum = YesNoType.yes;
                    wixFileAssembly.Vital    = YesNoType.yes;
                    wixFileAssembly.ReadOnly = YesNoType.yes;

                    RegisterTargetFile(wixFileAssembly.Name, string.Format("The {0} product assembly.", assemblyxml.Include), mapTargetFiles);

                    // Check whether it's a managed or native assembly
                    AssemblyName assemblyname = null;
                    try
                    {
                        assemblyname = AssemblyName.GetAssemblyName(fiAssembly.FullName);
                    }
                    catch (BadImageFormatException)
                    {
                    }

                    // Add COM Self-Registration data
                    if (assemblyxml.ComRegister)
                    {
                        /*
                         * foreach(ISchemaElement harvested in HarvestComSelfRegistration(wixFileAssembly, fiAssembly))
                         * wixComponent.AddChild(harvested);
                         */
                        SelfRegHarvester.Harvest(fiAssembly, assemblyname != null, wixComponent, wixFileAssembly);
                    }

                    // Ensure the managed DLL has a strong name
                    if ((assemblyname != null) && (Bag.Get <bool>(AttributeName.RequireStrongName)))
                    {
                        byte[] token = assemblyname.GetPublicKeyToken();
                        if ((token == null) || (token.Length == 0))
                        {
                            throw new InvalidOperationException(string.Format("The assembly “{0}” does not have a strong name.", assemblyxml.Include));
                        }
                    }

                    // Add PDBs
                    if (Bag.Get <bool>(AttributeName.IncludePdb))
                    {
                        HarvestSatellite(assemblyxml, assemblyxml.Include + ".pdb", wixComponent, MissingSatelliteErrorLevel.Error, "PDB file", mapTargetFiles);
                    }

                    // Add XmlDocs
                    if ((assemblyname != null) && (Bag.Get <bool>(AttributeName.IncludeXmlDoc)))
                    {
                        HarvestSatellite(assemblyxml, assemblyxml.Include + ".xml", wixComponent, MissingSatelliteErrorLevel.Error, "XmlDoc file", mapTargetFiles);
                    }

                    // Add configs
                    HarvestSatellite(assemblyxml, assemblyxml.Include + "." + sExtension + ".config", wixComponent, (assemblyxml.HasAppConfig ? MissingSatelliteErrorLevel.Error : MissingSatelliteErrorLevel.None), "application configuration file", mapTargetFiles);
                    HarvestSatellite(assemblyxml, assemblyxml.Include + "." + sExtension + ".manifest", wixComponent, (assemblyxml.HasMainfest ? MissingSatelliteErrorLevel.Error : MissingSatelliteErrorLevel.None), "assembly manifest file", mapTargetFiles);
                    HarvestSatellite(assemblyxml, assemblyxml.Include + ".XmlSerializers." + sExtension, wixComponent, (assemblyxml.HasXmlSerializers ? MissingSatelliteErrorLevel.Error : MissingSatelliteErrorLevel.None), "serialization assembly", mapTargetFiles);

                    // Add publisher policy assemblies
                    if (assemblyname != null)
                    {
                        HarvestPublisherPolicyAssemblies(assemblyxml, wixDirectory, wixComponentGroup, ref nGeneratedComponents, mapTargetFiles, guidcachexml);
                    }

                    // Register as an OmeaPlugin
                    if (assemblyname != null)
                    {
                        RegisterPlugin(assemblyxml, wixFileAssembly, wixComponentRegistry);
                    }
                }
            }
            return(nGeneratedComponents);
        }
Exemplo n.º 34
0
		}   // ByteArrayToHexDigitString (2 of 2)
		/// <summary>
		/// List selected properties of any assembly on a console.
		/// </summary>
		/// <param name="pmyLib">
		/// Pass in a reference to the desired assembly, which may be the
		/// assembly that exports a specified type, the executing assembly, the
		/// calling assembly, the entry assembly, or any other assembly for
		/// which you can obtain a reference.
		/// </param>
		public static void ShowKeyAssemblyProperties ( System.Reflection.Assembly pmyLib )
		{
			System.Reflection.AssemblyName MyNameIs = System.Reflection.AssemblyName.GetAssemblyName ( pmyLib.Location );
			System.Diagnostics.FileVersionInfo myVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo ( pmyLib.Location );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_SELECTED_DLL_PROPS_BEGIN , Environment.NewLine );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_ASSEMBLYFILEBASENAME , System.IO.Path.GetFileNameWithoutExtension ( pmyLib.Location ) );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_VERSIONSTRING , myVersionInfo.FileVersion );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_CULTURE , MyNameIs.CultureInfo.DisplayName );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_PUBLICKEYTOKEN , Util.ByteArrayToHexDigitString ( MyNameIs.GetPublicKeyToken ( ) ) );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_RUNTIME_VERSION , pmyLib.ImageRuntimeVersion );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_ASSEMBLYGUIDSTRING , GetAssemblyGuidString ( pmyLib ) );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_PRODUCTNAME , myVersionInfo.ProductName );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_LEGALCOPYRIGHT , myVersionInfo.LegalCopyright );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_LEGALTRADEMARKS , myVersionInfo.LegalTrademarks );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_COMPANYNAME , myVersionInfo.CompanyName );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_DESCRIPTION , myVersionInfo.FileDescription );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_COMMENTS , myVersionInfo.Comments , Environment.NewLine );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_ASSEMBYDIRNAME , System.IO.Path.GetDirectoryName ( pmyLib.Location ) );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_ASSEMBLYFILENAME , System.IO.Path.GetFileName ( pmyLib.Location ) , Environment.NewLine );

			string strAssemblyFileFQFN = pmyLib.Location;
			System.IO.FileInfo fiLibraryFile = new System.IO.FileInfo ( strAssemblyFileFQFN );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_FILE_CREATION_DATE , fiLibraryFile.CreationTime , fiLibraryFile.CreationTimeUtc );
			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_FILE_MODIFIED_DATE , fiLibraryFile.LastWriteTime , fiLibraryFile.LastWriteTimeUtc );

			Console.WriteLine ( Properties.Resources.MSG_ASM_PROPS_SELECTED_DLL_PROPS_END , Environment.NewLine );
		}   // private static void ShowKeAssemblyProperties method
Exemplo n.º 35
0
 /// <summary>Is the assembly and its referened assemblies not expected to have any metadata</summary>
 private static bool ShouldFilterAssembly(AssemblyName assemblyName)
 {
     return (ArePublicKeyTokensEqual(assemblyName.GetPublicKeyToken(), EcmaPublicKeyToken) ||
             ArePublicKeyTokensEqual(assemblyName.GetPublicKeyToken(), MsPublicKeyToken));
 }
Exemplo n.º 36
0
        public String ApplyPolicy(String assemblyName)
        {
            AssemblyName asmName = new AssemblyName(assemblyName);  

            byte[] pk = asmName.GetPublicKeyToken();
            if (pk == null)
                pk = asmName.GetPublicKey();

            // Simply-named assemblies cannot have policy, so for those,
            // we simply return the passed-in assembly name.
            if ((pk == null) || (pk.Length == 0))
                return assemblyName;
            else
                return nApplyPolicy(asmName);
        }
Exemplo n.º 37
0
        internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
        {
            if (originalAssemblyName == newAssemblyName)
            {
                return true;
            }

            AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
            AssemblyName newAssembly = new AssemblyName(newAssemblyName);

            // mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
            // so setting the assembly name to mscorlib must always be protected by a demand
            if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
        }
Exemplo n.º 38
0
 internal static string GetPublicKeyToken(AssemblyName name)
 {
     return string.Concat((from b in name.GetPublicKeyToken() select b.ToString("x2")).ToArray<string>());
 }
Exemplo n.º 39
0
        private static bool IsSimplyNamed(AssemblyName partialName)
        {
            byte[] pk = partialName.GetPublicKeyToken();
            if ((pk != null) &&
                (pk.Length == 0))
                return true;

            pk = partialName.GetPublicKey();
            if ((pk != null) &&
                (pk.Length == 0))
                return true;

            return false;
        }        
        public void Case10_SetPublicKeyToken()
        {
            AssemblyName n = new AssemblyName();
            byte[] barray = new byte[16];

            for (int i = 0; i < barray.Length; i++)
                barray[i] = (byte)'\0';

            n.SetPublicKeyToken(barray);
            byte[] barray_returned = n.GetPublicKeyToken();
            Assert.NotNull(barray_returned);
            Assert.True(isEqual(barray, barray_returned));
        }
Exemplo n.º 41
0
        private Type GetExceptionType(RpcErrorTypeBehavior typeResolution)
        {
            Type tException = typeof (ApplicationException);
            Assembly found = tException.Assembly;

            if (typeResolution == RpcErrorTypeBehavior.NoTypeResolution)
            {
                return tException;
            }

            if (!HasFullTypeName || !HasAssemblyName || String.IsNullOrEmpty(FullTypeName) ||
                String.IsNullOrEmpty(AssemblyName))
            {
                return tException;
            }

            if (!ValidTypeName.IsMatch(FullTypeName))
            {
                return tException;
            }

            if (typeResolution == RpcErrorTypeBehavior.OnlyUseMsCorLibTypes)
            {
                return found.GetType(FullTypeName) ?? tException;
            }

            AssemblyName name = new AssemblyName(AssemblyName);
            if (name.CodeBase != null)
            {
                return tException;
            }

            if (null != (found = LoadedAssemblies.Lookup(name)))
            {
                return found.GetType(FullTypeName) ?? tException;
            }

            if (typeResolution == RpcErrorTypeBehavior.OnlyUseLoadedAssemblies)
            {
                return tException;
            }

            if (typeResolution == RpcErrorTypeBehavior.OnlyLoadStrongNamed && name.GetPublicKeyToken() == null)
            {
                return tException;
            }

            Type test = Type.GetType(String.Format("{0}, {1}", FullTypeName, name));
            if (test != null)
            {
                return test;
            }

            if (typeResolution == RpcErrorTypeBehavior.LoadAnyAssembly)
            {
                return Type.GetType(String.Format("{0}, {1}", FullTypeName, new AssemblyName(name.Name))) ?? tException;
            }

            return tException;
        }
        public void Case9_SetPublicKeyToken()
        {
            AssemblyName n = new AssemblyName();
            byte[] barray = new byte[16];
            n.SetPublicKeyToken(barray);

            byte[] barray_returned = n.GetPublicKeyToken();
            Assert.NotNull(barray_returned);
            Assert.True(isEqual(barray, barray_returned));
        }
 internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
 {
     if (originalAssemblyName == newAssemblyName)
     {
         return(true);
     }
     System.Reflection.AssemblyName name  = new System.Reflection.AssemblyName(originalAssemblyName);
     System.Reflection.AssemblyName name2 = new System.Reflection.AssemblyName(newAssemblyName);
     return((!string.Equals(name2.Name, "mscorlib", StringComparison.OrdinalIgnoreCase) && !string.Equals(name2.Name, "mscorlib.dll", StringComparison.OrdinalIgnoreCase)) && Compare(name.GetPublicKeyToken(), name2.GetPublicKeyToken()));
 }