Inheritance: ICustomAttributeProvider
        public AssemblyScannerMockRegistry(Assembly pluginAssembly)
        {
            _pluginAssembly = pluginAssembly;
            Forward<ISagaPersister, TpInMemorySagaPersister>();

            Forward<IActivityLogger, LogMock>();
        }
Example #2
1
        public GameLoader(string fileName, Assembly [] preloads, Action<string> die)
        {
            Game = new Game(this, die);
            string extention = null;
            try
            {
                extention = fileName.Substring(fileName.LastIndexOf('.'));
            }
            catch (Exception)
            {
                die("File " + fileName + " could Not be loaded");
                return;
            }

            if (".kgl" == extention)
            {
                loaderUtility = new KGLLoaderUtility(fileName, this);
            }
            else
            {
                die("File " + fileName + " could Not be loaded");
            }

            foreach (Assembly loaded in preloads)
            {
                string name = Path.GetFileName(loaded.Location);
                if (!LoadedFiles.ContainsKey(name))
                {
                    LoadedFiles.Add(name, loaded);
                    ClassFactory.LoadServicesAndManagers(loaded);
                }
            }
        }
 public static string LoadString(string baseName, string resourceName, Assembly asm)
 {
     if (string.IsNullOrEmpty(baseName))
     {
         throw new ArgumentNullException("baseName");
     }
     if (string.IsNullOrEmpty(resourceName))
     {
         throw new ArgumentNullException("resourceName");
     }
     string str = null;
     if (asm != null)
     {
         str = LoadAssemblyString(asm, baseName, resourceName);
     }
     if (str == null)
     {
         str = LoadAssemblyString(Assembly.GetExecutingAssembly(), baseName, resourceName);
     }
     if (str == null)
     {
         return string.Empty;
     }
     return str;
 }
        private static void TryCreatingIndexesOrRedirectToErrorPage(Assembly[] indexAssemblies, string errorUrl)
        {
            try
            {
                foreach (var assembly in indexAssemblies)
                    IndexCreation.CreateIndexes(assembly, DocumentStore);
            }
            catch (WebException e)
            {
                var socketException = e.InnerException as SocketException;
                if (socketException == null)
                    throw;

                switch (socketException.SocketErrorCode)
                {
                    case SocketError.AddressNotAvailable:
                    case SocketError.NetworkDown:
                    case SocketError.NetworkUnreachable:
                    case SocketError.ConnectionAborted:
                    case SocketError.ConnectionReset:
                    case SocketError.TimedOut:
                    case SocketError.ConnectionRefused:
                    case SocketError.HostDown:
                    case SocketError.HostUnreachable:
                    case SocketError.HostNotFound:
                        HttpContext.Current.Response.Redirect(errorUrl);
                        break;
                    default:
                        throw;
                }
            }
        }
Example #5
1
        /// <summary>
        /// Sends an error message by opening the user's mail client.
        /// </summary>
        /// <param name="recipient"></param>
        /// <param name="subject"></param>
        /// <param name="ex"></param>
        /// <param name="assembly">The assembly where the error originated. This will 
        /// be used to extract version information.</param>
        public static void SendByMail(string recipient, string subject, Exception ex,
            Assembly assembly, StringDictionary additionalInfo)
        {
            string attributes = GetAttributes(additionalInfo);

            StringBuilder msg = new StringBuilder();

            msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
            msg.AppendLine();
            msg.AppendLine(GetMessage(ex));
            msg.AppendLine();
            msg.AppendLine(GetAttributes(additionalInfo));
            msg.AppendLine();
            msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
            msg.AppendLine();

            string command = string.Format("mailto:{0}?subject={1}&body={2}",
                recipient,
                Uri.EscapeDataString(subject),
                Uri.EscapeDataString(msg.ToString()));

            Debug.WriteLine(command);
            Process p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.UseShellExecute = true;

            p.Start();
        }
 public IEnumerable<Type> GetLoadableTypes(Assembly assembly, Type ofBaseType)
 {
     var types = GetLoadableTypes(assembly);
     return types != null
                ? types.Where(ofBaseType.IsAssignableFrom)
                : null;
 }
        public static IServiceCollection AddFromAssembly(this IServiceCollection serviceCollection, Assembly assembly)
        {
            var builder = new ServiceDescriptorsBuilder().AddSourceAssembly(assembly);
            BuildAndFill(serviceCollection, builder);

            return serviceCollection;
        }
Example #8
1
        public static int SearchPackageHandler(Assembly ass)
        {
            int count = 0;
            m_packagesHandlers.Clear();

            Type[] tList = ass.GetTypes();

            string interfaceStr = typeof(IPackageHandler).ToString();

            foreach (Type type in tList)
            {
                if (type.IsClass != true) continue;

                if (type.GetInterface(interfaceStr) == null) continue;

                PackageHandlerAttribute[] atts = (PackageHandlerAttribute[])type.GetCustomAttributes(typeof(PackageHandlerAttribute), true);

                if (atts.Length > 0)
                {
                    count++;
                    RegisterPacketHandler(atts[0].Code, (IPackageHandler)Activator.CreateInstance(type));
                    //m_packagesHandlers[atts[0].Code] = (IPackageHandler)Activator.CreateInstance(type);
                }
            }

            return count;
        }
Example #9
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;
            }
        }
Example #10
0
        TestRunState ITestRunner.RunNamespace(ITestListener testListener, Assembly assembly, string ns)
        {
            return TestRunState.NoTests;

            //TODO: Fix filter. ns is probably equal to NamespaceFilter in StoryRunnerFilter
            //return Run(assembly, null, testListener);
        }
Example #11
0
        public IEnumerable<IMigration> FindProfilesIn(Assembly assembly, string profile)
        {
            IEnumerable<Type> matchedTypes = assembly.GetExportedTypes()
                .Where(t => Conventions.TypeIsProfile(t) && t.GetOneAttribute<ProfileAttribute>().ProfileName.ToLower() == profile.ToLower());

            return matchedTypes.Select(type => type.Assembly.CreateInstance(type.FullName) as IMigration);
        }
Example #12
0
 /// <summary>
 /// Create an instance of ModelProgramProvider for a given assembly
 /// </summary>
 /// <param name="modelAssemblyFile">The full path to the assembly file.</param>
 /// <param name="generator">Optional parameter generator.</param>
 public ModelProgramProvider(string modelAssemblyFile, ParameterGenerator/*?*/ generator)
 {
     modelAssembly = Assembly.LoadFrom(modelAssemblyFile);
     this.generator = generator;
     Initialize();
     initialState = GetState();
 }
