SetPublicKeyToken() 공개 메소드

public SetPublicKeyToken ( byte publicKeyToken ) : void
publicKeyToken byte
리턴 void
예제 #1
0
        public Assembly LoadAssembly(string name)
        {
            System.Diagnostics.Debug.Write("Trying to load assembly: " + name);
            if (System.IO.File.Exists(name))
            {
                return Assembly.LoadFrom(name);
            }
            else
            {
                string assemblyName = System.IO.Path.GetFileNameWithoutExtension(name);
                byte[] publicKeyToekn;

                if (GACGeometryKeyTokens.TryGetValue(assemblyName, out publicKeyToekn))
                {
                    AssemblyName an = new AssemblyName();
                    an.Name = assemblyName;
                    an.SetPublicKeyToken(publicKeyToekn);
                    an.Version = mExecutingAssemblyName.Version;
                    an.CultureInfo = mExecutingAssemblyName.CultureInfo;
                    an.ProcessorArchitecture = mExecutingAssemblyName.ProcessorArchitecture;
                    System.Diagnostics.Debug.Write("Assembly: " + assemblyName + "," + an.Version.ToString() + " is in GAC.");
                    return Assembly.Load(an);
                }
            }
            throw new System.IO.FileNotFoundException();
        }
        /// <summary>
        /// Creates a dictionary of assemblyNames and assemblies and sets the AssemblyResolver for the current AppDomain.
        /// </summary>
        /// <param name="assemblies">List of loaded assemblies</param>
        internal static void SetAssemblyResolver(IEnumerable<Assembly> assemblies)
        {
            ConcurrentDictionary<string, Assembly> assemblyNames = new ConcurrentDictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
            foreach (var assembly in assemblies)
            {
                // Keep a dictionary of assembly names and assemblies. It is used in the AssemblyResolve event handler.
                assemblyNames[assembly.FullName] = assembly;

                // If the assembly is a signed Open Ria assembly, then also add an entry
                // so that it is used in places where the of unsigned version of the assembly is requested
                var assemblyName = assembly.GetName();
                if(assemblyName.IsOpenRiaAssembly() && assemblyName.IsSigned())
                {
                    var unsignedName = new AssemblyName(assemblyName.FullName);
                    unsignedName.SetPublicKeyToken(new byte[0]);
                    assemblyNames[unsignedName.FullName] = assembly;
                }
            }
            loadedAssemblyNames = assemblyNames;

            // Unregister the event handler first, in case it was registered before. If it wasn't, this would be a no-op.
            AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(AssemblyUtilities.CurrentDomain_AssemblyResolveEventHandler);
            
            // Register the event handler for this call.
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyUtilities.CurrentDomain_AssemblyResolveEventHandler);
        }
예제 #3
0
		protected void SetAssemblyName (LoadInfoType loadInfoType, string filename, string name, string version,
						string culture, string publicKeyToken, string className)
		{
			assemblyName = new AssemblyName ();
			this.infoType = loadInfoType;
			this.className = className;
			if (infoType == LoadInfoType.AssemblyName) {
				if (version != null)
					assemblyName.Version = new Version (version);
				if (culture != null) {
					if (culture == "neutral")
						culture = String.Empty;
					assemblyName.CultureInfo = new CultureInfo (culture);
				}
				if (publicKeyToken != null) {
					char[] chars = publicKeyToken.ToCharArray ();
					byte[] bytes = new byte [Buffer.ByteLength (chars)];
					
					for (int i  = 0; i < Buffer.ByteLength (chars); i++)
						bytes [i] = Buffer.GetByte (chars, i); 
					assemblyName.SetPublicKeyToken (bytes);
				}
				
				assemblyName.Name = name;
			} else if (infoType == LoadInfoType.AssemblyFilename) {
				this.filename = filename;
			} else {
				;
			}
		}
        public EmittedAssembly(string name, string rootNamespace, Version version, CultureInfo culture
			, byte[] publicKey, byte[] publicKeyToken)
        {
            Contracts.Require.IsNotNull("name", name);
            Contracts.Require.IsNotEmpty("name", name);
            Contracts.Require.IsNotNull("rootNamespace", rootNamespace);
            Contracts.Require.IsNotEmpty("rootNamespace", name);
            Contracts.Require.IsNotNull("version", version);
            Contracts.Require.IsNotNull("culture", culture);

            this._classes = new Dictionary<string, EmittedClass>();
            this.RootNamespace = rootNamespace ?? name;
            _assemName = new AssemblyName(name);
            _assemName.Version = version;
            _assemName.CultureInfo = culture;
            _assemName.SetPublicKey(publicKey);
            _assemName.SetPublicKeyToken(publicKeyToken);
            #if DEBUG
            this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.RunAndSave);
            this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false);
            #else
            this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.Run);
            this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false);
            #endif
        }
