GetType() private method

private GetType ( string name ) : Type
name string
return Type
Esempio n. 1
1
        public Test Build(string assemblyName, string testName, bool autoSuites)
        {
            if (testName == null || testName == string.Empty)
                return Build(assemblyName, autoSuites);

            // Change currentDirectory in case assembly references unmanaged dlls
            // and so that any addins are able to access the directory easily.
            using (new DirectorySwapper(Path.GetDirectoryName(assemblyName)))
            {
                this.assembly = Load(assemblyName);
                if (assembly == null) return null;

                // If provided test name is actually the name of
                // a type, we handle it specially
                Type testType = assembly.GetType(testName);
                if (testType != null)
                    return Build(assemblyName, testType, autoSuites);

                // Assume that testName is a namespace and get all fixtures in it
                IList fixtures = GetFixtures(assembly, testName);
                if (fixtures.Count > 0)
                    return BuildTestAssembly(assemblyName, fixtures, autoSuites);

                return null;
            }
        }
        protected SandboxGameAssemblyWrapper()
        {
            m_instance = this;
            m_isDebugging = false;
            m_isUsingCommonProgramData = false;
            m_isInSafeMode = false;

            m_assembly = Assembly.UnsafeLoadFrom("Sandbox.Game.dll");

            m_mainGameType = m_assembly.GetType(MainGameNamespace + "." + MainGameClass);
            m_serverCoreType = m_assembly.GetType(ServerCoreClass);

            m_mainGameInstanceField = m_mainGameType.GetField(MainGameInstanceField, BindingFlags.Static | BindingFlags.Public);
            m_configContainerField = m_mainGameType.GetField(MainGameConfigContainerField, BindingFlags.Static | BindingFlags.Public);
            m_configContainerType = m_configContainerField.FieldType;
            m_serverCoreNullRender = m_serverCoreType.GetField(ServerCoreNullRenderField, BindingFlags.Public | BindingFlags.Static);

            m_configContainerDedicatedDataField = m_configContainerType.GetField(ConfigContainerDedicatedDataField, BindingFlags.NonPublic | BindingFlags.Instance);
            m_setConfigWorldName = m_configContainerType.GetMethod(ConfigContainerSetWorldName, BindingFlags.Public | BindingFlags.Instance);

            m_lastProfilingOutput = DateTime.Now;
            m_countQueuedActions = 0;
            m_averageQueuedActions = 0;

            Console.WriteLine("Finished loading SandboxGameAssemblyWrapper");
        }
        private static object ResolveAdapter(Assembly assembly, Type interfaceType)
        {
            string typeName = MakeAdapterTypeName(interfaceType);

            try
            {
                // Is there an override?
                Type type = assembly.GetType(typeName + "Override");
                if (type != null)
                    return Activator.CreateInstance(type);

                // Fall back to a default implementation
                type = assembly.GetType(typeName);
                if (type != null)
                    return Activator.CreateInstance(type);

                // Fallback to looking in this assembly for a default
                type = typeof(ProbingAdapterResolver).Assembly.GetType(typeName);

                return type != null ? Activator.CreateInstance(type) : null;
            }
            catch
            {
                return null;
            }
        }
        private static Type GetTypeFromAssembly(Assembly assembly, string dtoObjectName, bool isNameFullyQualified, string alternateNamespace)
        {
            string typeName;
            Type type = null;

            if (assembly != null)
            {
                var asmName = assembly.FullName.Substring(0, assembly.FullName.IndexOf(','));
                typeName = isNameFullyQualified ? dtoObjectName : string.Format("{0}.{1}", asmName, dtoObjectName);
                type = assembly.GetType(typeName);

                if (type == null)
                {
                    if (!string.IsNullOrWhiteSpace(alternateNamespace))
                    {
                        typeName = string.Format("{0}.{1}", alternateNamespace, dtoObjectName);
                    }
                    else
                    {
                        typeName = dtoObjectName;
                    }
                    type = assembly.GetType(typeName);
                }
            }

            return type;
        }