Example #13
0
        public PluginEntity GetPluginEntity(Assembly _Assembly, string _Url, out List<Function> _Functions)
        {
            //this.Functions.ForEach(x => { x.Url = _Url; x.Assembly = _Assembly; });  // x 是临时的~~ 修改不了

            //for (int i = 0; i < this.Functions.Count; i++)   // 这样写赋值不上
            //{

            //    //Functions[i].Url = _Url;
            //    this.Functions[i].Url = "asdfasdf";
            //    this.Functions[i].Assembly = _Assembly;
            //}

            _Functions = Functions.Select(x => new Function()
                {
                    Action = x.Action,
                    Assembly = _Assembly,
                    Controller = x.Controller,
                    NameSpace = x.NameSpace,
                    ControllerType = x.ControllerType,
                    Name = x.Name,
                    Url = _Url
                }).ToList();

            return new PluginEntity(
                        Name: this.Name,
                        Author: this.Author,
                        Description: this.Description,
                        Functions: _Functions.ToDictionary(x => x.Name), // 通过Function对象的Name属性作为key
                        Assembly: _Assembly
                       );
        }
 public RegistrationModuleSettings()
 {
     TypeFilter = type => true;
     AssemblyFilter = assembly => true;
     IgnoreNamespaces = new string[] { };
     AdditionalAssemblies = new Assembly[] { };
 }
Example #15
0
        /// <summary>
        /// Gets the embedded file identified by the resource name, and converts the
        /// file into a string.
        /// </summary>
        /// <param name="resourceName">In VS, is DefaultNamespace.FileName?</param>
        /// <returns></returns>
        public static string GetEmbeddedStringResource(Assembly assembly, string resourceName)
        {
            string result = null;

            // Use the .NET procedure for loading a file embedded in the assembly
            Stream stream = assembly.GetManifestResourceStream(resourceName);
            if (stream != null)
            {
                // Convert bytes to string
                byte[] fileContentsAsBytes = new byte[stream.Length];
                stream.Read(fileContentsAsBytes, 0, (int)stream.Length);
                result = Encoding.Default.GetString(fileContentsAsBytes);
            }
            else
            {
                // Embedded resource not found - list available resources
                Debug.WriteLine("Unable to find the embedded resource file '" + resourceName + "'.");
                Debug.WriteLine("  Available resources:");
                foreach (string aResourceName in assembly.GetManifestResourceNames())
                {
                    Debug.WriteLine("    " + aResourceName);
                }
            }

            return result;
        }
Example #16
0
        private static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
        {
            var name = args.Name.Split(',')[0];

            if (name.Equals("Microsoft.UpdateServices.Administration"))
            {
                // Microsoft changed version numbers when putting WSUS Admin API into RSAT.
                // Need to try and maintain backward compatability.

                if (!alreadyTriedRedirect)
                {
                    alreadyTriedRedirect = true;

                    var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                    if (!programFiles.EndsWith(@"\"))
                    {
                        programFiles = programFiles + @"\";
                    }

                    redirect = Assembly.LoadFrom(string.Format("{0}Update Services\\Api\\Microsoft.UpdateServices.Administration.dll", programFiles));
                }

                return redirect;
            }

            return null;
        }
Example #17
0
        public void RegisterAssembly(Assembly assembly, string urlFolder, string resourcePrefix)
        {
            var assemblyFilename = Path.GetFileName(assembly.Location);
            _registeredAssemblies[assemblyFilename] = assembly;

            _requestUrlParser.AddMapping(urlFolder, assemblyFilename, resourcePrefix);
        }
Example #18
0
        /// <summary>
        /// ProcessingServiceInstaller initialization with information from service assembly and RunAs user name, password from config file
        /// </summary>
        /// <param name="serviceAssembly"></param>
        /// <param name="installRunAsUserFromConfig"></param>
        public ServiceInstallerBase(Assembly serviceAssembly, bool installRunAsUserFromConfig)
        {
            if (serviceAssembly == null)
                throw new ServiceInitializationException("Installation failed, serviceAssembly is null");

            IAssemblyInfo assemblyInfo = new AssemblyInfo(serviceAssembly);

            if (installRunAsUserFromConfig)
            {
                var config = ConfigurationManager.OpenExeConfiguration(serviceAssembly.Location);
                var configSection = config.GetSection("ServiceInstallerSettings");

                if (configSection != null)
                {
                    var configSectionElement = XElement.Parse(configSection.SectionInformation.GetRawXml());

                    foreach (var item in configSectionElement.XPathSelectElements("add"))
                    {
                        if (item.Attribute(XName.Get("key")) == null)
                            continue;

                        if (item.Attribute(XName.Get("key")).Value == "RunAsUserName")
                            _userName = item.Attribute(XName.Get("value")).Value;

                        if (item.Attribute(XName.Get("key")).Value == "RunAsUserPassword")
                            _password = item.Attribute(XName.Get("value")).Value;
                    }
                }
            }

            Initialize(assemblyInfo.Description, assemblyInfo.Description, assemblyInfo.Title, ServiceAccount.User, _userName, _password);
        }
        private void GetExamples(Assembly asm)
        {
            var types = asm.GetExportedTypes().OrderBy(t => t.Name);

            foreach (Type type in types)
            {
                if (type.GetInterface(typeof(IExample).Name) != null && !type.IsAbstract)
                {
                    var example = (ExampleDescriptionAttribute)type.GetCustomAttributes(typeof(ExampleDescriptionAttribute), false)[0];

                    var paths = example.NodePath.Split(';');
                    foreach (var path in paths)
                    {
                        var pathNodes = path.Split('/');
                        var nodes = this.treeView1.Nodes;
                        for (int index = 0; index < pathNodes.Length; index++)
                        {
                            var s = pathNodes[index];
                            if (!nodes.ContainsKey(s))
                            {
                                var node = nodes.Add(s, s);
                                if (index == pathNodes.Length - 1)
                                {
                                    node.Tag = type.GetConstructor(Type.EmptyTypes);
                                }
                            }

                            nodes = nodes[s].Nodes;
                        }
                    }
                }
            }
        }
 Assembly addAssembly(Assembly assembly)
 {
     var asmName = assembly.GetName();
     assemblies[asmName.FullName] = assembly;
     assemblies[asmName.Name] = assembly;
     return assembly;
 }
Example #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!");
     }
 }