예제 #5
0
 /// <summary>
 /// Returns a "live" System.Reflection.Assembly instance that provides reflective access to the referenced assembly. 
 /// If the assembly cannot be found or cannot be loaded, the result is null.
 /// </summary>
 public Assembly/*?*/ GetAssembly(IAssemblyReference/*?*/ assemblyReference) {
   if (assemblyReference == null) return null;
   var ident = assemblyReference.AssemblyIdentity;
   Assembly result = null;
   if (!this.assemblyMap.TryGetValue(ident, out result)) {
     var name = new System.Reflection.AssemblyName();
     if (!String.IsNullOrEmpty(ident.Location))
       name.CodeBase = new Uri(ident.Location).ToString();
     name.CultureInfo = new System.Globalization.CultureInfo(ident.Culture);
     name.Name = ident.Name.Value;
     name.SetPublicKeyToken(new List<byte>(ident.PublicKeyToken).ToArray());
     name.Version = ident.Version;
     var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
     foreach (var loadedAssem in loadedAssemblies) {
       if (System.Reflection.AssemblyName.ReferenceMatchesDefinition(name, loadedAssem.GetName())) {
         result = loadedAssem;
         break;
       }
     }
     if (result == null) {
       try {
         result = Assembly.Load(name);
       } catch (System.UriFormatException) {
       } catch (System.IO.FileNotFoundException) {
       } catch (System.IO.FileLoadException) {
       } catch (System.BadImageFormatException) {
       }
       this.assemblyMap.Add(ident, result);
     }
   }
   return result;
 }
예제 #6
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;
        }
예제 #7
0
        public static void RedirectAssembly(string shortName, Version targetVersion, string publicKeyToken)
        {
            ResolveEventHandler handler = null;

            handler = (sender, args) =>
            {
                // Use latest strong name & version when trying to load SDK assemblies
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.Name != shortName)
                    return null;

                Debug.WriteLine("Redirecting assembly load of " + args.Name
                                + ",\tloaded by " +
                                (args.RequestingAssembly == null ? "(unknown)" : args.RequestingAssembly.FullName));

                requestedAssembly.Version = targetVersion;
                requestedAssembly.SetPublicKeyToken(
                    new AssemblyName("x, PublicKeyToken=" + publicKeyToken).GetPublicKeyToken());
                requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;

                AppDomain.CurrentDomain.AssemblyResolve -= handler;

                return Assembly.Load(requestedAssembly);
            };
            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }
        /// <summary>
        /// Create a Processor, indicating whether it is to be schema-aware.
        /// </summary>
        /// <param name="schemaAware">Set to true if the Processor is to be schema-aware.
        /// This requires the Saxon-SA product to be installed, with a valid license key.</param>
        /// <param name="loadLocally">Set to true if Saxon-SA is to be loaded from the application
        /// directory rather than from the Global Assembly Cache. This option should normally
        /// be set only when troubleshooting, for example when using a locally-patched version
        /// of the software.</param>

        public Processor(bool schemaAware, bool loadLocally) {
            if (schemaAware) {
                if (loadLocally) {
                    Assembly asm = Assembly.Load("saxon8sa");
                } else {
                    try {
                        int[] v = JVersion.getStructuredVersionNumber();
                        AssemblyName asn = new AssemblyName();
                        asn.Name = "saxon8sa";
                        asn.Version = new Version(v[0], v[1], v[2], v[3]);
                        //asn.Version = new Version(JVersion.getMajorVersion(), JVersion.getMinorVersion());
                        asn.SetPublicKeyToken(new byte[] { 0xe1, 0xfd, 0xd0, 0x02, 0xd5, 0x08, 0x3f, 0xe6 });
                        asn.CultureInfo = new CultureInfo("");
                        Assembly asm = Assembly.Load(asn);
                        // try to load the saxon8sa.dll assembly
                        //Assembly asm = Assembly.Load("saxon8sa, Ver=" + JVersion.getProductVersion() + ".0.1, " +
                        //    @"SN=e1fdd002d5083fe6, Loc=neutral");
                    } catch (Exception e) {
                        Console.WriteLine("Cannot load Saxon-SA software (assembly saxon8sa.dll version " +
                            JVersion.getProductVersion() + ".0.1)");
                        throw e;
                    }
                }
                config = JConfiguration.makeSchemaAwareConfiguration(null);
                schemaManager = new SchemaManager(config);
            } else {
                config = new JConfiguration();
            }
            config.setURIResolver(new DotNetURIResolver(new XmlUrlResolver()));
            config.setCollectionURIResolver(new DotNetCollectionURIResolver());
        }