Esempio n. 5
0
        /// <summary>
        /// Loads the correct assembly and type information for accessing
        /// the IVsBuildManagerAccessor service.
        /// </summary>
        private static void LoadBuildManagerAssembly()
        {
            try
            {
                BuildManagerAdapter.buildManagerAssembly = Assembly.Load("Microsoft.VisualStudio.Shell.Interop.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                BuildManagerAdapter.buildManagerAccessorType = buildManagerAssembly.GetType("Microsoft.VisualStudio.Shell.Interop.SVsBuildManagerAccessor");
                BuildManagerAdapter.buildManagerAccessorInterfaceType = buildManagerAssembly.GetType("Microsoft.VisualStudio.Shell.Interop.IVsBuildManagerAccessor");

                if (BuildManagerAdapter.buildManagerAccessorType != null && BuildManagerAdapter.buildManagerAccessorInterfaceType != null)
                {
                    return;
                }
            }
            catch
            {
            }

            // If the first one didn't work, this one must. Don't swallow
            // exceptions here.
            BuildManagerAdapter.buildManagerAssembly = Assembly.Load("Microsoft.VisualStudio.CommonIDE, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            BuildManagerAdapter.buildManagerAccessorType = buildManagerAssembly.GetType("Microsoft.VisualStudio.CommonIDE.BuildManager.SVsBuildManagerAccessor");
            BuildManagerAdapter.buildManagerAccessorInterfaceType = buildManagerAssembly.GetType("Microsoft.VisualStudio.CommonIDE.BuildManager.IVsBuildManagerAccessor");

            if (BuildManagerAdapter.buildManagerAccessorType == null || BuildManagerAdapter.buildManagerAccessorInterfaceType == null)
            {
                throw new TypeLoadException("TypeLoadException: Microsoft.VisualStudio.CommonIDE.BuildManager.SVsBuildManagerAccessor");
            }
        }
Esempio n. 6
0
        static void CreateUsingLateBinding(Assembly asm)
        {
            try
            {
                // Get metadata for the Minivan type.
                Type miniVan = asm.GetType("CarLibrary.MiniVan");
                // Create the Minivan on the fly.
                object obj = Activator.CreateInstance(miniVan); // object, can't cast
                Console.WriteLine("Created a {0} using late binding!", obj);
                // Get info for TurboBoost.
                MethodInfo mi = miniVan.GetMethod("TurboBoost");
                // Invoke method ('null' for no parameters).
                mi.Invoke(obj, null);

                // First, get a metadata description of the sports car.
                Type sport = asm.GetType("CarLibrary.SportsCar");
                // Now, create the sports car.
                object sportobj = Activator.CreateInstance(sport);
                // Invoke TurnOnRadio() with arguments.
                MethodInfo mi2 = sport.GetMethod("TurnOnRadio");
                mi2.Invoke(obj, new object[] { true, 2 });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 7
0
 public RainMaker(Game game)
     : base(game)
 {
     terrariaAssembly = Assembly.GetAssembly(game.GetType());
     main = terrariaAssembly.GetType("Terraria.Main");
     worldGen = terrariaAssembly.GetType("Terraria.WorldGen");
 }
Esempio n. 8
0
        public MainForm()
        {
            InitializeComponent();

            _tasksAssembly = Assembly.LoadFrom(ConfigurationManager.AppSettings["TasksAssembly"]);
            _callbacksAssembly = Assembly.LoadFrom(ConfigurationManager.AppSettings["CallbacksAssembly"]);

            // TODO: implement a prefix for each task description, don't use Count!
            _taskDescriptionToObject = new Dictionary<string, TaskObject>(ConfigurationManager.AppSettings.Count);
            _concreteEventArgsToTaskDescription = new Dictionary<Type, string>(ConfigurationManager.AppSettings.Count);

            foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            {
                if (key != "TasksAssembly" && key != "CallbacksAssembly")
                {
                    String[] concreteTypeNamesAndOperandsRequired = ConfigurationManager.AppSettings[key].Split(',');
                    Type taskConcreteType = _tasksAssembly.GetType(concreteTypeNamesAndOperandsRequired[0]);
                    Type taskCallbackType = _callbacksAssembly.GetType(concreteTypeNamesAndOperandsRequired[1]);
                    Type taskConcreteEventArgsType = _callbacksAssembly.GetType(concreteTypeNamesAndOperandsRequired[2]);

                    _taskDescriptionToObject.Add(key, new TaskObject(taskConcreteType, taskCallbackType, Int32.Parse(concreteTypeNamesAndOperandsRequired[3]),
                        "true" == concreteTypeNamesAndOperandsRequired[4]));
                    _concreteEventArgsToTaskDescription.Add(taskConcreteEventArgsType, key);
                    tasksComboBox.Items.Add(key);
                }
            }

            _resultDelegate = new NewResultDelegate(AddResultToList);
        }
 public FsiLanguageServiceHelper()
 {
     EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
     fsiAssembly = Assembly.Load(String.Format("FSharp.VS.FSI, Version={0}.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", dte.Version));
     fsiLanguageServiceType = fsiAssembly.GetType("Microsoft.VisualStudio.FSharp.Interactive.FsiLanguageService");
     sessionsType = fsiAssembly.GetType("Microsoft.VisualStudio.FSharp.Interactive.Session.Sessions");
     fsiWindowType = fsiAssembly.GetType(FsiToolWindowClassName);
 }
		// At class initialization we try to use reflection to load the
		// Mono.Data.Sqlite assembly: this allows us to use Sqlite as the 
		// default certificate store without explicitly depending on the
		// assembly.
		static SqliteCertificateDatabase ()
		{
#if COREFX
			try {
				if ((sqliteAssembly = Assembly.Load (new AssemblyName ("Microsoft.Data.Sqlite"))) != null) {
					sqliteConnectionClass = sqliteAssembly.GetType ("Microsoft.Data.Sqlite.SqliteConnection");
					sqliteConnectionStringBuilderClass = sqliteAssembly.GetType ("Microsoft.Data.Sqlite.SqliteConnectionStringBuilder");

					// Make sure that the runtime can load the native sqlite library
					var builder = Activator.CreateInstance (sqliteConnectionStringBuilderClass);

					IsAvailable = true;
				}
			} catch (FileNotFoundException) {
			} catch (FileLoadException) {
			} catch (BadImageFormatException) {
			}
#elif !__MOBILE__
			var platform = Environment.OSVersion.Platform;

			try {
				// Mono.Data.Sqlite will only work on Unix-based platforms and 32-bit Windows platforms.
				if (platform == PlatformID.Unix || platform == PlatformID.MacOSX || IntPtr.Size == 4) {
					if ((sqliteAssembly = Assembly.Load ("Mono.Data.Sqlite")) != null) {
						sqliteConnectionClass = sqliteAssembly.GetType ("Mono.Data.Sqlite.SqliteConnection");
						sqliteConnectionStringBuilderClass = sqliteAssembly.GetType ("Mono.Data.Sqlite.SqliteConnectionStringBuilder");

						// Make sure that the runtime can load the native sqlite3 library
						var builder = Activator.CreateInstance (sqliteConnectionStringBuilderClass);
						sqliteConnectionStringBuilderClass.GetProperty ("DateTimeFormat").SetValue (builder, 0, null);

						IsAvailable = true;
					}
				}

				// System.Data.Sqlite is only available for Windows-based platforms.
				if (!IsAvailable && platform != PlatformID.Unix && platform != PlatformID.MacOSX) {
					if ((sqliteAssembly = Assembly.Load ("System.Data.SQLite")) != null) {
						sqliteConnectionClass = sqliteAssembly.GetType ("System.Data.SQLite.SQLiteConnection");
						sqliteConnectionStringBuilderClass = sqliteAssembly.GetType ("System.Data.SQLite.SQLiteConnectionStringBuilder");

						// Make sure that the runtime can load the native sqlite3 library
						var builder = Activator.CreateInstance (sqliteConnectionStringBuilderClass);
						sqliteConnectionStringBuilderClass.GetProperty ("DateTimeFormat").SetValue (builder, 0, null);

						IsAvailable = true;
					}
				}
			} catch (FileNotFoundException) {
			} catch (FileLoadException) {
			} catch (BadImageFormatException) {
			}
#else
			IsAvailable = true;
#endif
		}
Esempio n. 11
0
		internal static MethodInfo UnhandledExceptionHandler; // object->object
        
        public static void Bind(Assembly integrationAssembly)
        {
            integrationType = integrationAssembly.GetType("ExcelDna.Integration.Integration");

            Type menuManagerType = integrationAssembly.GetType("ExcelDna.Integration.MenuManager");
            addCommandMenu = menuManagerType.GetMethod("AddCommandMenu", BindingFlags.Static | BindingFlags.NonPublic);
            removeCommandMenus = menuManagerType.GetMethod("RemoveCommandMenus", BindingFlags.Static | BindingFlags.NonPublic);

			UnhandledExceptionHandler = integrationType.GetMethod("HandleUnhandledException", BindingFlags.Static | BindingFlags.NonPublic);
        }
Esempio n. 12
0
        public Runable(Assembly assembly, string[] args)
        {
            var constructor = assembly.GetType("Code").GetConstructor(new Type[] { typeof(string[]) });
            _instance = constructor.Invoke(new object[] { args }) as RuntimeBase;
            _instance.Progress += OnProgress;
            _instance.Select += OnSelect;
            _instance.Highlight += OnHighlight;

            _runType = assembly.GetType("Code");
        }
Esempio n. 13
0
 private Type FindTypeInAssembly(Assembly assembly, string typeName)
 {
     var type = assembly.GetType(typeName);
     if (type != null) return type;
     for (int i = 0; i < RazorTypeBuilder.DefaultNamespaceImports.Length; i++)
     {
         type = assembly.GetType(RazorTypeBuilder.DefaultNamespaceImports[i] + "." + typeName);
         if (type != null) return type;
     }
     return null;
 }
Esempio n. 14
0
        private Zip()
        {
            // Load types
            this.zipAssembly = LoadAssemblyFromResource(ASSEMBLY_RESOURCE_STRING);

            fastZipType = zipAssembly.GetType("ICSharpCode.SharpZipLib.Zip.FastZip");
            fastZipInstance = Activator.CreateInstance(fastZipType);

            zipFileType = zipAssembly.GetType("ICSharpCode.SharpZipLib.Zip.ZipFile");
            zipEntryType = zipAssembly.GetType("ICSharpCode.SharpZipLib.Zip.ZipEntry");
        }
Esempio n. 15
0
		static ClientReflectionHelper ()
		{
			SystemAssembly = typeof (Uri).Assembly;
			web_header_collection = SystemAssembly.GetType ("System.Net.WebHeaderCollection");
			headers_all_keys = web_header_collection.GetProperty ("AllKeys").GetGetMethod ();

			headers_get = web_header_collection.GetMethod ("Get", new Type [] { typeof (string) });
			headers_set = web_header_collection.GetMethod ("Set", new Type [] { typeof (string), typeof (string) });

			Type network_credential = SystemAssembly.GetType ("System.Net.NetworkCredential");
			network_credential_ctor = network_credential.GetConstructor (new Type [] { typeof (string), typeof (string), typeof (string) });
		}
Esempio n. 16
0
        public dynamic GetMappingCollectionEF6(Assembly ef6Assembly, out string containerName)
        {
            var edmItemCollectionType = ef6Assembly.GetType(
                "System.Data.Entity.Core.Metadata.Edm.EdmItemCollection",
                true);
            var storeItemCollectionType = ef6Assembly.GetType(
                "System.Data.Entity.Core.Metadata.Edm.StoreItemCollection",
                true);
            var storageMappingItemCollectionType = ef6Assembly.GetType(
                "System.Data.Entity.Core.Mapping.StorageMappingItemCollection",
                true);

            dynamic edmCollection;
            using (var reader = CreateSectionReader(EdmxSection.Csdl))
            {
                edmCollection = Activator.CreateInstance(
                    edmItemCollectionType,
                    (IEnumerable<XmlReader>)new[] { reader });
            }

            containerName = null;
            foreach (var item in edmCollection)
            {
                if (item.GetType().Name == "EntityContainer")
                {
                    containerName = item.ToString();

                    break;
                }
            }

            dynamic storeCollection;
            using (var reader = CreateSectionReader(EdmxSection.Ssdl))
            {
                storeCollection = Activator.CreateInstance(
                    storeItemCollectionType,
                    (IEnumerable<XmlReader>)new[] { reader });
            }

            dynamic mappingCollection;
            using (var reader = CreateSectionReader(EdmxSection.Msl))
            {
                mappingCollection = Activator.CreateInstance(
                    storageMappingItemCollectionType,
                    edmCollection,
                    storeCollection,
                    (IEnumerable<XmlReader>)new[] { reader });
            }

            return mappingCollection;
        }
Esempio n. 17
0
        public static void Initialize(Assembly integrationAssembly)
        {
            IntegrationMarshalHelpers.Initialize(integrationAssembly);
            Type menuManagerType = integrationAssembly.GetType("ExcelDna.Integration.MenuManager");
            addCommandMenu = menuManagerType.GetMethod("AddCommandMenu", BindingFlags.Static | BindingFlags.NonPublic);
            removeCommandMenus = menuManagerType.GetMethod("RemoveCommandMenus", BindingFlags.Static | BindingFlags.NonPublic);

            Type dnaLibraryType = integrationAssembly.GetType("ExcelDna.Integration.DnaLibrary");
            dnaLibraryCurrentLibrary = dnaLibraryType.GetProperty("CurrentLibrary",  BindingFlags.Static | BindingFlags.Public).GetValue(null, null);

            dnaLibraryAutoOpen = dnaLibraryType.GetMethod("AutoOpen", BindingFlags.Instance | BindingFlags.NonPublic);
            dnaLibraryAutoClose = dnaLibraryType.GetMethod("AutoClose", BindingFlags.Instance | BindingFlags.NonPublic);

            dnaLibraryGetName = dnaLibraryType.GetProperty("Name");
        }
Esempio n. 18
0
        private Type FindTypeInAssembly(Assembly assembly, string typeName)
        {
            var type = assembly.GetType(typeName);

            if (type != null) return type;

            foreach (var ns in SimpleRazorConfiguration.NamespaceImports.Select(x => x.Key).Distinct())
            {
                type = assembly.GetType(ns + "." + typeName);

                if (type != null) return type;
            }

            return null;
        }
Esempio n. 19
0
 static void InvokeMethodWithArgsUsingLateBinding(Assembly asm)
 {
     Type sport = asm.GetType("CarLibrary.SportsCar");
     object obj = Activator.CreateInstance(sport);
     MethodInfo method = sport.GetMethod("TurnOnRadio");
     method.Invoke(obj, new object[] { true, 2 });
 }
		public HatPackage() {
			_vcAssembly = Assembly.Load("Microsoft.VisualStudio.TeamFoundation.VersionControl");
			Type t = _vcAssembly.GetType("Microsoft.VisualStudio.TeamFoundation.VersionControl.HatPackage");
			var prop = t.GetProperty("Instance", BindingFlags.NonPublic | BindingFlags.Static);
			object instance = prop.GetValue(null, null);
			_wrapped = new AccessPrivateWrapper(instance);
		}
Esempio n. 21
0
 /// <summary>
 /// Loads this the module and instantiates the UrlMap.
 /// </summary>
 public void Load()
 {
     if (!File.Exists(ModulePath))
     {
         throw new NoSuchModuleException("Error: No such module at '" + ModulePath + "'.");
     }
     ModuleAssembly = Assembly.LoadFile(ModulePath);
     #if (Windows && !Unix)
     int lastslash = ModulePath.LastIndexOf(@"\");
     #else
     int lastslash = ModulePath.LastIndexOf("/");
     #endif
     string assemblynamespace = ModulePath.Substring(lastslash+1, ModulePath.LastIndexOf('.') - lastslash-1);
     ModuleNamespace = assemblynamespace;
     Type t = ModuleAssembly.GetType(assemblynamespace+".ModuleMap");
     if (t != null)
     {
         MethodInfo m = t.GetMethod("GetUrlMap");
         if (m != null)
         {
             UrlMap = (List<UrlMapItem>)m.Invoke(null, (new object[]{}));
         }
         else
         {
             throw new InvalidModuleMapException("Error: The ModuleMap class is incorrect!");
         }
     }
     else
     {
         throw new InvalidModuleMapException("Error: The ModuleMap class is missing!");
     }
 }
Esempio n. 22
0
File: Util.cs Progetto: Caspeco/JSIL
        public ComparisonTest(string filename, string[] stubbedAssemblies = null, TypeInfoProvider typeInfo = null)
        {
            Filename = Path.Combine(TestSourceFolder, filename);

            var sourceCode = File.ReadAllText(Filename);
            switch (Path.GetExtension(filename).ToLower()) {
                case ".cs":
                    Assembly = CompilerUtil.CompileCS(sourceCode, out TemporaryFiles);
                    break;
                case ".vb":
                    Assembly = CompilerUtil.CompileVB(sourceCode, out TemporaryFiles);
                    break;
                default:
                    throw new ArgumentException("Unsupported source file type for test");
            }

            var program = Assembly.GetType("Program");
            if (program == null)
                throw new Exception("Test missing 'Program' main class");

            TestMethod = program.GetMethod("Main");
            if (TestMethod == null)
                throw new Exception("Test missing 'Main' method of 'Program' main class");

            StubbedAssemblies = stubbedAssemblies;
            TypeInfo = typeInfo;
        }
 private static object ResolveAdapter(Assembly assembly, Type interfaceType)
 {
     string typeName = MakeAdapaterTypeName(interfaceType);
     Type type = assembly.GetType(typeName, throwOnError: false);
     if (type != null) return Activator.CreateInstance(type);
     return type;
 }
Esempio n. 24
0
        private static void tryAssemblyLoad()
        {
            try
            {
                coreAssembly = Assembly.LoadFrom("SSCore.dll");
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not load the SSCore library: \"" + e.Message + "\".");
                Environment.Exit(1);
            }
            if (coreAssembly == null)
            {
                Console.WriteLine("Could not load the SSCore library for an unknown reason.");
                Environment.Exit(1);
            }

            try
            {
                coreType = coreAssembly.GetType("SSCyg.SSCore");
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not load the SSCore type: \"" + e.Message + "\".");
                Environment.Exit(1);
            }
            if (coreType == null)
            {
                Console.WriteLine("Could not load the SSCore type for an unknown reason.");
                Environment.Exit(1);
            }
        }
        static CustomizationApi()
        {
            CustomAssembly = Assembly.GetEntryAssembly();
            CUSTOM_NAMESPACE = (from t in CustomAssembly.GetExportedTypes() where t.Name == CUSTOM_BOT_CLASS_NAME select t.Namespace).FirstOrDefault();
            if (CUSTOM_NAMESPACE == null)
                LogMessage.Exit("Could not find class " + CUSTOM_BOT_CLASS_NAME + " in the entry assembly.");
            bot_type = CustomAssembly.GetType(CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME);
            if (bot_type == null)
                LogMessage.Exit("Could not find class " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + " in the entry assembly.");

            try
            {
                session_creating = (Action)Delegate.CreateDelegate(typeof(Action), bot_type.GetMethod("SessionCreating", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".SessionCreating was not found.");
            }
            try
            {
                session_closing = (Action)Delegate.CreateDelegate(typeof(Action), bot_type.GetMethod("SessionClosing", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".SessionClosing was not found.");
            }
            try
            {
                fill_start_input_item_queue = (Action<InputItemQueue, Type>)Delegate.CreateDelegate(typeof(Action<InputItemQueue, Type>), bot_type.GetMethod("FillStartInputItemQueue", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".FillStartInputItemQueue was not found.");
            }
        }
    public override TaskResult Start(TaskExecutionNode node)
    {
      ContextTask task = (ContextTask) node.RemoteTask;
      
      _contextAssembly = LoadContextAssembly(task);
      if (_contextAssembly == null)
      {
        return TaskResult.Error;
      }

      _contextClass = _contextAssembly.GetType(task.ContextTypeName);
      if (_contextClass == null)
      {
        Server.TaskExplain(node.RemoteTask,
                           String.Format("Could not load type '{0}' from assembly {1}.",
                                         task.ContextTypeName,
                                         task.AssemblyLocation));
        Server.TaskError(node.RemoteTask, "Could not load context");
        return TaskResult.Error;
      }

      _listener = new PerContextRunListener(Server, node.RemoteTask);
      _runner = new DefaultRunner(_listener, RunOptions.Default);

      return TaskResult.Success;
    }
Esempio n. 27
0
        private Type ResolveTypeImpl(Assembly startAssembly, string typeName, bool ignoreCase)
        {
            Type modelType = null;

            if (startAssembly != null)
            {
                modelType = startAssembly.GetType(typeName, false, ignoreCase);
                if (modelType != null) return modelType;
            }

            if (this._knownGoodAssemblies.Any(assembly => (modelType = FindTypeInAssembly(assembly, typeName)) != null))
            {
                return modelType;
            }

            foreach (var assembly in TypeResolver.DefaultAssemblies.Union(KnownAssemblies))
            {
                if ((modelType = FindTypeInAssembly(assembly, typeName)) != null)
                {
                    this._knownGoodAssemblies.Add(assembly);
                    return modelType;
                }
            }

            return null;
        }
        public static MailMessageTemplate NewMailMessageTemplate(FeedRecord messageContent, Assembly assembly)
        {
            var messageTemplate = (MailMessageTemplate)Activator.CreateInstance(assembly.GetType("Federation.MailService.MailMessageRazorTemplate"));
            messageTemplate.SetModel(messageContent);

            return messageTemplate;
        }
Esempio n. 29
0
 static string generateHTML(Assembly assembly, string fullyQualitiedTemplateClassName, object model)
 {
     var generatedType = assembly.GetType(fullyQualitiedTemplateClassName);
     var instance = (RazorHtmlTemplate) Activator.CreateInstance(generatedType);
     var html = instance.generate(model);
     return html;
 }
Esempio n. 30
0
        private Type ResolveTypeImpl(Assembly startAssembly, string typeName, bool ignoreCase)
        {
            Type modelType = null;
            if (startAssembly != null)
            {
                modelType = startAssembly.GetType(typeName, false, ignoreCase);
                if (modelType != null) return modelType;
            }

            if (KnownGoodAssemblies.Any(assembly => (modelType = FindTypeInAssembly(assembly, typeName)) != null))
            {
                return modelType;
            }

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if ((modelType = FindTypeInAssembly(assembly, typeName)) != null)
                {
                    KnownGoodAssemblies.Add(assembly);
                    return modelType;
                }
            }

            return null;
        }
Esempio n. 31
0
        private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
                                                               String typeName,
                                                               bool ignoreCase,
                                                               Reflection.BindingFlags bindingAttr,
                                                               Reflection.Binder binder,
                                                               Object[] args,
                                                               Globalization.CultureInfo culture,
                                                               Object[] activationAttributes,
                                                               Security.Policy.Evidence securityInfo)
        {
#if FEATURE_CAS_POLICY
            Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null);
#endif // FEATURE_CAS_POLICY

#pragma warning disable 618
            Reflection.Assembly assembly = Reflection.Assembly.LoadFrom(assemblyFile); //, securityInfo);
#pragma warning restore 618
            Type t = assembly.GetType(typeName, true, ignoreCase);

            Object o = Activator.CreateInstance(t,
                                                bindingAttr,
                                                binder,
                                                args,
                                                culture,
                                                activationAttributes);

            // Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
            if (o == null)
            {
                return(null);
            }
            else
            {
                ObjectHandle Handle = new ObjectHandle(o);
                return(Handle);
            }
        }
Esempio n. 32
0
		static Type GetTestCase (string name, SR.Assembly assembly)
		{
			return assembly.GetType (name);
		}
Esempio n. 33
0
        public void send()
        {
            string dbtype    = "sqlserver";
            string dbconnStr = "server=sh-cdb-3ql7v8s2.sql.tencentcdb.com;port=63816;database=dongtou_kefu;uid=qjroot;pwd=qijin=mysql;CharSet=utf8";

            //读取dll
            System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(@"Qj.Models.dll");
            var listmodel = a.DefinedTypes;

            List <TableModel> listtm = new List <TableModel>();

            //循环类
            foreach (var item in listmodel)
            {
                System.Type t = a.GetType(item.FullName);

                //3.2.2 获取实体类类型对象
                //Type t = typeof(obj["Sys_Config"]);
                //3.2.3 获取实体类所有的公共属性
                List <PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
                //3.2.4 创建实体属性字典集合
                Dictionary <string, PropertyInfo> dicPropertys = new Dictionary <string, PropertyInfo>();
                //3.2.5 将实体属性中要修改的属性名 添加到字典集合中  键:属性名  值:属性对象
                DescriptionAttribute attributeTab = Attribute.GetCustomAttribute(t, typeof(DescriptionAttribute)) as DescriptionAttribute;
                //获取表名
                TableAttribute attributeTabName = Attribute.GetCustomAttribute(t, typeof(TableAttribute)) as TableAttribute;

                var tm = new TableModel();

                if (attributeTabName == null)
                {
                    Shell.WriteLineYellow(t.Name + "  表名未维护跳出");
                    Shell.WriteLine("");
                    continue;;
                }
                else
                {
                    tm.TableName = attributeTabName.Name;
                }

                if (attributeTab != null)
                {
                    tm.TableName = attributeTab.Description;
                }
                tm.listTCmodel = new List <TColumnModel>();

                propertyInfos.ForEach(p =>
                {
                    //Console.WriteLine(p.Name);
                    DescriptionAttribute attribute = Attribute.GetCustomAttribute(p, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    var tc        = new TColumnModel();
                    tc.ColumnName = p.Name;
                    if (attribute != null)
                    {
                        tc.Description = attribute.Description;
                    }
                    tm.listTCmodel.Add(tc);
                });
            }

            #region 生成说明

            if (dbtype == "sqlserver")
            {
                new Sqlserverdb(dbconnStr);

                string sqlcc = "select   *   from   dbo.sysobjects   where   id   =   object_id(N'CreateColumnDescriptions')   and   OBJECTPROPERTY(id, N'IsProcedure')   =   1";
                string sqltb = "select   *   from   dbo.sysobjects   where   id   =   object_id(N'CreateTableDescriptions')   and   OBJECTPROPERTY(id, N'IsProcedure')   =   1";
                var    ishas = Sqlserverdb.ExecuteScalar(sqlcc);
                if (ishas == null || ishas.ToString() == "")
                {
                    #region sql
                    var exsql = @"
                                        SET ANSI_NULLS ON
                                        GO
                                        SET QUOTED_IDENTIFIER ON
                                        GO
                                        -- =============================================
                                        -- Author:		<Author,,Name>
                                        -- Create date: <Create Date,,>
                                        -- Description:	<Description,,>
                                        -- =============================================
                                        CREATE PROCEDURE CreateColumnDescriptions 
	                                        @TableName varchar(200),
	                                        @Column varchar(200),
	                                        @Descriptions  varchar(200),
	                                        @isup int
                                        AS
                                        BEGIN
                                         /*
                                         exec  CreateColumnDescriptions 'ArticleLikes','id','xxx2',0
                                         */
	
	                                        if exists(
					                                         SELECT t.[name] AS 表名,c.[name] AS 字段名,cast(ep.[value] 
						                                        as varchar(100)) AS [字段说明]
						                                        FROM sys.tables AS t
						                                        INNER JOIN sys.columns 
						                                        AS c ON t.object_id = c.object_id
						                                         LEFT JOIN sys.extended_properties AS ep 
						                                        ON ep.major_id = c.object_id AND ep.minor_id = c.column_id WHERE ep.class =1 
						                                        AND t.name=@TableName  and c.name=@Column
		                                          )
		                                        begin
		
			                                        if(@isup=1)
				                                        begin
						                                        EXECUTE sp_updateextendedproperty N'MS_Description', @Descriptions, N'user', N'dbo', N'table', @TableName, N'column', @Column
				                                        end
		                                        end
	                                        else
		                                        begin
						                                        EXECUTE sp_addextendedproperty N'MS_Description', @Descriptions, N'user', N'dbo', N'table', @TableName, N'column', @Column
		                                        end


                                        END
                                        GO

                                    ";
                    #endregion

                    Sqlserverdb.ExecuteNonQuery(exsql);
                }
                ishas = Sqlserverdb.ExecuteScalar(sqltb);
                if (ishas == null || ishas.ToString() == "")
                {
                    #region sql
                    var exsql = @"
                                    SET ANSI_NULLS ON
                                    GO
                                    SET QUOTED_IDENTIFIER ON
                                    GO
                                    -- =============================================
                                    -- Author:		<Author,,Name>
                                    -- Create date: <Create Date,,>
                                    -- Description:	<Description,,>
                                    -- =============================================
                                    CREATE PROCEDURE CreateTableDescriptions 
                                        @TableName varchar(200),
                                        @Descriptions  varchar(200),
                                        @isup int
                                    AS
                                    BEGIN
                                     /*
                                     exec  CreateTableDescriptions 'ArticleLikes','xxx',0
                                     */
                                        
                                        if exists(
                                                SELECT tbs.name 表名,ds.value 描述   FROM sys.extended_properties ds  
                                                            LEFT JOIN sysobjects tbs ON ds.major_id=tbs.id  WHERE  ds.minor_id=0 and  tbs.name=@TableName)
                                            begin
                                            
                                                if(@isup=1)
                                                    begin
                                                            EXEC sp_updateextendedproperty 'MS_Description',@Descriptions,'user',dbo,'table',@TableName,null,null
                                                    end
                                            end
                                        else
                                            begin
                                                            EXECUTE sp_addextendedproperty N'MS_Description',@Descriptions, N'user', N'dbo', N'table', @TableName, NULL, NULL
                                            end
                                    
                                    
                                    END
                                    GO
                                    ";
                    #endregion

                    Sqlserverdb.ExecuteNonQuery(exsql);
                }
            }

            foreach (var item in listtm)
            {
            }

            #endregion
        }
Esempio n. 34
0
 public Type GetType(String name)
 {
     return(_assembly.GetType(name));
 }
 public SerializationCallbacksIntegrationTests()
 {
     assembly = this.GetType().Assembly;
     type     = assembly.GetType("PostSharp.Community.Virtuosity.Tests.Fody.Assembly.AssemblyToProcess.SerializationCallbackMethods", true);
 }
Esempio n. 36
0
        /// <summary>
        /// 实例化WebServices
        /// </summary>s
        /// <param name="url">WebServices地址</param>
        /// <param name="methodname">调用的方法</param>
        /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
        public static object InvokeWebService(string url, string methodname, string ns, object[] args)
        {
            //这里的namespace是需引用的webservices的命名空间
            string @namespace = ns;

            try
            {
                //获取WSDL
                WebClient                  wc        = new WebClient();
                Stream                     stream    = wc.OpenRead(url);
                ServiceDescription         sd        = ServiceDescription.Read(stream);
                string                     classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi       = new ServiceDescriptionImporter();
                sdi.ProtocolName          = "Soap";
                sdi.Style                 = ServiceDescriptionImportStyle.Client;
                sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                ServiceDescriptionImportWarnings warning = sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                //ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                return(ex.InnerException.Message);
            }
        }
 public static Type TypeUnit(this System.Reflection.Assembly assembly)
 {
     return(assembly.GetType("System.Web.UI.WebControls.Unit"));
 }
 public static Type CreateType <T>(System.Reflection.Assembly assembly)
 {
     return(assembly.GetType(typeof(T).FullName ?? string.Empty) ?? throw new InvalidOperationException());
 }
Esempio n. 39
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            ElementId deleteId = ElementId.InvalidElementId;

            //If we already have a form stored...
            if (this.Elements.Any())
            {
                //And register the form for deletion. Since we've already deleted it here manually, we can
                //pass "true" as the second argument.
                deleteId = this.Elements[0];
                this.DeleteElement(this.Elements[0], false);
            }

            //Surface argument
            Solid mySolid = (Solid)((Value.Container)args[0]).Item;

            GenericForm ffe = null;

            //use reflection to check for the method

            System.Reflection.Assembly revitAPIAssembly = System.Reflection.Assembly.GetAssembly(typeof(GenericForm));
            Type FreeFormType = revitAPIAssembly.GetType("Autodesk.Revit.DB.FreeFormElement", true);
            bool methodCalled = false;

            if (FreeFormType != null)
            {
                MethodInfo[] freeFormMethods    = FreeFormType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                String       nameOfMethodCreate = "Create";
                foreach (MethodInfo m in freeFormMethods)
                {
                    if (m.Name == nameOfMethodCreate)
                    {
                        object[] argsM = new object[2];
                        argsM[0] = this.UIDocument.Document;
                        argsM[1] = mySolid;

                        methodCalled = true;

                        ffe = (GenericForm)m.Invoke(null, argsM);
                        break;
                    }
                }
            }
            if (ffe != null)
            {
                this.Elements.Add(ffe.Id);
                freeFormSolids[ffe.Id] = mySolid;
                if (deleteId != ElementId.InvalidElementId)
                {
                    if (previouslyDeletedFreeForms == null)
                    {
                        previouslyDeletedFreeForms = new Dictionary <ElementId, ElementId>();
                    }
                    previouslyDeletedFreeForms[ffe.Id] = deleteId;
                    if (previouslyDeletedFreeForms.ContainsKey(deleteId))
                    {
                        ElementId previouslyDeletedId = previouslyDeletedFreeForms[deleteId];
                        if (previouslyDeletedId != ElementId.InvalidElementId)
                        {
                            freeFormSolids.Remove(previouslyDeletedFreeForms[deleteId]);
                        }
                        previouslyDeletedFreeForms.Remove(deleteId);
                    }
                }
            }
            else if (!methodCalled)
            {
                throw new Exception("This method is not available before 2014 release.");
            }

            return(Value.NewContainer(ffe));
        }
Esempio n. 40
0
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler      icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// For invoking Sabre Webservices, it's requiered to add to the request the atribute
        /// MessageHeader which is the same for all SWS classes. This method dinamically loads this atribute
        /// by usgin reflexion.
        /// </summary>
        /// <param name="typeMessageHeader">Type of class expected</param>
        /// <param name="vo_MessageHeader">Parameters to fill the MessageHeader object</param>
        /// <returns></returns>
        internal object getMessageHeader(Type typeMessageHeader, VO_MessageHeader vo_MessageHeader)
        {
            object messageHeader = Activator.CreateInstance(typeMessageHeader);

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();

            //MessageData
            DateTime dtmDate = DateTime.UtcNow;
            string   strDate = dtmDate.ToString("s") + "Z";

            PropertyInfo propertyInfoMessageData = messageHeader.GetType().GetProperty("MessageData");
            Type         typeMessageData         = assembly.GetType(propertyInfoMessageData.PropertyType.FullName);
            object       messageData             = Activator.CreateInstance(typeMessageData);

            messageData.GetType().GetProperty("Timestamp").SetValue(messageData, strDate, null);
            messageData.GetType().GetProperty("MessageId").SetValue(messageData, vo_MessageHeader.StrMessageId, null);

            //Service
            System.Reflection.PropertyInfo propertyInfoService = messageHeader.GetType().GetProperty("Service");
            Type   typeService = assembly.GetType(propertyInfoService.PropertyType.FullName);
            object service     = Activator.CreateInstance(typeService);

            service.GetType().GetProperty("Value").SetValue(service, vo_MessageHeader.StrValue, null);
            messageHeader.GetType().GetProperty("Service").SetValue(messageHeader, service, null);

            messageHeader.GetType().GetProperty("MessageData").SetValue(messageHeader, messageData, null);
            messageHeader.GetType().GetProperty("CPAId").SetValue(messageHeader, vo_MessageHeader.StrCPAId, null);
            messageHeader.GetType().GetProperty("Action").SetValue(messageHeader, vo_MessageHeader.StrAction, null);

            //From
            System.Reflection.PropertyInfo propertyInfoFrom = messageHeader.GetType().GetProperty("From");
            Type   typeFrom = assembly.GetType(propertyInfoFrom.PropertyType.FullName);
            object from     = Activator.CreateInstance(typeFrom);

            //PartyIdFrom
            PropertyInfo propertyInfoPartyID = from.GetType().GetProperty("PartyId");
            Type         typeFromPartyIds    = assembly.GetType(propertyInfoPartyID.PropertyType.FullName);
            Array        partyIdsAuxiliar    = Array.CreateInstance(typeFromPartyIds, 1);
            Type         typeFromPartyId     = typeFromPartyIds.GetElementType();
            Array        partyIds            = Array.CreateInstance(typeFromPartyId, 1);

            object fromPartyId = Activator.CreateInstance(typeFromPartyId);

            fromPartyId.GetType().GetProperty("Value").SetValue(fromPartyId, vo_MessageHeader.StrTo, null);
            partyIds.SetValue(fromPartyId, 0);
            from.GetType().GetProperty("PartyId").SetValue(from, partyIds, null);
            messageHeader.GetType().GetProperty("From").SetValue(messageHeader, from, null);

            //To
            System.Reflection.PropertyInfo propertyInfoTo = messageHeader.GetType().GetProperty("To");
            Type   typeTo = assembly.GetType(propertyInfoTo.PropertyType.FullName);
            object to     = Activator.CreateInstance(typeTo);

            //PartyIdTo
            partyIds    = Array.CreateInstance(typeFromPartyId, 1);
            fromPartyId = Activator.CreateInstance(typeFromPartyId);
            fromPartyId.GetType().GetProperty("Value").SetValue(fromPartyId, vo_MessageHeader.StrTo, null);
            partyIds.SetValue(fromPartyId, 0);
            to.GetType().GetProperty("PartyId").SetValue(to, partyIds, null);
            messageHeader.GetType().GetProperty("To").SetValue(messageHeader, to, null);

            //ConversationId
            messageHeader.GetType().GetProperty("ConversationId").SetValue(messageHeader, vo_MessageHeader.StrConversationId, null);

            return(messageHeader);
        }
Esempio n. 42
0
        public static string SoapRequest(string url, string method, object[] args)
        {
            //这里的namespace是需引用的webservices的命名空间,在这里是写死的,大家可以加一个参数从外面传进来。
            string @namespace = "client";

            try
            {
                System.Reflection.Assembly assembly = null;
                string classname = string.Empty;
                if (_dicWebServiceAssemblys.ContainsKey(url) == false)
                {
                    //获取WSDL
                    WebClient          wc     = new WebClient();
                    Stream             stream = wc.OpenRead(url + "?WSDL");
                    ServiceDescription sd     = ServiceDescription.Read(stream);
                    classname = sd.Services[0].Name;
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);

                    //生成客户端代理类代码
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    CSharpCodeProvider csc = new CSharpCodeProvider();
                    ICodeCompiler      icc = csc.CreateCompiler();

                    //设定编译参数
                    CompilerParameters cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false;
                    cplist.GenerateInMemory   = true;
                    cplist.ReferencedAssemblies.Add("System.dll");
                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");

                    //编译代理类
                    CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }

                    //生成代理实例,并调用方法
                    assembly = cr.CompiledAssembly;
                    lock (_dicWebServiceAssemblys)
                    {
                        if (_dicWebServiceAssemblys.ContainsKey(url) == false)
                        {
                            _dicWebServiceAssemblys.Add(url, assembly);
                        }
                    }
                    lock (_dicWebServiceClassName)
                    {
                        if (_dicWebServiceClassName.ContainsKey(url) == false)
                        {
                            _dicWebServiceClassName.Add(url, classname);
                        }
                    }
                }
                else
                {
                    assembly  = _dicWebServiceAssemblys[url];
                    classname = _dicWebServiceClassName[url];
                }
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(method);
                return(mi.Invoke(obj, args).ToString());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 43
0
        /// <summary>
        /// 呼叫WebService
        /// </summary>
        /// <param name="wsUrl">WebService地址</param>
        /// <param name="className">類名</param>
        /// <param name="methodName">方法名稱</param>
        /// <param name="soapHeader">SOAP頭</param>
        /// <param name="args">引數列表</param>
        /// <returns>返回呼叫結果</returns>
        public static object InvokeWebService(string url, string classname, string methodname, SoapHeader soapHeader, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = GetWsClassName(url);
            }

            try
            {
                //獲取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客戶端代理類程式碼
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler      icc = csc.CreateCompiler();

                //設定編譯引數
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //編譯代理類
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理例項,並呼叫方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);


                #region soapheader資訊
                FieldInfo[] arry = t.GetFields();

                FieldInfo fieldHeader = null;
                //soapheader 物件值
                object objHeader = null;
                if (soapHeader != null)
                {
                    fieldHeader = t.GetField(soapHeader.ClassName + "Value");

                    Type tHeader = assembly.GetType(@namespace + "." + soapHeader.ClassName);
                    objHeader = Activator.CreateInstance(tHeader);

                    foreach (KeyValuePair <string, object> property in soapHeader.Properties)
                    {
                        FieldInfo[] arry1 = tHeader.GetFields();
                        int         ts    = arry1.Count();
                        FieldInfo   f     = tHeader.GetField(property.Key);
                        if (f != null)
                        {
                            f.SetValue(objHeader, property.Value);
                        }
                    }
                }

                if (soapHeader != null)
                {
                    //設定Soap頭
                    fieldHeader.SetValue(obj, objHeader);
                }

                #endregion


                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Esempio n. 44
0
        private static X509Certificate2 ReadPECertificateFromBinaryImage(string filePath, bool verifyCertificateTrust, bool verifyIntegrity)
        {
            TheBaseAssets.MySYSLOG?.WriteToLog(eDEBUG_LEVELS.ESSENTIALS, 666, "ReadPECertificateFromBinaryImage", $"Trying PE load Cert from: {filePath}", eMsgLevel.l7_HostDebugMessage);

            X509Certificate2 firstSignerCert = null;

            // PE info from https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
            using (var fileStream = File.OpenRead(filePath))
            {
                // Read the PESignature Offset
                UInt32 peSignatureOffset;
                {
                    if (fileStream.Seek(0x3c, SeekOrigin.Begin) != 0x3c)
                    {
                        return(null);
                    }

                    if (!ReadUInt32LittleEndian(fileStream, out peSignatureOffset))
                    {
                        return(null);
                    }
                    if (peSignatureOffset < 0x3c + 4)
                    {
                        return(null);
                    }
                }
                // Read and verify the PESignature ("PE")
                {
                    if (fileStream.Seek(peSignatureOffset, SeekOrigin.Begin) != peSignatureOffset)
                    {
                        return(null);
                    }

                    var peSignatureBytes = new byte[4];
                    if (fileStream.Read(peSignatureBytes, 0, peSignatureBytes.Length) != peSignatureBytes.Length)
                    {
                        return(null);
                    }
                    if (!peSignatureBytes.SequenceEqual(new Byte[] { (byte)'P', (byte)'E', 0, 0 }))
                    {
                        return(null);
                    }
                }
                UInt32 headerOffset = peSignatureOffset + 4;

                // Verify SizeOfOptionalHeader field
                {
                    UInt32 sizeofOptionalHeaderOffset = headerOffset + 16;
                    if (fileStream.Seek(sizeofOptionalHeaderOffset, SeekOrigin.Begin) != sizeofOptionalHeaderOffset)
                    {
                        return(null);
                    }
                    if (!ReadUInt16LittleEndian(fileStream, out ushort sizeOfOptionalHeader))
                    {
                        return(null);
                    }
                    if (sizeOfOptionalHeader < 136)
                    {
                        return(null);
                    }
                }

                UInt32 optionalHeaderOffset = headerOffset + 20;

                // Determine PE vs. PE+
                bool isPEPlus;
                {
                    if (fileStream.Seek(optionalHeaderOffset, SeekOrigin.Begin) != optionalHeaderOffset)
                    {
                        return(null);
                    }

                    var magicNumber = new byte[2];
                    if (fileStream.Read(magicNumber, 0, magicNumber.Length) != magicNumber.Length)
                    {
                        return(null);
                    }
                    if (magicNumber.SequenceEqual(new Byte[] { 0xb, 1 }))
                    {
                        isPEPlus = false;
                    }
                    else if (magicNumber.SequenceEqual(new Byte[] { 0xb, 2 }))
                    {
                        isPEPlus = true;
                    }
                    else
                    {
                        return(null);
                    }
                }
                UInt32 dataDirectoryOffset;
                if (isPEPlus)
                {
                    dataDirectoryOffset = optionalHeaderOffset + 112;
                }
                else
                {
                    dataDirectoryOffset = optionalHeaderOffset + 96;
                }


                // Read Certificate Table offset and size
                UInt32 certificateTableOffset;
                UInt32 certificateTableSize;
                UInt32 certificateTableEntryOffset = dataDirectoryOffset + 4 * 8; // Table entry 4, each entry is 8 bytes
                {
                    if (fileStream.Seek(certificateTableEntryOffset, SeekOrigin.Begin) != certificateTableEntryOffset)
                    {
                        return(null);
                    }

                    if (!ReadUInt32LittleEndian(fileStream, out certificateTableOffset))
                    {
                        return(null);
                    }
                    if (!ReadUInt32LittleEndian(fileStream, out certificateTableSize))
                    {
                        return(null);
                    }
                }

                if (certificateTableSize == 0)
                {
                    // no certs/signatures
                    return(null);
                }
                if (certificateTableSize > 10 * 1024 * 1024) // 10 MB limit for certs
                {
                    // protect against overly large (presumably malicious) certificate table size
                    return(null);
                }
                if (certificateTableOffset < dataDirectoryOffset + 120)
                {
                    // sanity check that offset doesn't point before or into the data table
                    return(null);
                }

                UInt32 currentCertificateTableOffset = certificateTableOffset;
                UInt32 remainingCertificateTableSize = certificateTableSize;

                while (remainingCertificateTableSize >= 8)
                {
                    if (fileStream.Seek(currentCertificateTableOffset, SeekOrigin.Begin) != currentCertificateTableOffset)
                    {
                        return(null);
                    }

                    if (!ReadUInt32LittleEndian(fileStream, out var certEntryLength))
                    {
                        return(null);
                    }
                    if (certEntryLength <= 8)
                    {
                        // Empty/incomplete cert entry
                        return(null);
                    }
                    if (certEntryLength > remainingCertificateTableSize)
                    {
                        return(null);
                    }

                    if (!ReadUInt16LittleEndian(fileStream, out var certRevision))
                    {
                        return(null);
                    }
                    if (!ReadUInt16LittleEndian(fileStream, out var certType))
                    {
                        return(null);
                    }

                    var certificateBytes = new byte[certEntryLength - 8];
                    if (fileStream.Read(certificateBytes, 0, certificateBytes.Length) != certificateBytes.Length)
                    {
                        return(null);
                    }
                    if (verifyIntegrity)
                    {
#if !CDE_STANDARD
                        var signedCms = new SignedCms();
#else
                        // .Net Standard requires System.Security.Cryptography.Pkcs NuGet package for this functionality (also part of Microsoft.Windows.Compatibility): make this optional
                        dynamic signedCms = null;
                        System.Reflection.Assembly pkcsAssembly = null;
                        try
                        {
                            pkcsAssembly = System.Reflection.Assembly.Load("System.Security.Cryptography.Pkcs, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        } // {System.Security.Cryptography.Pkcs, Version=4.0.3.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a}
                        catch (Exception e) when(e is FileLoadException || e is FileNotFoundException)
                        {
                            try
                            {
                                pkcsAssembly = System.Reflection.Assembly.Load("System.Security.Cryptography.Pkcs");
                            }
                            catch (Exception e2) when(e2 is FileLoadException || e2 is FileNotFoundException)
                            {
                                // No PKCS crypto installed: degrade to not verify integrity
                                DontVerifyIntegrity = true;
                                verifyIntegrity     = false;
                            }
                        }
                        catch { }
                        if (pkcsAssembly != null)
                        {
                            var cmsType = pkcsAssembly.GetType("System.Security.Cryptography.Pkcs.SignedCms", false);
                            if (cmsType != null)
                            {
                                try
                                {
                                    signedCms = Activator.CreateInstance(cmsType);
                                }
                                catch { }
                            }
                        }
                        if (signedCms == null && verifyIntegrity)
                        {
                            return(null);
                        }
#endif
                        if (verifyIntegrity)
                        {
                            try
                            {
                                signedCms.Decode(certificateBytes);
                            }
                            catch (Exception failed)
                            {
                                TheBaseAssets.MySYSLOG?.WriteToLog(eDEBUG_LEVELS.OFF, 666, "ReadPECertificateFromBinaryImage", failed.ToString(), eMsgLevel.l1_Error);
                                return(null);
                            }
                            try
                            {
                                signedCms.CheckSignature(!verifyCertificateTrust);
                            }
                            catch
                            {
                                return(null);
                            }

                            if (signedCms.SignerInfos.Count < 1)
                            {
                                return(null);
                            }
                            if (firstSignerCert == null)
                            {
                                firstSignerCert = signedCms.SignerInfos[0].Certificate;
                            }

                            // TODO Propertly parse the SpcIndirectDataContent structure per Authenticode Spec
                            // For SHA1 the hash is always in the last 20 bytes of the content info: if another algorithm is used we will currently reject the signature
                            var    signedHash   = new byte[20];
                            byte[] contentBytes = signedCms.ContentInfo.Content;
                            signedHash = contentBytes.Skip(contentBytes.Length - 20).ToArray();

                            // Compute the image hash, ignoring certain sections per Authenticode spec
                            var fileHash = ComputePEHash(fileStream, optionalHeaderOffset, headerOffset, dataDirectoryOffset, certificateTableSize, certificateTableEntryOffset);
                            //var monoHash = new Mono.Security.Authenticode.AuthenticodeBase().HashFile(filePath, "SHA1");

                            if (fileHash?.SequenceEqual(signedHash) != true)
                            {
                                // File hash doesn't match signature: file was tampered with!
                                return(null);
                            }
                        }
                    }
                    if (!verifyIntegrity && firstSignerCert == null)
                    {
                        try
                        {
                            var certs = new X509Certificate2Collection();
                            certs.Import(certificateBytes);
                            if (TSM.L(eDEBUG_LEVELS.ESSENTIALS))
                            {
                                TheBaseAssets.MySYSLOG?.WriteToLog(eDEBUG_LEVELS.ESSENTIALS, 25666, "ReadPECertificateFromBinaryImage", $"Certs Found: {certs?.Count}", eMsgLevel.l7_HostDebugMessage);
                                int i = 0;
                                foreach (var cert in certs)
                                {
                                    TheBaseAssets.MySYSLOG?.WriteToLog(eDEBUG_LEVELS.ESSENTIALS, 25666, "ReadPECertificateFromBinaryImage", $"Cert [{i++}]: {cert.Thumbprint}", eMsgLevel.l7_HostDebugMessage);
                                }
                            }
                            firstSignerCert = Environment.OSVersion.Platform == PlatformID.Unix && certs.Count > 0 ? certs[certs.Count - 1] : certs[0];
                            //firstSignerCert = certs[0];
                        }
                        catch
                        {
                            firstSignerCert = null;
                        }
                    }

                    remainingCertificateTableSize -= certEntryLength;
                    currentCertificateTableOffset += certEntryLength;
                }
                return(firstSignerCert);
            }
        }
        public Type LoadObjectTypeFromAssembly(string layoutFilename, string layoutNameSpace, string classNameToLoad, string friendlyName = "")
        {
            Type     typeToLoad = default;
            FileInfo layoutFile;

            try
            {
                layoutFile = new FileInfo(enVars.libraryPath + layoutFilename);
                layoutFile.Refresh();
                if (!layoutFile.Exists)
                {
                    errorMessage = "Layout file not found. You need to reinstall the program";
                    return(null);
                }
            }
            catch (Exception ex) {
                errorMessage = "Error Layout file (" + ex.Message.ToString() + "). You need to reinstall the program";
                return(null);
            }

            if (friendlyName.Equals(""))
            {
                friendlyName = classNameToLoad;
            }

            try
            {
                System.Reflection.Assembly assemblyRaw = System.Reflection.Assembly.LoadFrom(enVars.libraryPath + layoutFilename);
                context.Add(friendlyName, new CollectibleAssemblyLoadContext());
                System.Reflection.Assembly assembly = context[friendlyName].LoadFromAssemblyPath(enVars.libraryPath + layoutFilename);

                // check if assembly has assemblies to load
                Type typeMainLayoutIni = assembly.GetType(layoutNameSpace + ".initializeAssembly");
                if (typeMainLayoutIni != null)
                {
                    Object     iniClass   = Activator.CreateInstance(typeMainLayoutIni, true);
                    MethodInfo methodInfo = typeMainLayoutIni.GetMethod("AssembliesToLoadAtStart");
                    if (methodInfo != null)
                    {
                        Dictionary <string, Environment.Core.environmentAssembliesClass> assembliesOn = (Dictionary <string, Environment.Core.environmentAssembliesClass>)methodInfo.Invoke(iniClass, default);
                        getAssemblies = enVarsAssemblies.Union(assembliesOn.Where(k => !enVarsAssemblies.ContainsKey(k.Key))).ToDictionary(k => k.Key, v => v.Value);
                    }
                }

                string t = "";
                foreach (Type type in assembly.GetTypes())
                {
                    t += type.FullName + " >> ";
                }
                typeToLoad = assembly.GetType(layoutNameSpace + "." + classNameToLoad);
                if (typeToLoad is null)
                {
                    errorMessage = "Class not found or invalid namespace";
                }
            }

            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return(null);
            }
            return(typeToLoad);
        }
Esempio n. 46
0
 public static EditorWindow InspectorWindow()
 {
     System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly;
     return(EditorWindow.GetWindow(assembly.GetType("UnityEditor.InspectorWindow")));
 }
 private System.Type GetType(string name)
 {
     return(_assembly.GetType(name));
 }
Esempio n. 48
0
        /// <summary>
        /// GetWsProxyType 获取目标Web服务对应的代理类型
        /// </summary>
        /// <param name="wsUrl">目标Web服务的url</param>
        /// <param name="classname">Web服务的class名称,如果不需要指定,则传入null</param>
        public static Type GetWsProxyType(string wsUrl, string classname)
        {
            string @namespace = "ESBasic.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(wsUrl);
            }
            string cacheKey = wsUrl + "@" + classname;

            if (WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey))
            {
                return(WebServiceHelper.WSProxyTypeDictionary[cacheKey]);
            }


            //获取WSDL
            WebClient                  wc     = new WebClient();
            Stream                     stream = wc.OpenRead(wsUrl + "?WSDL");
            ServiceDescription         sd     = ServiceDescription.Read(stream);
            ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(@namespace);

            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider csc = new CSharpCodeProvider();
            ICodeCompiler      icc = csc.CreateCompiler();

            //设定编译参数
            CompilerParameters cplist = new CompilerParameters();

            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory   = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");

            //编译代理类
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);

            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new Exception(sb.ToString());
            }

            //生成代理实例,并调用方法
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type[] ts          = assembly.GetTypes();
            Type   wsProxyType = assembly.GetType(@namespace + "." + classname, true, true);


            lock (WebServiceHelper.WSProxyTypeDictionary)
            {
                if (!WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey))
                {
                    WebServiceHelper.WSProxyTypeDictionary.Add(cacheKey, wsProxyType);
                }
            }
            return(wsProxyType);
        }