Example #22
0
        /// <summary>
        /// Initializes a new instance of the Theme class.
        /// </summary>
        /// <param name="themeAssembly">
        /// Assembly with the embedded resource containing the theme to apply.
        /// </param>
        /// <param name="themeResourceName">
        /// Name of the embedded resource containing the theme to apply.
        /// </param>
        protected Theme(Assembly themeAssembly, string themeResourceName)
            : this()
        {
            if (themeAssembly == null)
            {
                throw new ArgumentNullException("themeAssembly");
            }

            // Get the resource stream for the theme.
            using (Stream stream = themeAssembly.GetManifestResourceStream(themeResourceName))
            {
                if (stream == null)
                {
                    throw new ResourceNotFoundException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Properties.Resources.Theme_ResourceNotFound,
                            themeResourceName),
                        new Uri(themeResourceName, UriKind.Relative));
                }

                // Load the theme
                ThemeResources = LoadThemeResources(stream, Resources);
            }
        }
Example #23
0
        /// <summary>
        /// Stellt sicher, dass der Serialisierer alle benötigten Datentypen kennt.
        /// </summary>
        /// <param name="assembly">Eine Erweiterungsbibliothek.</param>
        internal static void AddTypes( Assembly assembly )
        {
            // Nothing to do
            if (assembly == null)
                return;

            // Process all
            lock (m_ExtraTypes)
            {
                // Check for update
                bool mustUpdate = false;

                // Check all
                foreach (var type in assembly.GetExportedTypes())
                {
                    // Resolve to base
                    var genericBase = FindCustomActionBase( type );
                    if (genericBase != null)
                        if (m_ExtraTypes.Add( typeof( CustomActionRequest<,> ).MakeGenericType( genericBase.GetGenericArguments() ) ))
                            mustUpdate = true;
                }

                // Reload serializer
                if (mustUpdate)
                    CreateSerializer();
            }
        }
Example #24
0
        private static Func<NancyContext, string, Response> AddStaticResourcePath(string requestedPath, Assembly assembly, string namespacePrefix)
        {
            return (context, s) =>
            {
                var path = context.Request.Path;
                if (!path.StartsWith(requestedPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    return null;
                }

                string resourcePath;
                string name;

                var adjustedPath = path.Substring(requestedPath.Length + 1);
                if (adjustedPath.IndexOf('/') >= 0)
                {
                    name = Path.GetFileName(adjustedPath);
                    resourcePath = namespacePrefix + "." + adjustedPath.Substring(0, adjustedPath.Length - name.Length - 1).Replace('/', '.');
                }
                else
                {
                    name = adjustedPath;
                    resourcePath = namespacePrefix;
                }
                return new EmbeddedFileResponse(assembly, resourcePath.Replace("-", "_"), name);
            };
        }
 public PluginConfiguration(string moduleName, Assembly applicationAssembly, Assembly domainAssembly, Assembly infrastructureAssembly)
 {
     ModuleName = moduleName;
     ApplicationAssembly = applicationAssembly;
     DomainAssembly = domainAssembly;
     InfrastructureAssembly = infrastructureAssembly;
 }
 private void AddAssemblyTypes(Assembly assembly)
 {
     Type[] types = assembly.GetTypes();
     foreach (var type in types)
         if (typeof(BinaryData).IsAssignableFrom(type) && !type.IsAbstract)
             AddType(type);
 }
Example #27
0
		public static CompilerContext compile_(CompileUnit unit, Assembly[] references)
		{
			BooCompiler compiler = NewCompiler();
			foreach (Assembly reference in references)
				compiler.Parameters.References.Add(reference);
			return compiler.Run(unit);
		}
Example #28
0
 public static string FindExecutionDirectory(Assembly assembly)
 {
     string applicationPath = assembly.CodeBase;
     UriBuilder uri = new UriBuilder(applicationPath);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
Example #29
0
 private static ResourceManager GetResourceManager(string resourceBaseName, Assembly assembly)
 {
     // check the cache
     if (_resManager == null)
         _resManager = new ResourceManager(resourceBaseName, assembly);
     return _resManager;
 }
Example #30
0
		public static UIImage FromResource (Assembly assembly, string name)
		{
			if (name == null)
				throw new ArgumentNullException ("name");
			assembly = Assembly.GetCallingAssembly ();
			var stream = assembly.GetManifestResourceStream (name);
			if (stream == null)
				return null;
			
			IntPtr buffer = Marshal.AllocHGlobal ((int) stream.Length);
			if (buffer == IntPtr.Zero)
				return null;
			
			var copyBuffer = new byte [Math.Min (1024, (int) stream.Length)];
			int n;
			IntPtr target = buffer;
			while ((n = stream.Read (copyBuffer, 0, copyBuffer.Length)) != 0){
				Marshal.Copy (copyBuffer, 0, target, n);
				target = (IntPtr) ((int) target + n);
			}
			try {
				var data = NSData.FromBytes (buffer, (uint) stream.Length);
				return UIImage.LoadFromData (data);
			} finally {
				Marshal.FreeHGlobal (buffer);
				stream.Dispose ();
			}
		}
Example #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);
            }
        }
Example #32
0
        public static object GetWebServiceInstance(string url, string classname)
        {
            if (url == null)
            {
                return(null);
            }

            string @namespace = "HWVDynamicWebServiceCalling";

            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 = csc.CompileAssemblyFromDom(cplist, ccu);// 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);
                return(Activator.CreateInstance(t));
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                throw new Exception("获取动态web服务调用的类的类型失败:" + ex.Message);
            }
        }