예제 #9
0
 private void Initialize()
 {
     _name = new AssemblyName();
     _name.Name = AssemblyCache.GetName(Interface);
     _name.Version = AssemblyCache.GetVersion(Interface);
     _name.CultureInfo = AssemblyCache.GetCulture(Interface);
     _name.SetPublicKeyToken(AssemblyCache.GetPublicKeyToken(Interface));
 }
예제 #10
0
		private static ModuleBuilder CreateProxyModule() {
			AssemblyName name = new AssemblyName("AutoMapper.Proxies");
            name.SetPublicKey(privateKey);
            name.SetPublicKeyToken(privateKeyToken);
            //AssemblyBuilder builder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
			AssemblyBuilder builder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
			return builder.DefineDynamicModule("AutoMapper.Proxies.emit");
		}
예제 #11
0
 public AssemblyName CreateAssemblyName()
 {
     var assemblyName = new AssemblyName(Name);
     assemblyName.Version = new Version(Version);
     assemblyName.CultureInfo = new CultureInfo(Culture);
     assemblyName.SetPublicKeyToken(FromHexString(PublicKeyToken));
     assemblyName.ProcessorArchitecture = ProcessorArchitecture;
     return assemblyName;
 }
 private void Initalize() {
     AssemblyName asmname = new AssemblyName();
     asmname.Name = "dynTypeCode";
     asmname.Version = new Version(0, 0, 0, 0);
     asmname.CultureInfo = CultureInfo.InvariantCulture;            
     asmname.SetPublicKeyToken(new byte[0]);
     m_asmBuilder = System.Threading.Thread.GetDomain().
         DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);
     m_modBuilder = m_asmBuilder.DefineDynamicModule("typecodeTypes");            
 }
        public static string GetAssemblyFullName(string name, string version, System.Globalization.CultureInfo culture, string publicKeyToken) {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = name;
            asmName.Version = new Version(version);

            asmName.CultureInfo = culture;
            if(publicKeyToken != null && publicKeyToken.Length == 2 * PublicKeyTokenBytesLength) {
                asmName.SetPublicKeyToken(StringToBytes(publicKeyToken));
            }
            return asmName.FullName;
        }
예제 #14
0
        private static AssemblyName GetAssemblyName(string codeBase, string fullName)
        {
            var assemblyName = new AssemblyName();
            var parts = fullName.Split(commaArray);
            assemblyName.Name = parts[0].TrimEnd(spaceArray);
            assemblyName.Version = Version.Parse(GetValue(parts[1]));
            assemblyName.CultureInfo = GetCultureInfo(GetValue(parts[2]));
            var publicKeyTokenString = GetValue(parts[3]);
            if (publicKeyTokenString != "null")
            {
                assemblyName.SetPublicKeyToken(Conversion.HexStringToByteArray(publicKeyTokenString));
            }
            else
            {
                assemblyName.SetPublicKeyToken(new byte[0]);
            }

            assemblyName.CodeBase = "file:///" + codeBase.Replace('\\', '/');
            return assemblyName;
        }