Esempio n. 49
0
    private static void AttachSerializeObj(GameObject obj, string behaviourName, System.Reflection.Assembly assembly,
                                           List <IMark> processedMarks = null)
    {
        if (null == processedMarks)
        {
            processedMarks = new List <IMark>();
        }

        IMark  uiMark    = obj.GetComponent <IMark>();
        string className = string.Empty;

        //if (uiMark != null)
        //{
        //    className = GetProjectNamespace() + "." + uiMark.ComponentName;

        //    // 这部分
        //    if (uiMark.GetUIMarkType() != UIMarkType.DefaultUnityElement)
        //    {
        //        var ptuimark = obj.GetComponent<UIMark>();
        //        if (ptuimark != null)
        //        {
        //            UnityEngine.Object.DestroyImmediate(ptuimark, true);
        //        }
        //    }
        //}
        //else
        //{
        //    className = behaviourName;
        //}
        className = behaviourName;

        // 得到类名
        System.Type t = assembly.GetType(className);
        // GameObject上没有此组件就添加
        Component com = obj.GetComponent(t) ?? obj.AddComponent(t);
        // 序列化这个组件
        SerializedObject sObj = new SerializedObject(com);

        IMark[] uiMarks = obj.GetComponentsInChildren <IMark>(true);

        foreach (var elementMark in uiMarks)
        {
            if (processedMarks.Contains(elementMark))
            {
                continue;
            }

            processedMarks.Add(elementMark);

            string uiType = elementMark.mComponentTypeName;
            // 成员变量名字
            string propertyName = UICodeGenerator.mPreFormat + elementMark.mTransform.gameObject.name;

            if (sObj.FindProperty(propertyName) == null)
            {
                Debug.LogFormat("sObj is Null:{0} {1} {2}", propertyName, uiType, sObj);
                continue;
            }

            sObj.FindProperty(propertyName).objectReferenceValue = elementMark.mTransform.gameObject;

            //AttachSerializeObj(elementMark.mTransform.gameObject, elementMark.ComponentName, assembly, processedMarks);
        }

        sObj.ApplyModifiedPropertiesWithoutUndo();
    }