Example #33
0
        static void Main(string[] args)
        {
            //2018-11-03
            //AppDomain.CurrentDomain.SetData("FormSmallest", "Y");

            bool   blnResult;
            string strProgramName = "TimeAttendanceClientIS";

            var mutex = new System.Threading.Mutex(true, strProgramName, out blnResult);

            if (blnResult == false)
            {
                System.Windows.Forms.MessageBox.Show(strProgramName + ".exe is already running.", strProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            bool blnContinue = true;

            //NB TimeAttendance.exe will Replace TimeAttendanceIS.exe_ to TimeAttendanceIS.exe if needs be

            //P = Payroll
            //T = Time Attendance Client
            AppDomain.CurrentDomain.SetData("FromProgramInd", "T");

            string strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;

#if (DEBUG)
            strBaseDirectory += "bin\\";

            //Server Files with _ Renamed (Only in Debug Mode)
            string[] strFiles = Directory.GetFiles(strBaseDirectory, "*.*_");

            foreach (string strFile in strFiles)
            {
                if (strFile.Substring(strFile.Length - 25) == "TimeAttendanceClient.exe_"
                    | strFile.Substring(strFile.Length - 29) == "TimeSheetDynamicUploadIS.exe_")
                {
                    continue;
                }

                File.Copy(strFile, strFile.Substring(0, strFile.Length - 1), true);
                File.Delete(strFile);
            }
#else
            if (args.Length == 0)
            {
                MessageBox.Show("Click on TimeAttendanceClient.exe to Start this Program");
                return;
            }
            else
            {
                if (args[0].ToString() != "1")
                {
                    MessageBox.Show("Click on TimeAttendanceClient.exe to Start this Program");
                    return;
                }
            }
#endif
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            FileInfo fiFileInfo = new FileInfo(strBaseDirectory + "TimeAttendanceLogon.dll_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "TimeAttendanceLogon.dll_", strBaseDirectory + "TimeAttendanceLogon.dll", true);
                    File.Delete(strBaseDirectory + "TimeAttendanceLogon.dll_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting TimeAttendanceLogon.dll_");
                }
            }

            fiFileInfo = new FileInfo(strBaseDirectory + "clsISClientUtilities.dll_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "clsISClientUtilities.dll_", strBaseDirectory + "clsISClientUtilities.dll", true);
                    File.Delete(strBaseDirectory + "clsISClientUtilities.dll_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting clsISClientUtilities.dll_");
                }
            }

            //Move TimeSheetDynamicUploadIS.dll_ Live
            fiFileInfo = new FileInfo(strBaseDirectory + "TimeSheetDynamicUploadIS.exe_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "TimeSheetDynamicUploadIS.exe_", strBaseDirectory + "TimeSheetDynamicUploadIS.exe", true);
                    File.Delete(strBaseDirectory + "TimeSheetDynamicUploadIS.exe_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting TimeSheetDynamicUploadIS.dll_");
                }
            }

            fiFileInfo = new FileInfo(strBaseDirectory + "clsISUtilities.dll_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "clsISUtilities.dll_", strBaseDirectory + "clsISUtilities.dll", true);
                    File.Delete(strBaseDirectory + "clsISUtilities.dll_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting clsISUtilities.dll_");
                }
            }

            fiFileInfo = new FileInfo(strBaseDirectory + "PasswordChange.dll_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "PasswordChange.dll_", strBaseDirectory + "PasswordChange.dll", true);
                    File.Delete(strBaseDirectory + "PasswordChange.dll_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting PasswordChange.dll_");
                }
            }

            fiFileInfo = new FileInfo(strBaseDirectory + "\\DownloadFiles.dll_");

            if (fiFileInfo.Exists == true)
            {
                try
                {
                    File.Copy(strBaseDirectory + "DownloadFiles.dll_", strBaseDirectory + "\\DownloadFiles.dll", true);
                    File.Delete(strBaseDirectory + "DownloadFiles.dll_");
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Error Copying / Deleting DownloadFiles.dll_");
                }
            }

            //2013-12-24
            //Get URL Path From Config File
            string strConfig = AppDomain.CurrentDomain.BaseDirectory + "URLConfig.txt";

            fiFileInfo = new FileInfo(strConfig);

            if (fiFileInfo.Exists == true)
            {
                StreamReader srStreamReader = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "URLConfig.txt");

                string strURLPath = srStreamReader.ReadLine();

                AppDomain.CurrentDomain.SetData("URLPath", strURLPath);

                srStreamReader.Close();
#if (DEBUG)
                DialogResult myDialogResult = System.Windows.Forms.MessageBox.Show("You are going to Use Internet Web Service Layer (Live System).\n\nWould you like to Continue.",
                                                                                   "Error",
                                                                                   MessageBoxButtons.YesNo,
                                                                                   MessageBoxIcon.Error);

                if (myDialogResult == System.Windows.Forms.DialogResult.No)
                {
                    blnContinue = false;
                }
#endif
            }
            else
            {
                AppDomain.CurrentDomain.SetData("URLPath", "");
#if (DEBUG)
#else
                MessageBox.Show("URLConfig.txt File Missing.\n\nSpeak to your System Administrator.",
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                blnContinue = false;
#endif
            }

            fiFileInfo = new FileInfo("URLClientConfig.txt");

            if (fiFileInfo.Exists == false)
            {
#if (DEBUG)
                AppDomain.CurrentDomain.SetData("URLClientPath", "");
#else
                //Set To Read Local Machine
                string strFile = "127.0.0.1:8000";

                StreamWriter swStreamWriter = fiFileInfo.AppendText();

                swStreamWriter.WriteLine(strFile);

                swStreamWriter.Close();

                AppDomain.CurrentDomain.SetData("URLClientPath", "127.0.0.1:8000");
#endif
            }
            else
            {
#if (DEBUG)
                DialogResult myDialogResult = System.Windows.Forms.MessageBox.Show("You are going to Use the LOCAL Web Service Layer (Live System).\n\nWould you like to Continue.",
                                                                                   "Question",
                                                                                   MessageBoxButtons.YesNo,
                                                                                   MessageBoxIcon.Question);

                if (myDialogResult == System.Windows.Forms.DialogResult.No)
                {
                    blnContinue = false;
                }
#endif
                StreamReader srStreamReader = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "URLClientConfig.txt");

                string strURLPath = srStreamReader.ReadLine();

                AppDomain.CurrentDomain.SetData("URLClientPath", strURLPath);

                srStreamReader.Close();
            }

            if (blnContinue == true)
            {
                try
                {
                    string strPath = AppDomain.CurrentDomain.BaseDirectory + "TimeAttendanceLogon.dll";

                    System.Reflection.Assembly tmpAssembly = System.Reflection.Assembly.LoadFile(strPath);

                    object lateBoundObj = tmpAssembly.CreateInstance("InteractPayrollClient.frmLogonScreen");

                    Form myForm = (System.Windows.Forms.Form)lateBoundObj;

                    myForm.ShowDialog();
                }
                catch (System.Exception ex)
                {
                }
                finally
                {
                    try
                    {
                        mutex.ReleaseMutex();
                    }
                    catch
                    {
                    }
                }
            }
        }