예제 #15
0
 private static IEnumerable<string> GetAllAssemblyNames(string assemblyName)
 {
     var assemblyNameObject = new AssemblyName(assemblyName);
     var full = assemblyNameObject.FullName;
     assemblyNameObject.ProcessorArchitecture = ProcessorArchitecture.None;
     var noProc = assemblyNameObject.FullName;
     assemblyNameObject.SetPublicKeyToken(null);
     var noPub = assemblyNameObject.FullName;
     var justVersion = string.Format("{0}, Version={1}", assemblyNameObject.Name, assemblyNameObject.Version);
     var list = new List<String> { assemblyName, full, noProc, noPub, justVersion, assemblyNameObject.Name };
     return list.Distinct().ToList();
 }
        static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (!args.Name.StartsWith(prefix))
                return null;

            var name = new AssemblyName(args.Name);
            name.SetPublicKeyToken(publicKeyToken);
            name.Version = roslynVersion;
            Debug.WriteLine("Ref12: Redirecting load of " + args.Name + ",\tfrom " + (args.RequestingAssembly == null ? "(unknown)" : args.RequestingAssembly.FullName));

            return Assembly.Load(name);
        }
예제 #17
0
	// Loading bundles
	
	public static AssemblyName MakeName (string shortname, string version) 
	{
	    byte[] pktok = typeof (Result).Assembly.GetName ().GetPublicKeyToken ();
	    
	    AssemblyName n = new AssemblyName ();
	    n.Name = MBuildPrefix + shortname;
	    n.SetPublicKeyToken (pktok);

	    if (version != null)
		n.Version = new Version (version);

	    return n;
	}
예제 #18
0
  /* Convenience method so that Scheme code can get away with using
     strings rather than Version objects and byte arrays and so on.
     
     Example usage:
     LoadAssembly("System.Windows.Forms", "2.0.0.0", "", "b77a5c561934e089");
     (you can find such info via the gacutil program)
  */

  public static void LoadAssembly(string name, 
                                  string version, // "maj.min.build.revision"
                                  string culture, 
                                  string publickey)
  {
    System.Reflection.AssemblyName n = new System.Reflection.AssemblyName();
    n.Name = name;
    n.Version = new System.Version(version);
    n.CultureInfo = new System.Globalization.CultureInfo(culture);
    n.SetPublicKeyToken( ToByteArray(publickey) );
    // Console.WriteLine("Attempting to load: {0}", n.FullName);
    System.Reflection.Assembly.Load(n);
  }
예제 #19
0
파일: Symbols.cs 프로젝트: lkinsella/cecil
        static SR.AssemblyName GetSymbolAssemblyName(SymbolKind kind)
        {
            if (kind == SymbolKind.PortablePdb)
            {
                throw new ArgumentException();
            }

            var suffix = GetSymbolNamespace(kind);

            var cecil_name = typeof(SymbolProvider).Assembly().GetName();

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

            name.SetPublicKeyToken(cecil_name.GetPublicKeyToken());

            return(name);
        }
예제 #20
0
        private static AssemblyName CreateAssemblyName(MetadataName name, MetadataName culture, Version version, AssemblyNameFlags flags, byte[] publicKeyOrToken) {
            var result = new AssemblyName();

            result.Name = name.ToString();
            if (!culture.IsEmpty) {
                result.CultureInfo = new CultureInfo(culture.ToString());
            }

            result.Version = version;
            result.Flags = flags;

            if (publicKeyOrToken.Length != 0) {
                if ((result.Flags & AssemblyNameFlags.PublicKey) != 0) {
                    result.SetPublicKey(publicKeyOrToken);
                } else {
                    result.SetPublicKeyToken(publicKeyOrToken);
                }
            }

            return result;
        }
        // CultureInfo is not portable.

        /// <summary>
        /// Converts this identity to <see cref="AssemblyName"/>.
        /// </summary>
        /// <returns>A new instance of <see cref="AssemblyName"/>.</returns>
        /// <exception cref="System.Globalization.CultureNotFoundException">The culture specified in <see cref="AssemblyIdentity.CultureName"/> is not available on the current platform.</exception>
        public static AssemblyName ToAssemblyName(this AssemblyIdentity identity)
        {
            var result = new AssemblyName();
            result.Name = identity.Name;
            result.Version = identity.Version;
            result.Flags = identity.Flags;
            result.ContentType = identity.ContentType;
            result.CultureInfo = CultureInfo.GetCultureInfo(identity.CultureName);

            if (identity.PublicKey.Length > 0)
            {
                result.SetPublicKey(identity.PublicKey.ToArray());
            }

            if (!identity.PublicKeyToken.IsDefault)
            {
                result.SetPublicKeyToken(identity.PublicKeyToken.ToArray());
            }

            return result;
        }