Esempio n. 50
0
        DisplayUnitType getDisplayUnitTypeOfFormatUnits()
        {
            Type RevitDoc = typeof(Autodesk.Revit.DB.Document);

            var propertyInfo = RevitDoc.GetProperties();

            Object unitObject      = null;
            Type   ProjectUnitType = null;

            foreach (PropertyInfo propertyInfoItem in propertyInfo)
            {
                if (propertyInfoItem.Name == "ProjectUnit")
                {
                    //r2013
                    System.Reflection.Assembly revitAPIAssembly = System.Reflection.Assembly.GetAssembly(RevitDoc);
                    ProjectUnitType = revitAPIAssembly.GetType("Autodesk.Revit.DB.ProjectUnit", false);
                    unitObject      = (Object)propertyInfoItem.GetValue((Object)dynRevitSettings.Doc.Document, null);
                    break;
                }
            }
            if (unitObject == null)
            {
                MethodInfo[] docMethods = RevitDoc.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                foreach (MethodInfo ds in docMethods)
                {
                    if (ds.Name == "GetUnits")
                    {
                        //r2014
                        object[] argsM = new object[0];
                        unitObject = ds.Invoke(dynRevitSettings.Doc.Document, argsM);
                        System.Reflection.Assembly revitAPIAssembly = System.Reflection.Assembly.GetAssembly(RevitDoc);
                        ProjectUnitType = revitAPIAssembly.GetType("Autodesk.Revit.DB.Units", false);
                        break;
                    }
                }
            }

            if (unitObject != null)
            {
                MethodInfo[] unitsMethods = ProjectUnitType.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

                foreach (MethodInfo ms in unitsMethods)
                {
                    if (ms.Name == "GetFormatOptions" || ms.Name == "get_FormatOptions")
                    {
                        object[] argsM = new object[1];
                        argsM[0] = UnitType.UT_Length;

                        FormatOptions LengthFormatOptions = (FormatOptions)ms.Invoke(unitObject, argsM);
                        if (LengthFormatOptions != null)
                        {
                            Type FormatOptionsType         = typeof(Autodesk.Revit.DB.FormatOptions);
                            var  FormatOptionsPropertyInfo = FormatOptionsType.GetProperties();
                            foreach (PropertyInfo propertyInfoItem2 in FormatOptionsPropertyInfo)
                            {
                                if (propertyInfoItem2.Name == "Units")
                                {
                                    //r2013
                                    return((DisplayUnitType)propertyInfoItem2.GetValue((Object)LengthFormatOptions, null));
                                }
                                else if (propertyInfoItem2.Name == "DisplayUnits")
                                {
                                    //r2014
                                    return((DisplayUnitType)propertyInfoItem2.GetValue((Object)LengthFormatOptions, null));
                                }
                            }
                        }
                    }
                }
            }
            return(new DisplayUnitType());
        }