Example #34
0
 public virtual void Run()
 {
     this.TryObtainLock();
     try{
         Preconditions(Pre.EngineNotClosed |
                       Pre.EngineNotRunning |
                       Pre.RootMonikerSet |
                       Pre.SiteSet |
                       Pre.RootNamespaceSet);
         // managed engines cannot support the AppDomain property so we always use the current one
         AppDomain appDomain = System.AppDomain.CurrentDomain;
         if (this.haveCompiledState)
         {
             // make sure the RootNamespace hasn't been changed since the compilation
             if (this.rootNamespace != this.compiledRootNamespace)
             {
                 throw new VsaException(VsaError.RootNamespaceInvalid);
             }
             this.loadedAssembly = this.LoadCompiledState();
             appDomain.SetData(this.engineMoniker, this.loadedAssembly);
         }
         else
         {
             // if Compile returned false last time it was called, quit before cache lookup or callback
             if (this.failedCompilation)
             {
                 throw new VsaException(VsaError.EngineNotCompiled);
             }
             this.startupClass   = null;
             this.loadedAssembly = appDomain.GetData(this.engineMoniker) as Assembly;
             if (this.loadedAssembly == null)
             {
                 // assembly is not in the cache, so callback to the site for compiled state
                 // prevent multiple callbacks which could result in duplicate assemblies being loaded into the AppDomain
                 string mutexName = this.engineMoniker + "/" + appDomain.GetHashCode().ToString(CultureInfo.InvariantCulture);
                 Mutex  compiledStateCallbackMutex = new Mutex(false, mutexName);
                 if (compiledStateCallbackMutex.WaitOne())
                 {
                     try{
                         // see if there was another callback before we got the lock
                         this.loadedAssembly = appDomain.GetData(this.engineMoniker) as Assembly;
                         if (this.loadedAssembly == null)
                         {
                             byte[] pe;
                             byte[] pdb;
                             this.engineSite.GetCompiledState(out pe, out pdb);
                             if (pe == null)
                             {
                                 throw new VsaException(VsaError.GetCompiledStateFailed);
                             }
                             this.loadedAssembly = Assembly.Load(pe, pdb, this.executionEvidence);
                             appDomain.SetData(this.engineMoniker, this.loadedAssembly);
                         }
                     }finally{
                         compiledStateCallbackMutex.ReleaseMutex();
                         compiledStateCallbackMutex.Close();
                     }
                 }
             }
         }
         // update the _Startup class Type object (if needed)
         try{
             if (this.startupClass == null)
             {
                 this.startupClass = this.loadedAssembly.GetType(this.rootNamespace + "._Startup", true);
             }
         }catch (Exception e) {
             // the _Startup class was not in the RootNamespace
             throw new VsaException(VsaError.BadAssembly, e.ToString(), e);
         }
         // set the engine to running, callback for global and event instances, then run global code
         try{
             this.startupInstance = (BaseVsaStartup)Activator.CreateInstance(this.startupClass);
             this.isEngineRunning = true;
             this.startupInstance.SetSite(this.engineSite);
             this.startupInstance.Startup();
         }catch (Exception e) {
             throw new VsaException(VsaError.UnknownError, e.ToString(), e);
         }
     }finally{
         this.ReleaseLock();
     }
 }
        /// <summary>
        /// 动态调用web服务
        /// </summary>
        /// <param name="url"></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 = DynamicWebService.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);
                CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp");
                //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);

                //设置CookieContainer 1987raymond添加
                PropertyInfo property = t.GetProperty("CookieContainer");
                property.SetValue(obj, container, null);

                System.Reflection.MethodInfo mi = t.GetMethod(methodName);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #36
0
        CreateCodeGroup(SecurityElement el)
        {
            if (el == null || !el.Tag.Equals("CodeGroup"))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_WrongElementType"), "<CodeGroup>"));
            }
            Contract.EndContractBlock();

            String className;
            int    classNameLength;
            int    classNameStart;

            if (!ParseElementForObjectCreation(el,
                                               BuiltInCodeGroup,
                                               out className,
                                               out classNameStart,
                                               out classNameLength))
            {
                goto USEREFLECTION;
            }

            switch (classNameLength)
            {
            case 12:
                // NetCodeGroup
                if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
                {
                    return(new NetCodeGroup());
                }
                else
                {
                    goto USEREFLECTION;
                }

            case 13:
                // FileCodeGroup
                if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
                {
                    return(new FileCodeGroup());
                }
                else
                {
                    goto USEREFLECTION;
                }

            case 14:
                // UnionCodeGroup
                if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
                {
                    return(new UnionCodeGroup());
                }
                else
                {
                    goto USEREFLECTION;
                }

            case 19:
                // FirstMatchCodeGroup
                if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
                {
                    return(new FirstMatchCodeGroup());
                }
                else
                {
                    goto USEREFLECTION;
                }

            default:
                goto USEREFLECTION;
            }

USEREFLECTION:
            Type groupClass = null;
            CodeGroup group = null;

            new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
            groupClass = GetClassFromElement(el, true);
            if (groupClass == null)
            {
                return(null);
            }
            if (!(typeof(CodeGroup).IsAssignableFrom(groupClass)))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_NotACodeGroupType"));
            }

            group = (CodeGroup)Activator.CreateInstance(groupClass, true);

            Contract.Assert(groupClass.Module.Assembly != Assembly.GetExecutingAssembly(),
                            "This path should not get called for mscorlib based classes");

            return(group);
        }
        public AssemblyModelFactory(Type type)
        {
            this.Assembly = type.Assembly;

            GetRefrenceModules(GetModule(this.Assembly));
        }
Example #38
0
 public static string GetImplementationVersion(this System.Reflection.Assembly asm)
 {
     return(asm.GetName().Version.ToString());
 }