예제 #22
0
파일: Symbols.cs 프로젝트: zz0813/Reflexil
        static SR.AssemblyName GetSymbolAssemblyName(SymbolKind kind)
        {
            if (kind == SymbolKind.PortablePdb)
            {
                throw new ArgumentException();
            }

            var suffix = GetSymbolNamespace(kind);

            var cecil_name = typeof(SymbolProvider).Assembly().GetName();

            var name = new SR.AssemblyName {
                // HACK - Reflexil - load our custom assembly
                Name    = "Mono.Cecil." + suffix + ".Reflexil",
                Version = cecil_name.Version,
            };

            name.SetPublicKeyToken(cecil_name.GetPublicKeyToken());

            return(name);
        }
예제 #23
0
        private static RuntimeAssembly LoadWithPartialNameHack(string partialName, bool cropPublicKey)
        {
            StackCrawlMark  lookForMyCaller = StackCrawlMark.LookForMyCaller;
            RuntimeAssembly assembly        = null;
            AssemblyName    name            = new AssemblyName(partialName);

            if (!IsSimplyNamed(name))
            {
                if (cropPublicKey)
                {
                    name.SetPublicKey(null);
                    name.SetPublicKeyToken(null);
                }
                AssemblyName assemblyRef = EnumerateCache(name);
                if (assemblyRef != null)
                {
                    assembly = InternalLoadAssemblyName(assemblyRef, null, ref lookForMyCaller, false, false);
                }
            }
            return(assembly);
        }
예제 #24
0
        static SR.AssemblyName GetPlatformSymbolAssemblyName()
        {
            var cecil_name = typeof(SymbolProvider).Assembly.GetName();

            var name = new SR.AssemblyName {
                /*Telerik Authorship*/
/* AGPL */
#if NETSTANDARD
                Name = "Telerik.JustDecompile.Mono.Cecil." + symbol_kind + ".NetStandard",
#else
/* End AGPL */
                Name = "Telerik.JustDecompile.Mono.Cecil." + symbol_kind,
/* AGPL */
#endif
/* End AGPL */
                Version = cecil_name.Version,
            };

            name.SetPublicKeyToken(cecil_name.GetPublicKeyToken());

            return(name);
        }
예제 #25
0
        //
        // Copies a RuntimeAssemblyName into a freshly allocated AssemblyName with no data aliasing to any other object.
        //
        public void CopyToAssemblyName(AssemblyName blank)
        {
            blank.Name = this.Name;
            if (this.Version != null)
            {
                blank.Version = this.Version;
            }
            if (this.CultureName != null)
            {
                blank.CultureName = this.CultureName;
            }

            // Our "Flags" contain both the classic flags and the ProcessorArchitecture + ContentType bits. The public AssemblyName has separate properties for
            // these. The setters for these properties quietly mask out any bits intended for the other one, so we needn't do that ourselves..
            blank.Flags       = this.Flags.ExtractAssemblyNameFlags();
            blank.ContentType = this.Flags.ExtractAssemblyContentType();
#pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete
            blank.ProcessorArchitecture = this.Flags.ExtractProcessorArchitecture();
#pragma warning restore SYSLIB0037

            if (this.PublicKeyOrToken != null)
            {
                // We must not hand out our own copy of the PKT to AssemblyName as AssemblyName is amazingly trusting and gives untrusted callers
                // full freedom to scribble on its PKT array. (As do we but we only have trusted callers!)
                byte[] pkCopy = new byte[this.PublicKeyOrToken.Length];
                ((ICollection <byte>)(this.PublicKeyOrToken)).CopyTo(pkCopy, 0);

                if (0 != (this.Flags & AssemblyNameFlags.PublicKey))
                {
                    blank.SetPublicKey(pkCopy);
                }
                else
                {
                    blank.SetPublicKeyToken(pkCopy);
                }
            }

            return;
        }
 private AssemblyName ConstructAssemblyName(IntPtr asmMetaPtr, char[] asmNameBuf, uint asmNameLength, IntPtr pubKeyPtr, uint pubKeyBytes, uint flags)
 {
     ASSEMBLYMETADATA assemblymetadata = (ASSEMBLYMETADATA) Marshal.PtrToStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA));
     AssemblyName name = new AssemblyName {
         Name = new string(asmNameBuf, 0, ((int) asmNameLength) - 1),
         Version = new Version(assemblymetadata.usMajorVersion, assemblymetadata.usMinorVersion, assemblymetadata.usBuildNumber, assemblymetadata.usRevisionNumber)
     };
     string str = Marshal.PtrToStringUni(assemblymetadata.rpLocale);
     name.CultureInfo = new CultureInfo(str);
     if (pubKeyBytes > 0)
     {
         byte[] destination = new byte[pubKeyBytes];
         Marshal.Copy(pubKeyPtr, destination, 0, (int) pubKeyBytes);
         if ((flags & 1) != 0)
         {
             name.SetPublicKey(destination);
             return name;
         }
         name.SetPublicKeyToken(destination);
     }
     return name;
 }