Esempio n. 51
0
        private void RegisterSinglonTypeToUnity(string implement, string liftCycle)
        {
            //获取程序集名称,判断是否已经有后缀
            string assemblyName = implement;

            string[] assemblyInfos = assemblyName.Split(';');
            if (assemblyInfos.Length != 2)
            {
                return;
            }

            assemblyName = assemblyInfos[0];

            string fileName = assemblyName.Replace(".dll", "").Replace(".DLL", "");

            if (assemblyName.LastIndexOf(".dll") < 0)
            {
                assemblyName += ".dll";
            }

            //string assemblyPath = System.IO.Path.Combine(PlatformConfig.ServerConfig.IOCSetting.AssemblyFilePath, assemblyName);

            ////判断程序集是否存在
            //if (!System.IO.File.Exists(assemblyPath))
            //    return;

            ////装载程序集
            //System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(assemblyPath);

            ////如果装载失败
            //if (assembly == null)
            //    return;
            string assemblyPath = string.Empty;

            var tempKeyValuePair = PlatformConfig.ServerConfig.KeyValueSettings.KeyValueItems.Where(pre => pre.Key.ToLower() == "ioc").FirstOrDefault();

            if (tempKeyValuePair != null && tempKeyValuePair.Value.ToLower() == "gac")
            {
                assemblyPath = this.GACAssemblys.Where(pre => pre.Split(',')[0].Contains(fileName)).FirstOrDefault();
            }

            //装载程序集
            System.Reflection.Assembly assembly = null;

            if (string.IsNullOrEmpty(assemblyPath))
            {
                assemblyPath = System.IO.Path.Combine(PlatformConfig.ServerConfig.IOCSetting.AssemblyFilePath, assemblyName);

                if (!Directory.Exists(PlatformConfig.ServerConfig.IOCSetting.AssemblyFilePath))
                {
                    assemblyPath = System.IO.Path.Combine(basePath, assemblyName);
                }
                else
                {
                    //判断程序集是否存在
                    if (!System.IO.File.Exists(assemblyPath) && PlatformConfig.ServerConfig.IOCSetting.AutomaticSniffing)
                    {
                        assemblyPath = System.IO.Path.Combine(basePath, assemblyName);
                    }
                }
                //判断程序集是否存在
                if (!System.IO.File.Exists(assemblyPath))
                {
                    return;
                }

                //装载程序集
                assembly = System.Reflection.Assembly.LoadFrom(assemblyPath);
            }
            else
            {
                //装载程序集
                assembly = System.Reflection.Assembly.Load(assemblyPath);
            }

            //如果装载失败
            if (assembly == null)
            {
                return;
            }

            if (assemblyFilters.Contains(fileName))
            {
                return;
            }

            //反射得到所有的程序集中的类型
            Type type = assembly.GetType(assemblyInfos[1]);

            if (type == null)
            {
                return;
            }

            RegisterCustomObjectItemType(type, liftCycle);
        }