Example #39
0
        public ScriptResult ProcessScript(Stream stream, IDictionary <string, string> requestParameters)
        {
            StringBuilder scriptBody = new StringBuilder();

            /* read the contents of the stream into a string
             * builder line by line to create a single
             * string that represents the script */
            StreamReader reader = new StreamReader(stream);
            string       line   = null;

            while ((line = reader.ReadLine()) != null)
            {
                scriptBody.Append(line);
            }

            /* combine the script string with the class template in order to create something
             * that can be compiled. NOTE that the class template provides the wout and
             * request variables */
            string source = _classTemplate.Replace("{0}", scriptBody.ToString());

            /* compile the generated source */
            CompilerResults result = _compiler.CompileAssemblyFromSource(_parameters, source);

            /* if the source didn't compile, generate an html document that lists the
             * compilation errors and return a failed script result with that html
             * document as the result */
            if (result.Errors.Count > 0)
            {
                StringBuilder errorBody = new StringBuilder();
                errorBody.Append("<html><body>");
                errorBody.Append("<h1>Script Compilation Errors</h1>");
                errorBody.Append("<p>The following errors occurred processing the requested resource</p>");
                errorBody.Append("<ul>");
                foreach (CompilerError error in result.Errors)
                {
                    errorBody.Append(string.Format("<li>{0}:{1} - Error: {2}</li>", error.Line, error.Column, error.ErrorText));
                }
                errorBody.Append("</ul>");
                errorBody.Append("</body></html>");

                /* the script result with the list of errors as the result */
                return(new ScriptResult()
                {
                    Error = true,
                    Result = errorBody.ToString()
                });
            }

            /* if the class compiled, use reflection to get the assembly and
             * instantiate the class */
            System.Reflection.Assembly codeAssembly = result.CompiledAssembly;
            object instance = codeAssembly.CreateInstance("Server.Executor");

            /* get an instance of the type of the class (i.e. Server.Executor) */
            Type instanceType = instance.GetType();

            /* get an instance of the method that we want to invoke
             * (i.e. Execute(StringWriter wout, Dictionary<string, string> request)) */
            MethodInfo executionMethod = instanceType.GetMethod("Execute", new Type[] { typeof(StringWriter), typeof(Dictionary <string, string>) });

            /* now we want to invoke the method on the instance of the Executor
             * that we created above */
            try
            {
                /* create a string writer to send in as wout */
                StringWriter s = new StringWriter();

                /* invoke the method with the string writer and request dictionary */
                executionMethod.Invoke(instance, new object[] { s, requestParameters });

                /* return a script result with the contents of the string writer which
                 * should be the HTML (or whatever) that was produced by the script
                 * and written to wout */
                return(new ScriptResult()
                {
                    Error = false,
                    Result = s.ToString()
                });
            }
            catch (Exception e)
            {
                /* if the method cannot be invoked (i.e. runtime error) send back
                 * a failed result with the runtime error */
                return(new ScriptResult()
                {
                    Error = true,
                    Result = string.Format("<html><body><h1>Runtime Error</h1><p>The following runtime error occurred: {0}</p>",
                                           e.InnerException.Message)
                });
            }
        }
Example #40
0
 protected static System.Globalization.CultureInfo GetNeutralResourcesLanguage(System.Reflection.Assembly a)
 {
     throw null;
 }
Example #41
0
        /// <summary>
        /// Gets the list of concrete generic type instances used in an assembly.
        /// See remarks
        /// </summary>
        /// <param name="assembly">The assembly</param>
        /// <param name="types"></param>
        /// <returns>The list of generic type instances</returns>
        /// <remarks>
        /// Note that this method fetchs only direct type instances but
        /// cannot fetch transitive generic type instances.
        /// </remarks>
        private static void CollectGenericTypeInstances(System.Reflection.Assembly assembly, List <Type> types, HashSet <Type> visited)
        {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // WARNING: THIS CODE HAS TO BE MAINTAINED IN SYNC WITH BclApp.cs
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            // From: https://gist.github.com/xoofx/710aaf86e0e8c81649d1261b1ef9590e
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }
            const int mdMaxCount = 1 << 24;

            foreach (var module in assembly.Modules)
            {
                for (int i = 1; i < mdMaxCount; i++)
                {
                    try
                    {
                        // Token base id for TypeSpec
                        const int mdTypeSpec = 0x1B000000;
                        var       type       = module.ResolveType(mdTypeSpec | i);
                        if (type.IsConstructedGenericType && !type.ContainsGenericParameters)
                        {
                            CollectGenericTypeInstances(type, types, visited);
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        break;
                    }
                    catch (ArgumentException)
                    {
                        // Can happen on ResolveType on certain generic types, so we continue
                    }
                }

                for (int i = 1; i < mdMaxCount; i++)
                {
                    try
                    {
                        // Token base id for MethodSpec
                        const int mdMethodSpec = 0x2B000000;
                        var       method       = module.ResolveMethod(mdMethodSpec | i);
                        var       genericArgs  = method.GetGenericArguments();
                        foreach (var genArgType in genericArgs)
                        {
                            if (genArgType.IsConstructedGenericType && !genArgType.ContainsGenericParameters)
                            {
                                CollectGenericTypeInstances(genArgType, types, visited);
                            }
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        break;
                    }
                    catch (ArgumentException)
                    {
                        // Can happen on ResolveType on certain generic types, so we continue
                    }
                }


                for (int i = 1; i < mdMaxCount; i++)
                {
                    try
                    {
                        // Token base id for Field
                        const int mdField = 0x04000000;
                        var       field   = module.ResolveField(mdField | i);
                        CollectGenericTypeInstances(field.FieldType, types, visited);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        break;
                    }
                    catch (ArgumentException)
                    {
                        // Can happen on ResolveType on certain generic types, so we continue
                    }
                }
            }
        }
Example #42
0
 public static IAssembly set_assembly(System.Reflection.Assembly value)
 {
     return(new Assembly(value));
 }
Example #43
0
 protected static System.Version GetSatelliteContractVersion(System.Reflection.Assembly a)
 {
     throw null;
 }
Example #44
0
 public CompiledResult(System.Reflection.Assembly assembly, CompilerError error)
 {
     this.assembly = assembly;
     this.error    = error;
 }
Example #45
0
 static Type GetTestCase(string name, SR.Assembly assembly)
 {
     return(assembly.GetType(name));
 }
Example #46
0
 public ResourceManager(string baseName, System.Reflection.Assembly assembly, System.Type usingResourceSet)
 {
 }
        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);
        }