예제 #27
0
        /// <summary>
        /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with possibly missing name components.
        /// </summary>
        /// <returns>
        /// An <see cref="AssemblyName"/> whose fields are be null if not present in <paramref name="nameObject"/>.
        /// </returns>
        internal static AssemblyName ToAssemblyName(FusionAssemblyIdentity.IAssemblyName nameObject)
        {
            var result = new AssemblyName();
            result.Name = FusionAssemblyIdentity.GetName(nameObject);
            result.Version = FusionAssemblyIdentity.GetVersion(nameObject);

            var cultureName = FusionAssemblyIdentity.GetCulture(nameObject);
            result.CultureInfo = (cultureName != null) ? new CultureInfo(cultureName) : null;

            byte[] publicKey = FusionAssemblyIdentity.GetPublicKey(nameObject);
            if (publicKey != null && publicKey.Length != 0)
            {
                result.SetPublicKey(publicKey);
            }
            else
            {
                result.SetPublicKeyToken(FusionAssemblyIdentity.GetPublicKeyToken(nameObject));
            }

            result.Flags = FusionAssemblyIdentity.GetFlags(nameObject);
            result.ContentType = FusionAssemblyIdentity.GetContentType(nameObject);
            return result;
        }
 internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
 {
     GraphicalHostReflectionWrapper wrapper = new GraphicalHostReflectionWrapper();
     if (IsInputFromRemoting(parentCmdlet))
     {
         ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)), "RemotingNotSupported", ErrorCategory.InvalidOperation, parentCmdlet);
         parentCmdlet.ThrowTerminatingError(errorRecord);
     }
     AssemblyName assemblyRef = new AssemblyName {
         Name = "Microsoft.PowerShell.GraphicalHost",
         Version = new Version(3, 0, 0, 0),
         CultureInfo = new CultureInfo(string.Empty)
     };
     assemblyRef.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });
     try
     {
         wrapper.graphicalHostAssembly = Assembly.Load(assemblyRef);
     }
     catch (FileNotFoundException exception)
     {
         string message = StringUtil.Format(HelpErrors.GraphicalHostAssemblyIsNotFound, featureName, exception.Message);
         parentCmdlet.ThrowTerminatingError(new ErrorRecord(new NotSupportedException(message, exception), "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         parentCmdlet.ThrowTerminatingError(new ErrorRecord(exception2, "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
     }
     wrapper.graphicalHostHelperType = wrapper.graphicalHostAssembly.GetType(graphicalHostHelperTypeName);
     ConstructorInfo info = wrapper.graphicalHostHelperType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
     if (info != null)
     {
         wrapper.graphicalHostHelperObject = info.Invoke(new object[0]);
     }
     return wrapper;
 }
예제 #29
0
        public static string GetGallioLoaderAssemblyPath()
        {
            var gallioAssemblyName = typeof(GallioLoaderLocator).Assembly.GetName();
            var gallioLoaderAssemblyName = new AssemblyName("Gallio.Loader")
            {
                Version = gallioAssemblyName.Version,
                CultureInfo = CultureInfo.InvariantCulture
            };
            gallioLoaderAssemblyName.SetPublicKeyToken(gallioAssemblyName.GetPublicKeyToken());

            try
            {
                Assembly loaderAssembly = Assembly.Load(gallioLoaderAssemblyName);
                if (loaderAssembly.GlobalAssemblyCache)
                    return null;

                return AssemblyUtils.GetFriendlyAssemblyLocation(loaderAssembly);
            }
            catch (Exception ex)
            {
                // Could not find the loader.
                throw new RuntimeException("Could not find the Gallio.Loader assembly.  It should be registered in the GAC or installed as a plugin.", ex);
            }
        }
예제 #30
0
파일: Engine.cs 프로젝트: RoastBoy/nant
            public void DoLoad() {
                engine = new Engine();
                string pth = Path.Combine(framework.FrameworkDirectory.FullName, "Microsoft.Build.Engine.dll");
                if (File.Exists(pth)) {
                    engine._a = Assembly.LoadFile(pth);
                } else {
                    //frameworks 3.0 and 3.5 do not copy its assemblies into filesystem. They reside just in assembly cache (GAC)

                    //Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
                    AssemblyName an = new AssemblyName("Microsoft.Build.Engine");
                    an.Version = new Version(framework.Version.Major, framework.Version.Minor, 0, 0);
                    an.CultureInfo = System.Globalization.CultureInfo.InvariantCulture;
                    an.SetPublicKeyToken(new byte[] { 0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a });

                    engine._a = Assembly.Load(an); //load from GAC
                }
                engine._t = engine._a.GetType("Microsoft.Build.BuildEngine.Engine");
                engine._obj = Activator.CreateInstance(engine._t);

                //2.0
                if (engine._a.GetName().Version.Major == 2) {
                    engine._t.GetProperty("BinPath").SetValue(engine._obj, framework.FrameworkDirectory.FullName, null);
                }
            }
예제 #31
0
        /// <summary>
        /// In the case where Gallio is being called from TDNet during a zero-registration
        /// test run (based on the contents of a *.tdnet file), we may 
        /// </summary>
        private static void InstallLoaderAssemblyResolverIfNeeded()
        {
            if (loaderAssemblyResolverInstalled)
                return;

            Assembly gallioTDNetRunnerAssembly = typeof(BaseTestRunner).Assembly;
            string gallioTDNetRunnerAssemblyPath = new Uri(gallioTDNetRunnerAssembly.CodeBase).LocalPath;
            string gallioTDNetRunnerAssemblyDir = Path.GetDirectoryName(gallioTDNetRunnerAssemblyPath);
            string gallioLoaderAssemblyPath = GetGallioLoaderAssemblyPath(gallioTDNetRunnerAssemblyDir);

            if (gallioLoaderAssemblyPath == null)
            {
                return;
            }

            AssemblyName gallioTDNetRunnerAssemblyName = gallioTDNetRunnerAssembly.GetName();
            var gallioLoaderAssemblyName = new AssemblyName("Gallio.Loader")
            {
                Version = gallioTDNetRunnerAssemblyName.Version,
                CultureInfo = CultureInfo.InvariantCulture
            };
            gallioLoaderAssemblyName.SetPublicKeyToken(gallioTDNetRunnerAssemblyName.GetPublicKeyToken());

            AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
            {
                if (e.Name == gallioLoaderAssemblyName.Name
                    || e.Name == gallioLoaderAssemblyName.FullName)
                {
                    return Assembly.LoadFrom(gallioLoaderAssemblyPath);
                }

                return null;
            };

            loaderAssemblyResolverInstalled = true;
        }
        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));
        }
 public void Case8_SetPublicKeyToken()
 {
     AssemblyName n = new AssemblyName();
     n.SetPublicKeyToken(null);
     Assert.Null(n.GetPublicKeyToken());
 }