Esempio n. 52
0
        public static string CompileCodeRunTime(string txtCodeSource,
                                                string featureCalling, string Disc, out DataTable dt,
                                                ref System.Reflection.Assembly assembly, TextBox txtConsole, string[] refs = null,
                                                object[] args = null)
        {
            if (txtCodeSource == "")
            {
                dt = null; return("");
            }
            CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>()
            {
                { "CompilerVersions", "v4.5" }
            });
            var             compileParameters = new CompilerParameters();
            CompilerResults results           = default(CompilerResults);

            compileParameters.GenerateInMemory      = true;
            compileParameters.TreatWarningsAsErrors = false;
            compileParameters.WarningLevel          = 0; //4
                                                         //compileParameters.CompilerOptions = "/Imports:System.Security.Cryptography,System.IO,System,System,System.Collections,System.Collections.Generic,System.Data.Common,System.Data,System.Drawing,System.Diagnostics,System.Windows.Forms,System.Linq,clbData,System.Xml.Linq,Microsoft.Office.Interop.Excel,Oracle.ManagedDataAccess.Client";
                                                         //compileParameters.CompilerOptions = compileParameters.CompilerOptions + " / optionexplicit + / optionstrict - / optioncompare:text / optimize - / debug + / warnaserror - / nowarn:42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 / optioninfer+ ";

            /*•0 - Turns off emission of all warning messages.
             * •1 - Displays severe warning messages.
             * •2 - Displays level 1 warnings plus certain, less - severe warnings, such as warnings about hiding class members.
             * •3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
             * •4 - Displays all level 3 warnings plus informational warnings.This is the default warning level at the command line.
             */

            string excel    = "",
                   excel_15 = @"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll",
                   excel_14 = @"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll";;

            if (File.Exists(excel_15))
            {
                excel = excel_15;
            }
            else
            {
                if (File.Exists(excel_14))
                {
                    excel = excel_14;
                }
            }

            if (refs == null)
            {
                string[] dRefs = { "System.Data.dll",                                "System.Data.DataSetExtensions.dll",
                                   "System.Core.dll",                                "System.dll",                       "System.Xml.dll",
                                   "System.Windows.Forms.dll",                       "System.Xml.Linq.dll",
                                   "System.DirectoryServices.dll",                   "System.Security.Principal.dll",
                                   "System.DirectoryServices.AccountManagement.dll",
                                   "Oracle.ManagedDataAccess.dll",                   excel,                              "System.Data.Linq.dll",
                                   "System.Drawing.dll",                             "ClbData.dll",
                                   "BouncyCastle.Crypto.dll",                        "Common.Logging.Core.dll",          "Common.Logging.dll",
                                   "itext.barcodes.dll",                             "itext.forms.dll",                  "itext.io.dll",              "itext.kernel.dll","itext.layout.dll",
                                   "itext.pdfa.dll",                                 "itext.sign.dll",                   "itext.styledxmlparser.dll", "itext.svg.dll",
                                   "itextsharp.dll",                                 "ZetaLongPaths.dll"
                                   //,Application.ExecutablePath +@"\Tracker.exe"
                };


                refs = dRefs;
            }
            if ((refs != null))
            {
                compileParameters.ReferencedAssemblies.AddRange(refs);
                try
                {
                    txtCodeSource = txtCodeSource.Replace("%featureCalling%", featureCalling).Replace("%cnnstring%", "Data Source = usazrwpora03v:1523 / uspicore; User ID = TRACKERDATA; Password = TRACKERDATA").Replace(" %Disc%", Disc);
                    results       = provider.CompileAssemblyFromSource(compileParameters, txtCodeSource);
                }
                catch (Exception ex)
                {
                    //Compile errors don't throw exceptions; you've got some deeper problem...
                    MessageBox.Show(ex.Message);
                    dt = null; return("Compile errors don't throw exceptions; you've got some deeper problem...");
                }
                //Output errors to the StatusBar
                if (results.Errors.Count == 0)
                {
                    assembly = results.CompiledAssembly;
                    Type program = assembly.GetType("Tracker.AddOn.Program");


                    MethodInfo main = program.GetMethod("Main");
                    if (main != null)
                    {
                        ParameterInfo[] parameters    = main.GetParameters();
                        object          classInstance = Activator.CreateInstance(program, null);
                        try
                        {
                            if (parameters.Length == 0)
                            {
                                main.Invoke(classInstance, null);
                            }
                            else
                            {
                                //object[] parametersArray = new object[] { "Hello" };
                                var result = main.Invoke(classInstance, args);

                                foreach (Attribute attr in program.GetCustomAttributes(true))
                                {
                                    //dt = program.GetCustomAttribute(DataTable);
                                }
                                dt = ((dynamic)classInstance).dt;
                                string txt = ((dynamic)classInstance).txtOut;
                                if (txtConsole != null)
                                {
                                    try { txtConsole.Text = txt; } catch { }
                                }
                                return("");
                            }
                        }
                        catch (Exception ex)
                        {
                            dt = null; MessageBox.Show(ex.Message);
                            return(ex.Message);
                        }
                    }
                    dt = null; return("");
                }
                else
                {
                    string sErrors = "";
                    foreach (CompilerError err in results.Errors)
                    {
                        sErrors = sErrors + (string.Format("Line {0}, Col {1}: {4} {2} - {3}", err.Line, err.Column, err.ErrorNumber, err.ErrorText, err.IsWarning ? "Warning" : "Error")) + Constants.vbCrLf;
                    }
                    MessageBox.Show(sErrors);
                    dt = null; return(sErrors);
                }
            }
            dt = null; return("empty");
        }