Example #48
0
 public ResourceManager(string baseName, System.Reflection.Assembly assembly)
 {
 }
 public virtual void Run()
 {
     this.TryObtainLock();
     try
     {
         this.Preconditions(Pre.SiteSet | Pre.RootNamespaceSet | Pre.RootMonikerSet | Pre.EngineNotRunning | Pre.EngineNotClosed);
         System.AppDomain currentDomain = System.AppDomain.CurrentDomain;
         if (this.haveCompiledState)
         {
             if (this.rootNamespace != this.compiledRootNamespace)
             {
                 throw new JSVsaException(JSVsaError.RootNamespaceInvalid);
             }
             this.loadedAssembly = this.LoadCompiledState();
             currentDomain.SetData(this.engineMoniker, this.loadedAssembly);
         }
         else
         {
             if (this.failedCompilation)
             {
                 throw new JSVsaException(JSVsaError.EngineNotCompiled);
             }
             this.startupClass   = null;
             this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly;
             if (this.loadedAssembly == null)
             {
                 string name  = this.engineMoniker + "/" + currentDomain.GetHashCode().ToString(CultureInfo.InvariantCulture);
                 Mutex  mutex = new Mutex(false, name);
                 if (mutex.WaitOne())
                 {
                     try
                     {
                         this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly;
                         if (this.loadedAssembly == null)
                         {
                             byte[] buffer;
                             byte[] buffer2;
                             this.engineSite.GetCompiledState(out buffer, out buffer2);
                             if (buffer == null)
                             {
                                 throw new JSVsaException(JSVsaError.GetCompiledStateFailed);
                             }
                             this.loadedAssembly = System.Reflection.Assembly.Load(buffer, buffer2, this.executionEvidence);
                             currentDomain.SetData(this.engineMoniker, this.loadedAssembly);
                         }
                     }
                     finally
                     {
                         mutex.ReleaseMutex();
                         mutex.Close();
                     }
                 }
             }
         }
         try
         {
             if (this.startupClass == null)
             {
                 this.startupClass = this.loadedAssembly.GetType(this.rootNamespace + "._Startup", true);
             }
         }
         catch (Exception exception)
         {
             throw new JSVsaException(JSVsaError.BadAssembly, exception.ToString(), exception);
         }
         try
         {
             this.startupInstance = (BaseVsaStartup)Activator.CreateInstance(this.startupClass);
             this.isEngineRunning = true;
             this.startupInstance.SetSite(this.engineSite);
             this.startupInstance.Startup();
         }
         catch (Exception exception2)
         {
             throw new JSVsaException(JSVsaError.UnknownError, exception2.ToString(), exception2);
         }
     }
     finally
     {
         this.ReleaseLock();
     }
 }
Example #50
0
 /// <summary>
 /// 获取Assembly所在的路径
 /// </summary>
 /// <param name="assemble"></param>
 /// <returns></returns>
 public static string GetAssemblyPath(System.Reflection.Assembly assemble)
 {
     return(System.IO.Path.GetDirectoryName(assemble.Location) + @"\");
 }
Example #51
0
        public FsmStateMachine(XmlDocument xmlDoc)
        {
            this.states = new Dictionary <string, State>();
            XmlNode root = xmlDoc.SelectSingleNode("StateMachine");

            fsmName = root.Attributes["name"].Value;
            XmlNodeList states = root.SelectNodes("State");

            for (int i = 0, size = states.Count; i < size; i++)
            {
                XmlNode stateNode = states[i];
                State   state     = new State(stateNode.Attributes["name"].Value);
                state.isDefault = stateNode.Attributes["isDefault"].Value == "true";
                XmlNodeList actions = stateNode.SelectSingleNode("Actions").SelectNodes("Action");
                for (int j = 0; j < actions.Count; j++)
                {
                    XmlNode   actionNode = actions[j];
                    string    className  = actionNode.Attributes["name"].Value;
                    FSMAction action     = (FSMAction)Reflection.GetExecutingAssembly().CreateInstance(className);
                    action.name = className;
                    XmlNodeList paramsNodes = actionNode.SelectSingleNode("params").SelectNodes("param");
                    for (int k = 0; k < paramsNodes.Count; k++)
                    {
                        XmlNode   paramNode    = paramsNodes[k];
                        string    propertyName = paramNode.Attributes["key"].Value;
                        Type      tp           = action.GetType();
                        FieldInfo pInfo        = tp.GetField(propertyName);
                        if (null == pInfo)
                        {
                            UnityEngine.Debug.LogError("获取条件名为: " + action.name + "的属性 " + paramNode.Attributes["key"].Value + "不存在");
                            return;
                        }
                        pInfo.SetValue(action, paramNode.Attributes["value"].Value);
                    }
                    state.AddAction(action);
                }

                XmlNodeList transitions = stateNode.SelectSingleNode("Transitions").SelectNodes("Transition");
                for (int j = 0; j < transitions.Count; j++)
                {
                    XmlNode     transitionNode  = transitions[j];
                    Transition  trans           = new Transition(transitionNode.Attributes["name"].Value, state.name, transitionNode.Attributes["toState"].Value);
                    XmlNodeList conditionsNodes = transitionNode.SelectSingleNode("Conditions").SelectNodes("Condition");
                    for (int k = 0; k < conditionsNodes.Count; k++)
                    {
                        XmlNode      conditionNode = conditionsNodes[k];
                        string       className     = conditionNode.Attributes["name"].Value;
                        FSMCondition condition     = (FSMCondition)Reflection.GetExecutingAssembly().CreateInstance(className);
                        condition.name = className;
                        XmlNodeList paramsNodes = conditionNode.SelectSingleNode("params").SelectNodes("param");
                        for (int m = 0; m < paramsNodes.Count; m++)
                        {
                            XmlNode   paramNode = paramsNodes[m];
                            FieldInfo pInfo     = condition.GetType().GetField(paramNode.Attributes["key"].Value);
                            if (null == pInfo)
                            {
                                UnityEngine.Debug.LogError("获取条件名为: " + condition.name + "的属性 " + paramNode.Attributes["key"].Value + "不存在");
                                return;
                            }
                            // UnityEngine.Debug.Log("获取条件名为: " + condition.name + "的属性 " + paramNode.Attributes["key"].Value + "不存在");
                            pInfo.SetValue(condition, paramNode.Attributes["value"].Value);
                        }
                        trans.AddCondition(condition);
                    }
                    state.AddTransition(trans);
                }

                AddState(state);
            }
        }
Example #52
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));
            }
        }
 public AssemblyModelFactory(System.Reflection.Assembly assembly)
 {
     this.Assembly = assembly;
     GetRefrenceModules(GetModule(assembly));
 }