예제 #34
0
		private int LoadAssemblyInternal (LuaState luaState)
		{			
			try {
				string assemblyName = LuaLib.LuaToString (luaState, 1).ToString ();
				Assembly assembly = null;
				Exception exception = null;

				try {
					assembly = Assembly.Load (assemblyName);
				} catch (BadImageFormatException) {
					// The assemblyName was invalid.  It is most likely a path.
				} catch (FileNotFoundException e) {
					exception = e;
				}

#if !SILVERLIGHT
				if (assembly == null) {
					try {
						assembly = Assembly.Load (AssemblyName.GetAssemblyName (assemblyName));
					} catch (FileNotFoundException e) {
						exception = e;
					}
					if (assembly == null) {

						AssemblyName mscor = assemblies [0].GetName ();
						AssemblyName name = new AssemblyName ();
						name.Name = assemblyName;
						name.CultureInfo = mscor.CultureInfo;
						name.Version = mscor.Version;
						name.SetPublicKeyToken (mscor.GetPublicKeyToken ());
						name.SetPublicKey (mscor.GetPublicKey ());
						assembly = Assembly.Load (name);

						if (assembly != null)
							exception = null;
					}
					if (exception != null)
						ThrowError (luaState, exception);
				}
#endif
				if (assembly != null && !assemblies.Contains (assembly))
					assemblies.Add (assembly);
			} catch (Exception e) {
				ThrowError (luaState, e);
			}

			return 0;
		}
        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));
        }