Esempio n. 53
0
        /// <summary>
        /// 调用WebService
        /// </summary>
        /// <param name="wsUrl">WebService地址</param>
        /// <param name="className">类名</param>
        /// <param name="methodName">方法名称</param>
        /// <param name="soapHeader">SOAP头</param>
        /// <param name="args">参数列表</param>
        /// <returns>返回调用结果</returns>
        public static object InvokeWebService(string wsUrl, string className, string methodName, SoapHeader soapHeader, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((className == null) || (className == ""))
            {
                className = GetWsClassName(wsUrl);
            }
            try
            {
                //获取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(wsUrl + "?wsdl");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler      icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }


                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + className, true, true);

                FieldInfo[] arry = t.GetFields();

                FieldInfo client    = null;
                object    clientkey = null;
                if (soapHeader != null)
                {
                    //Soap头开始
                    client = t.GetField(soapHeader.ClassName + "Value");

                    //获取客户端验证对象
                    Type typeClient = assembly.GetType(@namespace + "." + soapHeader.ClassName);

                    //为验证对象赋值
                    clientkey = Activator.CreateInstance(typeClient);

                    foreach (KeyValuePair <string, object> property in soapHeader.Properties)
                    {
                        typeClient.GetField(property.Key).SetValue(clientkey, property.Value);
                    }
                    //Soap头结束
                }

                //实例类型对象
                object obj = Activator.CreateInstance(t);

                if (soapHeader != null)
                {
                    //设置Soap头
                    client.SetValue(obj, clientkey);
                }

                System.Reflection.MethodInfo mi = t.GetMethod(methodName);

                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Esempio n. 54
0
        public void WriteBackingSourceConfig()
        {
            if (!ValidateParameters())
            {
                return;
            }

            System.Reflection.Assembly asm = null;
            Alachisoft.NCache.Config.Dom.Provider[] prov = new Provider[1];

            try
            {
                asm = System.Reflection.Assembly.LoadFrom(AssemblyPath);
            }
            catch (Exception e)
            {
                successFull = false;
                string message = string.Format("Could not load assembly \"" + AssemblyPath + "\". {0}", e.Message);
                OutputProvider.WriteErrorLine("Error: {0}", message);
                return;
            }

            if (asm == null)
            {
                successFull = false;
                throw new Exception("Could not load specified assembly.");
            }

            System.Type type = asm.GetType(Class, true);

            prov[0] = new Provider();
            prov[0].ProviderName     = ProviderName;
            prov[0].AssemblyName     = asm.FullName;
            prov[0].ClassName        = Class;
            prov[0].FullProviderName = asm.GetName().Name + ".dll";
            if (!string.IsNullOrEmpty(Parameters))
            {
                prov[0].Parameters = GetParams(Parameters);
            }
            if (DefaultProvider == true)
            {
                prov[0].IsDefaultProvider = true;
            }
            else
            {
                prov[0].IsDefaultProvider = false;
            }


            if (ReadThru)
            {
                System.Type typeProvider = type.GetInterface("IReadThruProvider");

                if (typeProvider == null)
                {
                    successFull = false;
                    OutputProvider.WriteErrorLine("Error: Specified class does not implement IReadThruProvider.");
                    return;
                }
                else
                {
                    backingSource.Readthru           = new Readthru();
                    backingSource.Readthru.Enabled   = true;
                    backingSource.Readthru.Providers = prov;
                }
            }
            else if (WriteThru)
            {
                System.Type typeProvider = type.GetInterface("IWriteThruProvider");

                if (typeProvider == null)
                {
                    successFull = false;
                    OutputProvider.WriteErrorLine("Error: Specified class does not implement IWriteThruProvider.");
                    return;
                }
                else
                {
                    backingSource.Writethru                          = new Writethru();
                    backingSource.Writethru.Enabled                  = true;
                    backingSource.Writethru.Providers                = prov;
                    backingSource.Writethru.WriteBehind              = new WriteBehind();
                    backingSource.Writethru.WriteBehind.Mode         = "non-batch";
                    backingSource.Writethru.WriteBehind.Throttling   = _operationPerSecond.ToString();
                    backingSource.Writethru.WriteBehind.RequeueLimit = _operationQueueLimit.ToString();
                    backingSource.Writethru.WriteBehind.Eviction     = _operationEvictionRatio.ToString();
                }
            }

            ConfigurationBuilder cfg = new ConfigurationBuilder();
            string output            = cfg.GetSectionXml(backingSource, "backing-source", 1);

            if (string.IsNullOrEmpty(OutputFile))
            {
                OutputProvider.WriteLine(output);
            }
            else
            {
                StringBuilder xml = new StringBuilder();
                xml.Append(output);
                WriteXmlToFile(xml.ToString());
                OutputProvider.WriteLine("BackingSource config for Class " + Class + " is generated at " + OutputFile);
                OutputProvider.WriteLine(System.Environment.NewLine);
            }
        }
        public void GenerateQueryIndex()
        {
            if (!ValidateParameters())
            {
                return;
            }

            System.Reflection.Assembly           asm          = null;
            Alachisoft.NCache.Config.Dom.Class[] queryClasses = null;
            string failedNodes = string.Empty;
            string serverName  = string.Empty;

            try
            {
                string extension = ".dll";
                try
                {
                    asm       = System.Reflection.Assembly.LoadFrom(AssemblyPath);
                    extension = Path.GetExtension(asm.FullName);
                }
                catch (Exception e)
                {
                    string message = string.Format("Could not load assembly \"" + AssemblyPath + "\". {0}", e.Message);
                    OutputProvider.WriteErrorLine("Error : {0}", message);
                    _successful = false;
                    return;
                }

                if (asm == null)
                {
                    throw new Exception("Could not load specified Assembly");
                }

                System.Type type = asm.GetType(Class, true);

                QueryIndex queryIndices = new QueryIndex();
                queryIndices.Classes = GetSourceClass(GetClass(queryClasses, asm));

                ConfigurationBuilder cfg   = new ConfigurationBuilder();
                string configurationString = cfg.GetSectionXml(queryIndices, "query-indexes", 1);

                if (OutputFile == null || OutputFile.Equals(string.Empty))
                {
                    if (_successful)
                    {
                        OutputProvider.WriteLine(configurationString);
                    }
                }
                else
                {
                    WriteXmlToFile(configurationString);
                    if (_successful)
                    {
                        OutputProvider.WriteLine("Query Indexes generated for Class '{0}' at {1}", Class, OutputFile);
                    }
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error : {0}", e.Message);
                _successful = false;
            }
            finally
            {
                OutputProvider.WriteLine(Environment.NewLine);
            }
        }
Esempio n. 56
0
        /// < summary>
        /// 动态调用web服务
        /// < /summary>
        /// < param name="url">WSDL服务地址< /param>
        /// < param name="classname">类名< /param>
        /// < param name="methodname">方法名< /param>
        /// < param name="args">参数< /param>
        /// < returns>< /returns>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WSHelper.GetWsClassName(url);
                if (classname.EndsWith("?wsdl", true, null))
                {
                    classname = classname.Replace("?wsdl", "").Replace("?WSDL", "");
                }
            }
            try
            { //获取WSDL
                WebClient wc = new WebClient();
                url = url.ToLower().EndsWith("wsdl") ? url : url + "?WSDL";
                Stream             stream = wc.OpenRead(url);
                ServiceDescription sd;
                string             wsdlDoc = string.Empty;
                using (StreamReader sr = new StreamReader(stream))
                {
                    wsdlDoc = sr.ReadToEnd();
                }

                wsdlDoc = System.Text.RegularExpressions.Regex.Replace(wsdlDoc, "location=\"[\\s\\S]*?\"", "location=\"" + (url.ToLower().EndsWith("?wsdl") ? url.Substring(0, url.Length - "?wsdl".Length) : url) + "\"");

                using (StringReader sr = new StringReader(wsdlDoc))
                {
                    sd = ServiceDescription.Read(sr);
                }

                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);
                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();
                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 57
0
 /// <summary>
 /// 获取链接库中脚本类型
 /// </summary>
 /// <param name="sScriptName">脚本名字</param>
 /// <returns></returns>
 public System.Type getScriptType(string sScriptName)
 {
     return(_mStriptdll.GetType(sScriptName));
 }
Esempio n. 58
0
        public virtual async void LoadImages(String[] imageNames, String[] labels = null)
        {
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
            {
                //use default images
                InvokeOnImagesLoaded(imageNames);
                return;
            }

            if (!(System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX) ||
                  System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)))
            {
                await Plugin.Media.CrossMedia.Current.Initialize(); //Implementation only available for iOS, Android
            }
            String[] mats = new String[imageNames.Length];
            for (int i = 0; i < mats.Length; i++)
            {
                String pickImgString = "Use Image from";
                if (labels != null && labels.Length > i)
                {
                    pickImgString = labels[i];
                }
                bool haveCameraOption;
                bool havePickImgOption;
                if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                {
                    //CrossMedia is not implemented on Windows.
                    haveCameraOption  = false;
                    havePickImgOption = true; //We will provide our implementation of pick image option
                }
                else
                {
                    haveCameraOption =
                        (Plugin.Media.CrossMedia.Current.IsCameraAvailable && Plugin.Media.CrossMedia.Current.IsTakePhotoSupported);
                    havePickImgOption =
                        Plugin.Media.CrossMedia.Current.IsPickVideoSupported;
                }

                String action;
                if (haveCameraOption & havePickImgOption)
                {
                    action = await DisplayActionSheet(pickImgString, "Cancel", null, "Default", "Photo Library",
                                                      "Camera");
                }
                else if (havePickImgOption)
                {
                    action = await DisplayActionSheet(pickImgString, "Cancel", null, "Default", "Photo Library");
                }
                else
                {
                    action = "Default";
                }


                if (action.Equals("Default"))
                {
#if __ANDROID__
                    FileInfo fi = Emgu.TF.Util.AndroidFileAsset.WritePermanentFileAsset(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity, imageNames[i], "tmp",
                                                                                        Emgu.TF.Util.AndroidFileAsset.OverwriteMethod.AlwaysOverwrite);

                    mats[i] = fi.FullName;
#else
                    mats[i] = imageNames[i];
#endif
                }
                else if (action.Equals("Photo Library"))
                {
                    if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                    {
                        // our implementation of pick image for Windows

                        /*
                         * using (System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog())
                         * {
                         *  dialog.Multiselect = false;
                         *  dialog.Title = "Select an Image File";
                         *  dialog.Filter = "Image | *.jpg;*.jpeg;*.png;*.bmp;*.gif | All Files | *";
                         *  if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                         *  {
                         *      mats[i] = dialog.FileName;
                         *  }
                         *  else
                         *  {
                         *      return;
                         *  }
                         * }*/
                        System.Reflection.Assembly windowsFormsAssembly = Emgu.TF.Util.Toolbox.FindAssembly("System.Windows.Forms.dll");
                        if (windowsFormsAssembly != null)
                        {
                            //Running on Windows
                            Type openFileDialogType = windowsFormsAssembly.GetType("System.Windows.Forms.OpenFileDialog");
                            Type dialogResultType   = windowsFormsAssembly.GetType("System.Windows.Forms.DialogResult");
                            if (openFileDialogType != null && dialogResultType != null)
                            {
                                object dialog = Activator.CreateInstance(openFileDialogType);
                                openFileDialogType.InvokeMember(
                                    "Multiselect",
                                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
                                    Type.DefaultBinder,
                                    dialog,
                                    new object[] { (object)false });
                                openFileDialogType.InvokeMember(
                                    "Title",
                                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
                                    Type.DefaultBinder,
                                    dialog,
                                    new object[] { (object)"Select an Image File" });
                                openFileDialogType.InvokeMember(
                                    "Filter",
                                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
                                    Type.DefaultBinder,
                                    dialog,
                                    new object[] { (object)"Image | *.jpg;*.jpeg;*.png;*.bmp;*.gif | All Files | *" });
                                object dialogResult = openFileDialogType.InvokeMember(
                                    "ShowDialog",
                                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
                                    Type.DefaultBinder,
                                    dialog,
                                    null);
                                String dialogResultStr = Enum.GetName(dialogResultType, dialogResult);
                                if (dialogResultStr.Equals("OK"))
                                {
                                    //mats[i] = dialog.FileName;
                                    String fileName = openFileDialogType.InvokeMember(
                                        "FileName",
                                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty,
                                        Type.DefaultBinder,
                                        dialog,
                                        null) as String;
                                    mats[i] = fileName;
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        var photoResult = await Plugin.Media.CrossMedia.Current.PickPhotoAsync();

                        if (photoResult == null) //canceled
                        {
                            return;
                        }
                        mats[i] = photoResult.Path;
                    }
                }
                else if (action.Equals("Camera"))
                {
                    var mediaOptions = new Plugin.Media.Abstractions.StoreCameraMediaOptions
                    {
                        Directory = "Emgu",
                        Name      = $"{DateTime.UtcNow}.jpg"
                    };
                    var takePhotoResult = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(mediaOptions);

                    if (takePhotoResult == null) //canceled
                    {
                        return;
                    }
                    mats[i] = takePhotoResult.Path;
                }

                //Handle user cancel
                if (action == null)
                {
                    return;
                }
            }
            InvokeOnImagesLoaded(mats);
        }
Esempio n. 59
0
        public Type ClassGenerator(SqlDataReader reader)
        {
            CSharpCodeProvider c = new CSharpCodeProvider();

#pragma warning disable 618
            ICodeCompiler icc = c.CreateCompiler();
#pragma warning restore 618
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.ReferencedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("mscorlib.dll");
            //cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            cp.ReferencedAssemblies.Add(typeof(T).Assembly.ManifestModule.FullyQualifiedName);
            cp.ReferencedAssemblies.Add(typeof(IMapper <SqlDataReader, T>).Assembly.ManifestModule.FullyQualifiedName);

            cp.CompilerOptions  = "/t:library";
            cp.GenerateInMemory = true;


            var sb = new StringBuilder("");
            sb.Append("using System; \n");
            sb.Append("using System.Xml; \n");
            sb.Append("using System.Data; \n");
            sb.Append("using System.Data.SqlClient; \n");
            //sb.Append("using Microsoft.CSharp.RuntimeBinder; \n");
            sb.Append("using Shoniz.Common.Data.DataConvertor.Mapper; \n");
            if (!IsMicrosoftType(typeof(T)))
            {
                cp.ReferencedAssemblies.Add(typeof(T).Assembly.ManifestModule.FullyQualifiedName);
            }

            sb.Append("namespace DynamicAssemblyInRuntime \n");
            sb.Append("{ \n");
            sb.Append("    public class " + typeof(T).FullName.Replace('.', '_') + " : IMapper<SqlDataReader, " + typeof(T).FullName + "> \n");
            sb.Append("    { \n");
            sb.Append(MethodBodyGenerator(reader));
            //sb.Append("        public string Execute() \n");
            //sb.Append("        {");
            //sb.Append("             return  \"hhhhhhhhhh\";");
            //sb.Append("            //#CSharpCodesToReturnTOutObject \n");
            //sb.Append("        } // EOF method \n");
            sb.Append("    } // EOF class \n");
            sb.Append("} // EOF namespace \n");

            //
            // Generate Code within 'EvalCode' method
            //


            var cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                throw new EvaluateException("ERROR: " + cr.Errors[0].ErrorText);
            }

            System.Reflection.Assembly a = cr.CompiledAssembly;

            Type t = a.GetType("DynamicAssemblyInRuntime." + typeof(T).FullName.Replace('.', '_'));

            //MethodInfo mi = t.GetMethod("Convert");

            return(t);
        }
Esempio n. 60
0
        static public IEnumerable <string> GetMemberSignatures(System.Reflection.Assembly assembly, string fullyQualifiedTypeName, string memberName)
        {
            IEnumerable <string> retVal = null;

            if (string.IsNullOrWhiteSpace(memberName))
            {
                retVal = GetMemberSignatures(assembly, fullyQualifiedTypeName);
            }
            else
            {
                var sb         = new StringBuilder();
                var type       = assembly.GetType(fullyQualifiedTypeName);
                var candidates = new SortedSet <string>();

                if (type != null)
                {
                    foreach (var constructor in type.GetConstructors(BINDING_FLAGS))
                    {
                        if (constructor.Name == memberName)
                        {
                            AppendConstructorInfo(constructor, sb);
                            candidates.Add(sb.ToString());
                            sb.Clear();
                        }
                    }
                    foreach (var method in type.GetMethods(BINDING_FLAGS))
                    {
                        if (method.Name == memberName)
                        {
                            AppendMethodInfo(method, sb);
                            candidates.Add(sb.ToString());
                            sb.Clear();
                        }
                    }
                    foreach (var property in type.GetProperties(BINDING_FLAGS))
                    {
                        if (property.Name == memberName)
                        {
                            AppendPropertyInfo(property, sb);
                            candidates.Add(sb.ToString());
                            sb.Clear();
                        }
                    }
                    foreach (var @event in type.GetEvents(BINDING_FLAGS))
                    {
                        if (@event.Name == memberName)
                        {
                            AppendEventInfo(@event, sb);
                            candidates.Add(sb.ToString());
                            sb.Clear();
                        }
                    }
                    foreach (var field in type.GetFields(BINDING_FLAGS))
                    {
                        if (field.Name == memberName)
                        {
                            AppendFieldInfo(field, sb);
                            candidates.Add(sb.ToString());
                            sb.Clear();
                        }
                    }
                }

                retVal = candidates;
            }
            return(retVal);
        }