Example #54
0
 /// <summary>
 /// 这个方法里可HOOK所有资源。
 /// </summary>
 /// <param name="webView"></param>
 /// <param name="param"></param>
 /// <param name="url"></param>
 /// <param name="job"></param>
 /// <returns></returns>
 bool OnwkeLoadUrlBeginCallback(IntPtr webView, IntPtr param, string url, IntPtr job)
 {
     //mb://index.html/js/index.js
     if (url.StartsWith("mb://"))
     {
         Regex  regex = new Regex(@"mb://", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
         string str   = regex.Replace(url, ""); // url.TrimStart("mb://".ToArray());//.Substring(startIndex);
                                                //if (url != Url)//加载本地资源
                                                //{
                                                //    str = url.TrimStart(Url.ToArray());
                                                //}
         str = str.Replace('/', '.');
         System.Reflection.Assembly Assemblys = BlinkBrowserPInvoke.ResourceAssemblys["MiniBlinkPinvokeDemo"];
         if (Assemblys != null)
         {
             using (Stream sm = Assemblys.GetManifestResourceStream("MiniBlinkPinvokeDemo." + str))
             {
                 if (sm != null)
                 {
                     StreamReader m_stream = new StreamReader(sm, Encoding.Default);
                     m_stream.BaseStream.Seek(0, SeekOrigin.Begin);
                     string strLine = m_stream.ReadToEnd();
                     m_stream.Close();
                     string data = strLine;
                     if (url.EndsWith(".css"))
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("text/css"));
                     }
                     else if (url.EndsWith(".png"))
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("image/png"));
                     }
                     else if (url.EndsWith(".gif"))
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("image/gif"));
                     }
                     else if (url.EndsWith(".jpg"))
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("image/jpg"));
                     }
                     else if (url.EndsWith(".js"))
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("application/javascript"));
                     }
                     else
                     {
                         BlinkBrowserPInvoke.wkeNetSetMIMEType(job, Marshal.StringToCoTaskMemAnsi("text/html"));
                     }
                     //wkeNetSetURL(job, url);
                     BlinkBrowserPInvoke.wkeNetSetData(job, Marshal.StringToCoTaskMemAnsi(data), Encoding.Default.GetBytes(data).Length);
                 }
                 else
                 {
                     ResNotFond(url, job);
                 }
             }
         }
         else
         {
             ResNotFond(url, job);
         }
         return(true);
     }
     else
     {
         //如果需要 OnwkeLoadUrlEndCallback 回调,需要取消注释下面的 hook
         BlinkBrowserPInvoke.wkeNetHookRequest(job);
     }
     return(false);
 }
Example #55
0
 protected AssemblyNameReference ImportScope(SR.Assembly assembly)
 {
     return(ImportReference(assembly.GetName()));
 }
Example #56
0
        private void LoadCollectorAgents()
        {
            lvwAgentType.Items.Clear();
            lvwAgentType.Groups.Clear();

            ListViewGroup generalGroup = new ListViewGroup("General");

            lvwAgentType.Groups.Add(generalGroup);

            foreach (string categoryName in (from a in RegisteredAgentCache.Agents
                                             where ((a.IsCollector && selectingCollectorAgents) || (selectingNotifierAgents && a.IsNotifier)) && a.CategoryName != "Test" && a.CategoryName != "General"
                                             group a by a.CategoryName into g
                                             orderby g.Key
                                             select g.Key))
            {
                lvwAgentType.Groups.Add(new ListViewGroup(categoryName));
            }
            ListViewGroup testGroup = new ListViewGroup("Test");

            lvwAgentType.Groups.Add(testGroup);

            ListViewItem lvi;

            foreach (RegisteredAgent ar in (from a in RegisteredAgentCache.Agents
                                            where (selectingCollectorAgents && a.IsCollector) || (selectingNotifierAgents && a.IsNotifier)
                                            orderby a.Name
                                            select a))
            {
                try
                {
                    ListViewGroup agentGroup = (from ListViewGroup gr in lvwAgentType.Groups
                                                where gr.Header.ToLower() == ar.CategoryName.ToLower()
                                                select gr).FirstOrDefault();
                    if (agentGroup == null)
                    {
                        agentGroup = generalGroup;
                    }

                    lvi = new ListViewItem(ar.DisplayName);
                    string details = ar.ClassName;
                    System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(ar.AssemblyPath);
                    details += ", Version: " + a.GetName().Version.ToString();
                    details += ", Assembly: " + System.IO.Path.GetFileName(a.Location);

                    if (agentGroup == testGroup)
                    {
                        lvi.ImageIndex = 1;
                    }
                    else
                    {
                        lvi.ImageIndex = 0;
                    }
                    lvi.Group = agentGroup;
                    lvi.SubItems.Add(details);
                    lvi.Tag = ar;
                    lvwAgentType.Items.Add(lvi);
                    if (ar.Name == InitialRegistrationName)
                    {
                        lvi.Selected = true;
                    }
                }
                catch { }
            }

            ListViewGroup templatesGroup = new ListViewGroup("Templates");

            lvwAgentType.Groups.Add(templatesGroup);

            foreach (QuickMonTemplate qt in QuickMonTemplate.GetAllTemplates().Where(t => (selectingCollectorAgents && t.TemplateType == TemplateType.CollectorAgent) || (selectingNotifierAgents && t.TemplateType == TemplateType.NotifierAgent)))
            {
                ListViewItem lviTemplateCollector = new ListViewItem(qt.Name);
                lviTemplateCollector.SubItems.Add(qt.Description);
                lviTemplateCollector.Group = templatesGroup;
                lviTemplateCollector.Tag   = qt;
                lvwAgentType.Items.Add(lviTemplateCollector);
            }
        }
Example #57
0
 private Assembly(System.Reflection.Assembly assembly)
 {
     _assembly = assembly;
 }
Example #58
0
 /// <summary>
 /// Add all message handlers that are found in specified assembly.
 /// </summary>
 /// <param name="asm"></param>
 /// <returns></returns>
 public MessageBusConfigurator AddMessageHandlersFromAssembly(System.Reflection.Assembly asm)
 {
     RegisterMessageHandlersFromAssembly(asm, _wc);
     return(this);
 }
 public Program(System.Reflection.Assembly assembly)
 {
     this.assembly = assembly;
 }
Example #60
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);
        }