예제 #36
0
    public static void initclr()
#endif
    {
#if DEBUG_PRINT
        System.Console.WriteLine("Attempting to load Python.Runtime using standard binding rules... ");
#endif
#if USE_PYTHON_RUNTIME_PUBLIC_KEY_TOKEN
        var pythonRuntimePublicKeyTokenData = new byte[] { 0x50, 0x00, 0xfe, 0xa6, 0xcb, 0xa7, 0x02, 0xdd };
#endif

        // Attempt to find and load Python.Runtime using standard assembly binding rules.
        // This roughly translates into looking in order:
        // - GAC
        // - ApplicationBase
        // - A PrivateBinPath under ApplicationBase
        // With an unsigned assembly, the GAC is skipped.
        var pythonRuntimeName = new System.Reflection.AssemblyName("Python.Runtime")
        {
#if USE_PYTHON_RUNTIME_VERSION
            Version = new System.Version("4.0.0.1"),
#endif
            CultureInfo = System.Globalization.CultureInfo.InvariantCulture,
        };
#if USE_PYTHON_RUNTIME_PUBLIC_KEY_TOKEN
        pythonRuntimeName.SetPublicKeyToken(pythonRuntimePublicKeyTokenData);
#endif
        // We've got the AssemblyName with optional features; try to load it.
        System.Reflection.Assembly pythonRuntime;
        try
        {
            pythonRuntime = System.Reflection.Assembly.Load(pythonRuntimeName);
#if DEBUG_PRINT
            System.Console.WriteLine("Success!");
#endif
        }
        catch (System.IO.IOException)
        {
            try
            {
                // If the above fails for any reason, we fallback to attempting to load "Python.Runtime.dll"
                // from the directory this assembly is running in. "This assembly" is probably "clr.pyd",
                // sitting somewhere in PYTHONPATH.  This is using Assembly.LoadFrom, and inherits all the
                // caveats of that call.  See MSDN docs for details.
                // Suzanne Cook's blog is also an excellent source of info on this:
                // http://blogs.msdn.com/suzcook/
                // http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx
                // http://blogs.msdn.com/suzcook/archive/2003/06/13/57180.aspx

                var executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
                var assemblyDirectory = System.IO.Path.GetDirectoryName(executingAssembly.Location);
                if (assemblyDirectory == null)
                {
                    throw new System.InvalidOperationException(executingAssembly.Location);
                }
                var pythonRuntimeDllPath = System.IO.Path.Combine(assemblyDirectory, "Python.Runtime.dll");
#if DEBUG_PRINT
                System.Console.WriteLine("Attempting to load Python.Runtime from: '{0}'...", pythonRuntimeDllPath);
#endif
                pythonRuntime = System.Reflection.Assembly.LoadFrom(pythonRuntimeDllPath);
            }
            catch (System.InvalidOperationException)
            {
#if DEBUG_PRINT
                System.Console.WriteLine("Could not load Python.Runtime, so sad.");
#endif
#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
                return(IntPtr.Zero);
#else
                return;
#endif
            }
        }

        // Once here, we've successfully loaded SOME version of Python.Runtime
        // So now we get the PythonEngine and execute the InitExt method on it.
        var pythonEngineType = pythonRuntime.GetType("Python.Runtime.PythonEngine");

#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
        return((IntPtr)pythonEngineType.InvokeMember("InitExt", System.Reflection.BindingFlags.InvokeMethod, null, null, null));
#else
        pythonEngineType.InvokeMember("InitExt", System.Reflection.BindingFlags.InvokeMethod, null, null, null);
#endif
    }