Example #1
0
 public XamlParserContext (XamlSchemaContext schemaContext, Assembly localAssembly)
     : base(schemaContext)
 {
     this._stack = new XamlContextStack<XamlParserFrame>(() => new XamlParserFrame());
     this._prescopeNamespaces = new Dictionary<string, string>();
     base._localAssembly = localAssembly;
 }
Example #2
0
    public ExistingTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcessExistingAttribute\bin\Debug\AssemblyToProcessExistingAttribute.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var currentDirectory = AssemblyLocation.CurrentDirectory();
        var moduleWeaver = new ModuleWeaver
                           {
                               ModuleDefinition = moduleDefinition,
                               AddinDirectoryPath = currentDirectory,
                               SolutionDirectoryPath = currentDirectory,
                               AssemblyFilePath = afterAssemblyPath,
                           };

        moduleWeaver.Execute();
        moduleDefinition.Write(afterAssemblyPath);
        moduleWeaver.AfterWeaving();

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Example #3
0
    public WeaverHelper(string projectPath)
    {
        this.projectPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\TestAssemblies", projectPath));

        GetAssemblyPath();

        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);

        var assemblyResolver = new TestAssemblyResolver(BeforeAssemblyPath, this.projectPath);
        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = assemblyResolver
        };
        var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, readerParameters);
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver
                              };

        weavingTask.Execute();

        moduleDefinition.Write(AfterAssemblyPath);

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
    public WithIncludesTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory,@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "3.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var assemblyResolver = new MockAssemblyResolver
            {
                Directory = Path.GetDirectoryName(beforeAssemblyPath)
            };
        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath,new ReaderParameters
            {
                AssemblyResolver = assemblyResolver
            });
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver,
                                  IncludeNamespaces = new List<string>{"MyNameSpace"},
                                  LogWarning =s => warnings.Add(s)
                              };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
    public IntegrationTests()
    {
        beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
        #if (!DEBUG)

        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
        #endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var assemblyResolver = new MockAssemblyResolver
            {
                Directory = Path.GetDirectoryName(beforeAssemblyPath)
            };
        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath,new ReaderParameters
            {
                AssemblyResolver = assemblyResolver
            });
        var weavingTask = new ModuleWeaver
                              {
                                  ModuleDefinition = moduleDefinition,
                                  AssemblyResolver = assemblyResolver,
                              };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Example #6
0
    public IntegrationTests()
    {
        beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll"));
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = new MockAssemblyResolver(),
            LogWarning = s => warnings.Add(s),
            LogError = s => errors.Add(s),
            HideObsoleteMembers = true
        };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
 public void AddAssembly(Assembly assembly)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException("assembly");
     }
     if (!this.rawAssemblyLoaders.Contains(assembly))
     {
         try
         {
             this.rawAssemblyLoaders[assembly] = new AssemblyLoader(this, assembly, this.localAssembly == assembly);
             if (this.TypesChanged != null)
             {
                 FireEventsNoThrow(this.TypesChanged, new object[] { this, EventArgs.Empty });
             }
         }
         catch (Exception exception)
         {
             this.typeLoadErrors[assembly.FullName] = exception;
             if (this.TypeLoadErrorsChanged != null)
             {
                 FireEventsNoThrow(this.TypeLoadErrorsChanged, new object[] { this, EventArgs.Empty });
             }
         }
     }
 }
Example #8
0
        /// <summary>
        /// Merges the proxy and the target assemblies and tampers the resulting one.
        /// </summary>
        /// <param name="dependenciesLocations">The paths to the directories which may contain the dependencies.</param>
        /// <returns>The resulting assembly.</returns>
        public IAssembly Tamper(params string[] dependenciesLocations)
        {
            Contract.Ensures(Contract.Result<IAssembly>() != null);

            var tempDirectoryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tempMergedAssemblyPath = Path.Combine(tempDirectoryPath, Path.GetFileName(this.Pair.Target.FilePath));

            Trace.WriteLine(string.Format("Tampering assemblies using temporary file {0}.", tempMergedAssemblyPath));

            Directory.CreateDirectory(tempDirectoryPath);

            Trace.WriteLine("Performing the merging.");
            this.Merge(tempMergedAssemblyPath);
            var result = new Assembly(tempMergedAssemblyPath, dependenciesLocations);

            Trace.WriteLine("Checking for mistakes.");
            this.CheckForMistakes(this.Pair.Proxy);

            Trace.WriteLine("Altering the version, if needed.");
            this.AlterVersion(result);

            Trace.WriteLine("Replacing the public key, if needed.");
            result.ReplacePublicKey(this.Pair.Target);

            Trace.WriteLine("Rewriting the bodies of the methods within the target assembly.");
            this.Rewrite(result);

            Trace.WriteLine("Tampering finished.");
            return result;
        }
        private void AssemblyDetailsForm_Load(object sender, EventArgs e)
        {
            manager = new DBManager(RevitDocument);

            //if (this.IsAdd)
            //{
            //    lblTitle.Text = "";
            //}
            //else
            //{
                toSwap = CurrentAssembly;
            //    lblToSwap.Text = toSwap.AssemblyName;
                loadInformation(toSwap);
            //}
            List<Assembly> fromModel = manager.RetrieveWallInfo();
            //List<Assembly> options = null;
            //if (this.IsAdd)
            //options = manager.getAllAssemblies();
            //options.AddRange(fromModel);

            //else
            //    options = manager.getAssembliesByCode(toSwap.AssemblyCode);
            //if (options != null)
            //{
            //    foreach (Assembly a in options)
            //        cboAlternatives.Items.Add(a);
            //}
        }
Example #10
0
        public static AttributeMap[] Create(TypeModel model, Assembly assembly)
        {

#if FEAT_IKVM
            const bool inherit = false;
            System.Collections.Generic.IList<CustomAttributeData> all = assembly.__GetCustomAttributes(model.MapType(typeof(Attribute)), inherit);
            AttributeMap[] result = new AttributeMap[all.Count];
            int index = 0;
            foreach (CustomAttributeData attrib in all)
            {
                result[index++] = new AttributeDataMap(attrib);
            }
            return result;
#else
#if WINRT || COREFX
            Attribute[] all = System.Linq.Enumerable.ToArray(assembly.GetCustomAttributes());
#else
            const bool inherit = false;
            object[] all = assembly.GetCustomAttributes(inherit);
#endif
            AttributeMap[] result = new AttributeMap[all.Length];
            for(int i = 0 ; i < all.Length ; i++)
            {
                result[i] = new ReflectionAttributeMap((Attribute)all[i]);
            }
            return result;
#endif
        }
Example #11
0
		internal ResourceModule(Assembly assembly, string scopeName, string location)
			: base(assembly.universe)
		{
			this.assembly = assembly;
			this.scopeName = scopeName;
			this.location = location;
		}
        public void It_provides_a_list_of_the_dependencies_of_the_given_target_assembly()
        {
            const string pathToAssembly = @"F:\Projects\Spikes\DependencyVisualizer\DependencyVisualizer.Tests\bin\Debug\DependencyVisualizer.Tests.dll";
              SUT = new Assembly(pathToAssembly);

              Assert.Equal(6, SUT.Dependencies.Count());
        }
Example #13
0
 public static void Instantiate(Assembly a, Interpreter interp)
 {
     Hashtable table = interp.VarTable;
     try {
         CodeChunk chunk = (CodeChunk)a.CreateInstance("CsiChunk");
         chunk.Go(table);
         // vs 0.8 we display the type and value of expressions.  The variable $_ is
         // always set, which is useful if you want to save the result of the last
         // calculation.
         if (interp.returnsValue && DumpingValue) {
             object val = table["_"];
             Type type = val.GetType();
             string stype = type.ToString();
             if (stype.StartsWith("System."))  // to simplify things a little bit...
                 stype = stype.Substring(7);
             stype = "("+stype+")";
             if (val is string) {
                 Print(stype,"'"+val+"'");
             } else
             if (val is IEnumerable) {
                 Print(stype);
                 Dumpl((IEnumerable)val);
             } else
                 Print(stype,val);
         }
     }  catch(Exception ex) {
         Print(ex.GetType() + " was thrown: " + ex.Message);
     }
 }
    public virtual ParticulaDibujable[] GeneraDibujables(Particula[] particula,float[] color,bool aleat)
    {
        ArrayList result=new ArrayList();
        for (int i = 0; i < particula.Length; i++)
        {
            if(particula[i]==null)return (ParticulaDibujable[])result.ToArray(Type.GetType("ParticulaDibujable"));
            try
            {
                if(tempInfo==null || tempInfo.Nombre!=particula[i].GetType().Name)
                {
                    tempInfo=pinfo.GetInfoParticulas(particula[i].GetType().Name);
                }

            }
            catch (Exception ex) { throw new Exception("Error al Generar Particulas Dibujables"); }
            assem=GestorEnsamblados.GetAssemblyByName(tempInfo.EnsambladoDibujable,tempInfo.PathDibujable);
            if(aleat)
            {
                result.Add((ParticulaDibujable)assem.CreateInstance(tempInfo.NombreDibujable, true, BindingFlags.CreateInstance, null, new object[] {particula[i]}, null, null));
            }
            else
            {
                result.Add((ParticulaDibujable)assem.CreateInstance(tempInfo.NombreDibujable, true, BindingFlags.CreateInstance, null, new object[] {particula[i], color}, null, null));
            }

        }
        return (ParticulaDibujable[])result.ToArray(Type.GetType("ParticulaDibujable"));
    }
 public ClassValidator(string xamlFileName, Assembly localAssembly, string rootNamespace)
 {
     this.xamlFileName = xamlFileName;
     this.localAssembly = localAssembly;
     this.eventArgs = null;
     this.rootNamespace = rootNamespace;
 }
Example #16
0
 public AssemblyViewModel(
     IViewModelDependencies appCtx, IZetboxContext dataCtx, ViewModel parent,
     Assembly obj)
     : base(appCtx, dataCtx, parent, obj)
 {
     _assembly = obj;
 }
 public TinyMCECodeGenerator()
 {
     Context = new AssemblyContext();
     Assembly = new Assembly
     {
         Usings = new List<string> 
             { 
                 "System",
                 "System.Collections.Generic",
             }
     };
     Context.Assemblies.Add(Assembly);
     var asm = new Assembly
     {
         Classes = new List<Class>
         {
             new Class{Name="void"},
             new Class{Name="object"},
             new Class{Name="bool"},
             new Class{Name="string"},
             new Class{Name="Array"},
             new Class{Name="int"},
             new Class{Name="Function", IsDelegate=true},
         }
     };
     Context.Assemblies.Add(asm);
     ObjectClass = Context.GetClass("object");
 }
Example #18
0
    public void Setup()
    {
        var projectPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\AssemblyToProcess\AssemblyToProcess.csproj"));
        assemblyPath = Path.Combine(Path.GetDirectoryName(projectPath), @"bin\Debug\AssemblyToProcess.dll");
#if (!DEBUG)
        assemblyPath = assemblyPath.Replace("Debug", "Release");
#endif

        newAssemblyPath = assemblyPath.Replace(".dll", "2.dll");
        shadowAssemblyPath = assemblyPath.Replace(".dll", "2shadow.dll");
        File.Copy(assemblyPath, newAssemblyPath, true);
        File.Copy(assemblyPath, shadowAssemblyPath, true);
        
        var moduleDefinition = ModuleDefinition.ReadModule(newAssemblyPath);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition            
        };

        weavingTask.Execute();

        moduleDefinition.Write(newAssemblyPath);

        assembly = Assembly.LoadFile(newAssemblyPath);
    }
    public static void Main(string[] args)
    {
        libslAssembly = Assembly.Load("libsecondlife");
        if (libslAssembly == null) throw new Exception("Assembly load exception");

        ProxyConfig proxyConfig = new ProxyConfig("Analyst V2", "Austin Jennings / Andrew Ortman", args);
        proxy = new Proxy(proxyConfig);

        // build the table of /command delegates
        InitializeCommandDelegates();

        // add delegates for login
        proxy.SetLoginRequestDelegate(new XmlRpcRequestDelegate(LoginRequest));
        proxy.SetLoginResponseDelegate(new XmlRpcResponseDelegate(LoginResponse));

        // add a delegate for outgoing chat
        proxy.AddDelegate(PacketType.ChatFromViewer, Direction.Outgoing, new PacketDelegate(ChatFromViewerOut));

        //  handle command line arguments
        foreach (string arg in args)
            if (arg == "--log-all")
                LogAll();
            else if (arg == "--log-login")
                logLogin = true;

        // start the proxy
        proxy.Start();
    }
Example #20
0
 /// <summary>
 /// Execute a public method_name(args) in compiled_assembly
 /// </summary>
 /// <param name="compiled_assembly">compiled assembly</param>
 /// <param name="methode_name">method to execute</param>
 /// <param name="args">method arguments</param>
 /// <returns>method execution result</returns>
 public static object ExecuteInstanceMethod(Assembly compiled_assembly, string methode_name, object[] args)
 {
     if (compiled_assembly != null)
     {
         foreach (Type type in compiled_assembly.GetTypes())
         {
             foreach (MethodInfo method in type.GetMethods())
             {
                 if (method.Name == methode_name)
                 {
                     if ((method != null) && (method.IsPublic))
                     {
                         object obj = Activator.CreateInstance(type, null);
                         return method.Invoke(obj, args);
                     }
                     else
                     {
                         throw new Exception("Cannot invoke method :" + methode_name);
                     }
                 }
             }
         }
     }
     return null;
 }
 public WithInterceptorTests()
 {
     var assemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\DebugWithInterceptor\AssemblyToProcess.dll");
     assembly = AssemblyWeaver.Weave(assemblyPath);
     var methodTimeLogger = assembly.GetType("MethodTimeLogger");
     methodBaseField = methodTimeLogger.GetField("MethodBase");
 }
Example #22
0
	static int GetTypeTrue (Assembly a)
	{
		string typename = "InheritanceDemand";
		Type t = a.GetType (typename, true);
		Console.WriteLine ("*0* Can get type '{0}' with security.", t);
		return 0;
	}
    static AssemblyWeaver()
    {
        BeforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
        BeforeAssemblyPathSymbols = Path.ChangeExtension(BeforeAssemblyPath, "pdb");

        #if (!DEBUG)
        BeforeAssemblyPath = BeforeAssemblyPath.Replace("Debug", "Release");
        BeforeAssemblyPathSymbols = BeforeAssemblyPathSymbols.Replace("Debug", "Release");
        #endif
        AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
        AfterAssemblyPathSymbols = Path.ChangeExtension(AfterAssemblyPath, "pdb");

        File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
        File.Copy(BeforeAssemblyPathSymbols, AfterAssemblyPathSymbols, true);

        var assemblyResolver = new MockAssemblyResolver();
        var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, new ReaderParameters { ReadSymbols = true });

        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
            LogError = LogError,
            LogInfo = LogInfo,
            DefineConstants = new[] { "DEBUG" }, // Always testing the debug weaver
        };

        weavingTask.Execute();
        moduleDefinition.Write(AfterAssemblyPath, new WriterParameters { WriteSymbols = true });

        Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
Example #24
0
#pragma warning restore 0649


        static DateTime GetBuildDateTime(Assembly assembly)
        {
            if (File.Exists(assembly.Location))
            {
                var buffer = new byte[Math.Max(Marshal.SizeOf(typeof(_IMAGE_FILE_HEADER)), 4)];
                using (var fileStream = new FileStream(assembly.Location, FileMode.Open, FileAccess.Read))
                {
                    fileStream.Position = 0x3C;
                    fileStream.Read(buffer, 0, 4);
                    fileStream.Position = BitConverter.ToUInt32(buffer, 0); // COFF header offset
                    fileStream.Read(buffer, 0, 4); // "PE\0\0"
                    fileStream.Read(buffer, 0, buffer.Length);
                }
                var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                try
                {
                    var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER));

                    return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1) 
                        + new TimeSpan(coffHeader.TimeDateStamp * TimeSpan.TicksPerSecond));
                }
                finally
                {
                    pinnedBuffer.Free();
                }
            }
            return new DateTime();
        }
Example #25
0
    public AssemblyWeaver(string assemblyPath, List<string> referenceAssemblyPaths = null)
    {
        if (referenceAssemblyPaths == null)
        {
            referenceAssemblyPaths  = new List<string>();
        }
        assemblyPath = FixAssemblyPath(assemblyPath);

        var newAssembly = assemblyPath.Replace(".dll", "2.dll");
        File.Copy(assemblyPath, newAssembly, true);

        var assemblyResolver = new MockAssemblyResolver();
        foreach (var referenceAssemblyPath in referenceAssemblyPaths)
        {
            var directoryName = Path.GetDirectoryName(referenceAssemblyPath);
            assemblyResolver.AddSearchDirectory(directoryName);
        }
        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = assemblyResolver
        };
        var moduleDefinition = ModuleDefinition.ReadModule(newAssembly, readerParameters);
        var weavingTask = new ModuleWeaver
        {
            ModuleDefinition = moduleDefinition,
            AssemblyResolver = assemblyResolver,
            LogError = LogError,
            ReferenceCopyLocalPaths = referenceAssemblyPaths
        };

        weavingTask.Execute();
        moduleDefinition.Write(newAssembly);

        Assembly = Assembly.LoadFrom(newAssembly);
    }
        protected override Assembly Generate()
        {
            var nt = Host.NameTable;
            var mscorlib = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity);
            var assembly = new Assembly
                               {
                                   Name = nt.GetNameFor(AssemblyName),
                                   ModuleName = nt.GetNameFor(DllName),
                                   Kind = ModuleKind.DynamicallyLinkedLibrary,
                                   TargetRuntimeVersion = mscorlib.TargetRuntimeVersion,
                                   MetadataFormatMajorVersion = 2
                               };
            assembly.AssemblyReferences.Add(mscorlib);

            var rootNamespace = new RootUnitNamespace();
            assembly.UnitNamespaceRoot = rootNamespace;
            rootNamespace.Unit = assembly;

            // define module
            DefineModule(assembly, rootNamespace);

            var typeA = GenerateTypeA(rootNamespace);
            assembly.AllTypes.Add(typeA);

            var baseType = GenericTypeInstance.GetGenericTypeInstance(typeA, new[] { Host.PlatformType.SystemString }, Host.InternFactory);
            var typeB = GenerateTypeB(rootNamespace, baseType);
            assembly.AllTypes.Add(typeB);

            return assembly;
        }
 public void run(Assembly item)
 {
     item
         .all_types()
         .where(x => !exclusion_policy.is_satisfied_by(x))
         .each(x => add_registration_for(x));
 }
Example #28
0
 public MainWindow(ref Assembly asm)
     : base(Gtk.WindowType.Toplevel)
 {
     this.asm = asm;
     Build ();
     parser = new Parser();
 }
Example #29
0
    public DebugConsoleBridge()
    {
        _assembly = Assembly.GetAssembly(typeof(SceneView));

        _typeLogEntries = _assembly.GetType("UnityEditorInternal.LogEntries");

        _startGettingEntriesMethod = _typeLogEntries.GetMethod("StartGettingEntries");
        _getEntryInternalMethod = _typeLogEntries.GetMethod("GetEntryInternal");
        _endGettingEntriesMethod = _typeLogEntries.GetMethod("EndGettingEntries");
        _getCountMethod = _typeLogEntries.GetMethod("GetCount");
        _clearMethod = _typeLogEntries.GetMethod("Clear");
        _getCountsByTypeMethod = _typeLogEntries.GetMethod("GetCountsByType");
        _setConsoleFlagMethod = _typeLogEntries.GetMethod("SetConsoleFlag");
        _getConsoleFlagsMethod = _typeLogEntries.GetMethod("get_consoleFlags");
        _getStatusTextMethod = _typeLogEntries.GetMethod("GetStatusText");

        _typeLogEntry = _assembly.GetType("UnityEditorInternal.LogEntry");

        _conditionField = _typeLogEntry.GetField("condition");
        _modeField = _typeLogEntry.GetField("mode");
        _instanceIdField = _typeLogEntry.GetField("instanceID");
        _fileField = _typeLogEntry.GetField("file");
        _lineField = _typeLogEntry.GetField("line");

        Type typeStyles = typeof(EditorGUIUtility);
        if(typeStyles != null)
            _getStyleMethod = typeStyles.GetMethod("GetStyle", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.GetField | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Static);

        object entryPlaceholder = Activator.CreateInstance(_typeLogEntry);
          		_getEntryInternalParams = new object[2] { 0, entryPlaceholder };
    }
Example #30
0
    public TaskTests()
    {
        beforeAssemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll");
#if (!DEBUG)
        beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release");
#endif

        afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll");
        File.Copy(beforeAssemblyPath, afterAssemblyPath, true);

        var moduleDefinition = ModuleDefinition.ReadModule(afterAssemblyPath);
        var currentDirectory = AssemblyLocation.CurrentDirectory();
        var weavingTask = new ModuleWeaver
                          {
                              ModuleDefinition = moduleDefinition,
                              AddinDirectoryPath = currentDirectory,
                              SolutionDirectoryPath = currentDirectory,
                              AssemblyFilePath = afterAssemblyPath,
                              SvnHelper = new MockSvnHelper(),
                          };

        weavingTask.Execute();
        moduleDefinition.Write(afterAssemblyPath);
        weavingTask.AfterWeaving();

        assembly = Assembly.LoadFile(afterAssemblyPath);
    }
Example #31
0
        private void bkwMain_DoWork(object sender, DoWorkEventArgs e)
        {
            Guid    argument           = (Guid)e.Argument;
            DataSet drawingForTsOutPut = PlArchivManage.Agent.GetDrawingForTsOutPut(argument);
            int     count  = drawingForTsOutPut.Tables[0].Rows.Count;
            int     length = Assembly.GetExecutingAssembly().Location.LastIndexOf(@"\");
            string  str    = Assembly.GetExecutingAssembly().Location.Substring(0, length);

            if (count == 0)
            {
                MessageBox.Show("未查询到任何数据!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                e.Result = "未查询到任何数据!...";
            }
            else
            {
                IWorkbook  workbook;
                FileStream stream;
                int        num5;
                string     path = str + @"\plmtuoshaidan.xls";
                int        num3 = drawingForTsOutPut.Tables[0].Rows.Count;
                int        num4 = drawingForTsOutPut.Tables[0].Columns.Count;
                using (stream = File.OpenRead(path))
                {
                    workbook = WorkbookFactory.Create(stream);
                    stream.Close();
                }
                ISheet sheetAt = workbook.GetSheetAt(0);
                for (num5 = 0; num5 < sheetAt.NumMergedRegions; num5++)
                {
                    CellRangeAddress mergedRegion = sheetAt.GetMergedRegion(num5);
                    switch (sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).ToString())
                    {
                    case "$liuchengmingcheng":
                        sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).SetCellValue(this._wk);
                        break;

                    case "$name":
                        sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).SetCellValue(this._name);
                        break;

                    case "$tsfs":
                        sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).SetCellValue(this._TSTYPE);
                        break;

                    case "$ttfs":
                        sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).SetCellValue(this._YCT);
                        break;

                    case "$sm":
                        sheetAt.GetRow(mergedRegion.FirstRow).GetCell(mergedRegion.FirstColumn).SetCellValue(this._SM);
                        break;
                    }
                }
                for (num5 = 0; num5 < 5; num5++)
                {
                    for (int i = 0; i < 6; i++)
                    {
                        switch (sheetAt.GetRow(num5).GetCell(i).ToString())
                        {
                        case "$tsfs":
                            sheetAt.GetRow(num5).GetCell(i).SetCellValue(this._TSTYPE);
                            break;

                        case "$ttfs":
                            sheetAt.GetRow(num5).GetCell(i).SetCellValue(this._YCT);
                            break;

                        case "$SM":
                            sheetAt.GetRow(num5).GetCell(i).SetCellValue(this._SM);
                            break;
                        }
                    }
                }
                int        num7  = 5;
                int        num8  = 1;
                int        num9  = 0;
                short      num10 = 460;
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Medium;
                style.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Medium;
                style.BorderRight       = NPOI.SS.UserModel.BorderStyle.Medium;
                style.BorderTop         = NPOI.SS.UserModel.BorderStyle.Medium;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.WrapText          = true;
                foreach (DataRow row in drawingForTsOutPut.Tables[0].Rows)
                {
                    IRow row2 = sheetAt.CreateRow(num7++);
                    row2.Height = (short)(num10 * ((Encoding.Default.GetByteCount(row[5].ToString()) / 40) + 1));
                    ICell cell = row2.CreateCell(0);
                    cell.SetCellValue((double)num8++);
                    cell.CellStyle = style;
                    cell           = row2.CreateCell(1);
                    cell.SetCellValue(row[0].ToString());
                    cell.CellStyle = style;
                    cell           = row2.CreateCell(2);
                    cell.SetCellValue(row[2].ToString());
                    cell.CellStyle = style;
                    cell           = row2.CreateCell(3);
                    cell.SetCellValue(row[3].ToString());
                    cell.CellStyle           = style;
                    cell.CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    cell = row2.CreateCell(4);
                    cell.SetCellValue(row[4].ToString());
                    cell.CellStyle           = style;
                    cell.CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    cell = row2.CreateCell(5);
                    cell.SetCellValue(row[5].ToString());
                    cell.CellStyle = style;
                    string str4 = row.Table.Columns[3].ToString();
                    num9 += Convert.ToInt32(row[3].ToString());
                }
                sheetAt.CreateRow(num7 + 2).CreateCell(1).SetCellValue("合计" + num9 + " 张");
                sheetAt.GetRow(num7 + 2).CreateCell(3).SetCellValue("计划签字:");
                sheetAt.GetRow(num7 + 2).CreateCell(4).SetCellValue(PLUser.Agent.GetUserByOid(this._item.Creator).Name);
                sheetAt.GetRow(num7 + 2).CreateCell(5).SetCellValue(DateTime.Now.ToShortDateString());
                using (stream = new FileStream("C:/a.xls", FileMode.Create))
                {
                    workbook.Write(stream);
                    stream.Close();
                }
                Process.Start("C:/a.xls");
                e.Result = "报表已生成...请保存...";
            }
        }
Example #32
0
 static Type[] GetInterfaces <T>()
 {
     return(Assembly.GetExecutingAssembly().GetTypes().Where(c => c.GetInterfaces().Any(t => t == typeof(T))).ToArray());
 }
Example #33
0
        public static IServiceCollection AddAllImplementationsOfInterfaceInAssemblyAsSingleton <TInterface>(this IServiceCollection serviceCollection, Assembly assembly)
        {
            Type interfaceType = typeof(TInterface);

            if (!interfaceType.IsInterface)
            {
                throw new InvalidOperationException($"Not an interface: {interfaceType}");
            }

            foreach (var implementationType in assembly
                     .GetTypes()
                     .Where(t => t.IsClass && !t.IsAbstract && interfaceType.IsAssignableFrom(t)))
            {
                serviceCollection.AddSingleton(interfaceType, implementationType);
            }

            return(serviceCollection);
        }
Example #34
0
 private void InitLoadControls()
 {
     string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
     this.Text += version;
     Logger.Info(string.Format("get software version: [{0}]", version));
 }
Example #35
0
        } //Ez futatja a DataGridView-ba kért lekérdezést

        static void DrawToTab1(List <Datastruct> temp)
        {
            string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            //string asd = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            byte eltolas = 0;

            for (int j = 0; j < 30; j++)
            {
                // dátum
                Label  date_lbl = new Label();
                string honap;
                int    hetszam = Convert.ToInt32(temp[j].date.DayOfWeek);
                string napnev  = "Error!";
                string nap;
                switch (hetszam)
                {
                case 0:
                    napnev = "Vasárnap";
                    break;

                case 1:
                    napnev = "Hétfő";
                    break;

                case 2:
                    napnev = "Kedd";
                    break;

                case 3:
                    napnev = "Szerda";
                    break;

                case 4:
                    napnev = "Csütörtök";
                    break;

                case 5:
                    napnev = "Péntek";
                    break;

                case 6:
                    napnev = "Szombat";
                    break;

                default:
                    napnev = "Error";
                    break;
                }
                if (temp[j].date.Day < 10)
                {
                    nap = "0" + Convert.ToString(temp[j].date.Day);
                }
                else
                {
                    nap = Convert.ToString(temp[j].date.Day);
                }

                if (temp[j].date.Month < 10)
                {
                    honap = "0" + Convert.ToString(temp[j].date.Month);
                }
                else
                {
                    honap = temp[j].date.Month.ToString();
                }
                date_lbl.Text     = honap + "." + nap + ".\n" + napnev;
                date_lbl.Name     = "data_lbl" + j.ToString();
                date_lbl.Size     = new Size(37, 30);
                date_lbl.Location = new Point(j * 50 + 14 + eltolas, 30); // plusz 16 miatt van középen a szöveg a képhez képest
                panel1.Controls.Add(date_lbl);

                string filepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                //dátum vége
                try
                {
                    //pcb -> képek
                    PictureBox pcb = new PictureBox();
                    pcb.Size = new Size(32, 32);
                    if (temp[j].weathertype.Contains("Erősen felhős") || temp[j].weathertype.Contains("Borult"))
                    {
                        Bitmap bit = new Bitmap(filepath + @"\borult.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Közepesen felhős") || temp[j].weathertype.Contains("Gyengén felhős"))
                    {
                        Bitmap bit = new Bitmap(filepath + @"\kozepesen_felhos.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Szeles nap") || temp[j].weathertype.Contains("Viharos szél") || temp[j].weathertype.Contains("Hidegfront erős széllel"))
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\szeles_nap.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Zápor") || temp[j].weathertype.Contains("Gyenge eső") || temp[j].weathertype.Contains("Zivatar") || temp[j].weathertype.Contains("zivatarok"))
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\zapor.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Eső"))
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\eso.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Derült") || temp[j].weathertype.Contains("Melegfront"))
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\derult.png");
                        pcb.Image = bit;
                    }
                    else if (temp[j].weathertype.Contains("Havas eső") || temp[j].weathertype.Contains("Hózápor"))
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\havas.png");
                        pcb.Image = bit;
                    }
                    else
                    {
                        Bitmap bit = new Bitmap(@filepath + @"\error.png");
                        pcb.Image = bit;
                    }
                    ToolTip tt = new ToolTip();
                    tt.SetToolTip(pcb, temp[j].weathertype);
                    pcb.SizeMode = PictureBoxSizeMode.StretchImage; //beletördeli a picutrebox-ba a képet
                    pcb.Location = new Point(j * 50 + 15 + eltolas, 70);
                    pcb.Name     = "pcb" + j.ToString();
                    panel1.Controls.Add(pcb);
                    ////pcb -> képek Vége
                }
                catch (System.ArgumentException e)
                {
                    MessageBox.Show(e.ToString() + temp[j].weathertype);
                }

                //max hőfok
                Label max_hofok_lbl = new Label();
                max_hofok_lbl.Text     = temp[j].max_temperature.ToString() + "°C";
                max_hofok_lbl.Size     = new Size(32, 15);
                max_hofok_lbl.Location = new Point(j * 50 + 20 + eltolas, 130);
                max_hofok_lbl.Name     = "max_hofok_lbl" + j.ToString();
                panel1.Controls.Add(max_hofok_lbl);
                if (temp[j].max_temperature > 10)
                {
                    eltolas++;
                }
                if (temp[j].max_temperature < -9)
                {
                    eltolas++;
                }
                //min hőfok vége

                //min hőfok
                Label min_hofok_lbl = new Label();
                min_hofok_lbl.Text     = temp[j].min_temperature.ToString() + "°C";
                min_hofok_lbl.Size     = new Size(32, 15);
                min_hofok_lbl.Location = new Point(j * 50 + 20 + eltolas, 180);
                min_hofok_lbl.Name     = "min_hofok_lbl" + j.ToString();
                panel1.Controls.Add(min_hofok_lbl);
                if (temp[j].min_temperature > 9)
                {
                    eltolas++;
                }
                if (temp[j].min_temperature < -9)
                {
                    eltolas += 2;
                }
                //min hőfok vége

                if (j < 7)
                {
                    //rain
                    Label rain_lbl = new Label();
                    rain_lbl.Text     = temp[j].rain.ToString() + " mm";
                    rain_lbl.Size     = new Size(32, 15);
                    rain_lbl.Location = new Point(j * 50 + 20 + eltolas, 230);
                    rain_lbl.Name     = "rain_lbl" + j.ToString();
                    panel1.Controls.Add(rain_lbl);
                    if (temp[j].rain > 10)
                    {
                        eltolas++;
                    }
                    //rain vége

                    //rain probaility lbl
                    Label rain_probality_lbl = new Label();
                    rain_probality_lbl.Text     = temp[j].rain_probability.ToString() + "%";
                    rain_probality_lbl.Size     = new Size(32, 15);
                    rain_probality_lbl.Location = new Point(j * 50 + 24 + eltolas, 280);
                    rain_probality_lbl.Name     = "rain_probality_lbl" + j.ToString();
                    panel1.Controls.Add(rain_probality_lbl);
                    //rain probaility lbl vége
                }
            } // form labelek, pictureboxok}
        }     //Megkap egy Lit<Datastruct>-ot és azt kirajzolja a Tab1-re
Example #36
0
        public FrmLogin(FrmStart _frmstart)
        {
            InitializeComponent();
            try
            {
                this.frmStart          = _frmstart;
                this.tbPwd.Region      = new Region(GetRoundRectPath(new RectangleF(0, 0, this.tbPwd.Width, this.tbPwd.Height), 5f));
                this.tbUserName.Region = new Region(GetRoundRectPath(new RectangleF(0, 0, this.tbUserName.Width, this.tbUserName.Height), 5f));
                this.iniSysInfo(false);
                this.tbUserName.Text = string.Empty;
                this.tbPwd.Text      = string.Empty;
                this.ActiveControl   = this.tbUserName;
                this.tbUserName.Focus();
                Assembly assembly = Assembly.GetExecutingAssembly();
                //this.labelEdition.Text = assembly.FullName;

                // 获取程序集元数据
                AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)
                                                       AssemblyCopyrightAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
                                                                                                     typeof(AssemblyCopyrightAttribute));
                AssemblyDescriptionAttribute description = (AssemblyDescriptionAttribute)
                                                           AssemblyDescriptionAttribute.GetCustomAttribute(System.Reflection.Assembly.GetExecutingAssembly(),
                                                                                                           typeof(AssemblyDescriptionAttribute));
            }
            catch (Exception ex)
            {
                LoggerHelper.Log("MsmkLogger", "FrmLogin--->FrmLogin-->Error:" + ex.ToString(), LogEnum.ExceptionLog);
            }
        }
Example #37
0
        /// <summary>
        /// Usage message.
        /// </summary>
        private static void Usage(Mono.Options.OptionSet options)
        {

            // show usage
            WriteLine();
            WriteLine("Usage: {0}.exe <applicationname> [<iothubconnectionstring>] [<options>]", Assembly.GetEntryAssembly().GetName().Name);
            WriteLine();
            WriteLine("OPC Edge Publisher to subscribe to configured OPC UA servers and send telemetry to Azure IoTHub.");
            WriteLine("To exit the application, just press ENTER while it is running.");
            WriteLine();
            WriteLine("applicationname: the OPC UA application name to use, required");
            WriteLine("                 The application name is also used to register the publisher under this name in the");
            WriteLine("                 IoTHub device registry.");
            WriteLine();
            WriteLine("iothubconnectionstring: the IoTHub owner connectionstring, optional");
            WriteLine();
            WriteLine("There are a couple of environment variables which can be used to control the application:");
            WriteLine("_HUB_CS: sets the IoTHub owner connectionstring");
            WriteLine("_GW_LOGP: sets the filename of the log file to use");
            WriteLine("_TPC_SP: sets the path to store certificates of trusted stations");
            WriteLine("_GW_PNFP: sets the filename of the publishing configuration file");
            WriteLine();
            WriteLine("Command line arguments overrule environment variable settings.");
            WriteLine();

            // output the options
            WriteLine("Options:");
            options.WriteOptionDescriptions(Console.Out);
        }
Example #38
0
        /// <summary>Discovers the routes.</summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="assemblyDirectoryPath">The assembly directory path.</param>
        /// <param name="assemblyMatchPattern">The assembly match pattern.</param>
        /// <returns></returns>
        protected virtual Task<IList<DeepSleepRouteRegistration>> DiscoverRoutes(
            IServiceProvider serviceProvider, 
            string assemblyDirectoryPath, 
            string assemblyMatchPattern)
        {
            var registrations = new List<DeepSleepRouteRegistration>();

            var files = Directory.GetFiles(assemblyDirectoryPath, assemblyMatchPattern, this.searchOption);

            foreach (var file in files)
            {
                Assembly assembly = null;

                try
                {
                    assembly = Assembly.LoadFile(file);
                }
                catch { }


                if (assembly != null)
                {
                    IEnumerable<MethodInfo> methods = new List<MethodInfo>();

                    try
                    {
                        methods = assembly
                            .GetTypes()
                            .SelectMany(t => t.GetMethods(bindingAttr: BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod))
                            .Where(m => m.GetCustomAttribute<ApiRouteAttribute>() != null);
                    }
                    catch { }

                    foreach (var method in methods)
                    {
                        var apiRoute = method.GetCustomAttribute<ApiRouteAttribute>(false);

                        DeepSleepRequestConfiguration configuration = null;
                        configuration = this.AssignRouteAllowAnonymousAttribute(configuration, method.GetCustomAttribute<ApiRouteAllowAnonymousAttribute>());
                        configuration = this.AssignRouteCacheDirectiveAttribute(configuration, method.GetCustomAttribute<ApiRouteCacheDirectiveAttribute>());
                        configuration = this.AssignRouteCrossOriginAttribute(configuration, method.GetCustomAttribute<ApiRouteCrossOriginAttribute>());
                        configuration = this.AssignRouteEnableHeadAttribute(configuration, method.GetCustomAttribute<ApiRouteEnableHeadAttribute>());
                        configuration = this.AssignRouteLanguageAttribute(configuration, method.GetCustomAttribute<ApiRouteLanguageSupportAttribute>());
                        configuration = this.AssignRouteRequestValidationAttribute(configuration, method.GetCustomAttribute<ApiRouteRequestValidationAttribute>());
                        configuration = this.AssignRouteValidationErrorConfigurationAttribute(configuration, method.GetCustomAttribute<ApiRouteValidationErrorConfigurationAttribute>());
                        configuration = this.AssignRouteErrorResponseProviderAttribute(configuration, method.GetCustomAttribute<ApiRouteErrorResponseProviderAttribute>());
                        configuration = this.AssignRouteMediaSerializerConfigurationAttribute(configuration, method.GetCustomAttribute<ApiRouteMediaSerializerConfigurationAttribute>());

                        var registration = new DeepSleepRouteRegistration(
                            template: apiRoute.Template,
                            httpMethods: apiRoute.HttpMethods,
                            controller: Type.GetType(method.DeclaringType.AssemblyQualifiedName),
                            methodInfo: method,
                            config: configuration);

                        registrations.Add(registration);
                    }
                }
            }

            return Task.FromResult(registrations as IList<DeepSleepRouteRegistration>);
        }
        private static void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            e.Cancel = true;
            Assembly mainAssembly = e.Argument as Assembly;

            var companyAttribute =
                (AssemblyCompanyAttribute) GetAttribute(mainAssembly, typeof(AssemblyCompanyAttribute));
            if (string.IsNullOrEmpty(AppTitle))
            {
                var titleAttribute =
                    (AssemblyTitleAttribute) GetAttribute(mainAssembly, typeof(AssemblyTitleAttribute));
                AppTitle = titleAttribute != null ? titleAttribute.Title : mainAssembly.GetName().Name;
            }

            string appCompany = companyAttribute != null ? companyAttribute.Company : "";

            RegistryLocation = !string.IsNullOrEmpty(appCompany)
                ? $@"Software\{appCompany}\{AppTitle}\AutoUpdater"
                : $@"Software\{AppTitle}\AutoUpdater";

            InstalledVersion = mainAssembly.GetName().Version;

            WebRequest webRequest = WebRequest.Create(AppCastURL);

            webRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

            if (Proxy != null)
            {
                webRequest.Proxy = Proxy;
            }

            var uri = new Uri(AppCastURL);

            WebResponse webResponse;

            try
            {
                if (uri.Scheme.Equals(Uri.UriSchemeFtp))
                {
                    var ftpWebRequest = (FtpWebRequest) webRequest;
                    ftpWebRequest.Credentials = FtpCredentials;
                    ftpWebRequest.UseBinary = true;
                    ftpWebRequest.UsePassive = true;
                    ftpWebRequest.KeepAlive = true;
                    ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                    webResponse = ftpWebRequest.GetResponse();
                }
                else if(uri.Scheme.Equals(Uri.UriSchemeHttp) || uri.Scheme.Equals(Uri.UriSchemeHttps))
                {
                    HttpWebRequest httpWebRequest = (HttpWebRequest) webRequest;

                    httpWebRequest.UserAgent = GetUserAgent();

                    if (BasicAuthXML != null)
                    {
                        httpWebRequest.Headers[HttpRequestHeader.Authorization] = BasicAuthXML.ToString();
                    }

                    webResponse = httpWebRequest.GetResponse();
                }
                else
                {
                    webResponse = webRequest.GetResponse(); 
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
                e.Cancel = false;
                return;
            }

            UpdateInfoEventArgs args;

            using (Stream appCastStream = webResponse.GetResponseStream())
            {
                if (appCastStream != null)
                {
                    if (ParseUpdateInfoEvent != null)
                    {
                        using (StreamReader streamReader = new StreamReader(appCastStream))
                        {
                            string data = streamReader.ReadToEnd();
                            ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(data);
                            ParseUpdateInfoEvent(parseArgs);
                            args = parseArgs.UpdateInfo;
                        }
                    }
                    else
                    {
                        XmlDocument receivedAppCastDocument = new XmlDocument();

                        try
                        {
                            receivedAppCastDocument.Load(appCastStream);

                            XmlNodeList appCastItems = receivedAppCastDocument.SelectNodes("item");

                            args = new UpdateInfoEventArgs();

                            if (appCastItems != null)
                            {
                                foreach (XmlNode item in appCastItems)
                                {
                                    XmlNode appCastVersion = item.SelectSingleNode("version");

                                    try
                                    {
                                        CurrentVersion = new Version(appCastVersion?.InnerText);
                                    }
                                    catch (Exception)
                                    {
                                        CurrentVersion = null;
                                    }

                                    args.CurrentVersion = CurrentVersion;

                                    XmlNode appCastChangeLog = item.SelectSingleNode("changelog");

                                    args.ChangelogURL = appCastChangeLog?.InnerText;

                                    XmlNode appCastUrl = item.SelectSingleNode("url");

                                    args.DownloadURL = appCastUrl?.InnerText;

                                    if (Mandatory.Equals(false))
                                    {
                                        XmlNode mandatory = item.SelectSingleNode("mandatory");

                                        Boolean.TryParse(mandatory?.InnerText, out Mandatory);

                                        string mode = mandatory?.Attributes["mode"]?.InnerText;

                                        if (!string.IsNullOrEmpty(mode))
                                        {
                                            UpdateMode = (Mode) Enum.Parse(typeof(Mode), mode);
                                            if (ReportErrors && !Enum.IsDefined(typeof(Mode), UpdateMode))
                                            {
                                                throw new InvalidDataException(
                                                    $"{UpdateMode} is not an underlying value of the Mode enumeration.");
                                            }
                                        }
                                    }

                                    args.Mandatory = Mandatory;
                                    args.UpdateMode = UpdateMode;

                                    XmlNode appArgs = item.SelectSingleNode("args");

                                    args.InstallerArgs = appArgs?.InnerText;

                                    XmlNode checksum = item.SelectSingleNode("checksum");

                                    args.HashingAlgorithm = checksum?.Attributes["algorithm"]?.InnerText;

                                    args.Checksum = checksum?.InnerText;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            e.Cancel = false;
                            webResponse.Close();
                            return;
                        }
                    }
                }
                else
                {
                    e.Cancel = false;
                    webResponse.Close();
                    return;
                }
            }

            if (args.CurrentVersion == null || string.IsNullOrEmpty(args.DownloadURL))
            {
                webResponse.Close();
                if (ReportErrors)
                {
                    throw new InvalidDataException();
                }

                return;
            }

            CurrentVersion = args.CurrentVersion;
            ChangelogURL = args.ChangelogURL = GetURL(webResponse.ResponseUri, args.ChangelogURL);
            DownloadURL = args.DownloadURL = GetURL(webResponse.ResponseUri, args.DownloadURL);
            InstallerArgs = args.InstallerArgs ?? String.Empty;
            HashingAlgorithm = args.HashingAlgorithm ?? "MD5";
            Checksum = args.Checksum ?? String.Empty;

            webResponse.Close();

            if (Mandatory)
            {
                ShowRemindLaterButton = false;
                ShowSkipButton = false;
            }
            else
            {
                using (RegistryKey updateKey = Registry.CurrentUser.OpenSubKey(RegistryLocation))
                {
                    if (updateKey != null)
                    {
                        object skip = updateKey.GetValue("skip");
                        object applicationVersion = updateKey.GetValue("version");
                        if (skip != null && applicationVersion != null)
                        {
                            string skipValue = skip.ToString();
                            var skipVersion = new Version(applicationVersion.ToString());
                            if (skipValue.Equals("1") && CurrentVersion <= skipVersion)
                                return;
                            if (CurrentVersion > skipVersion)
                            {
                                using (RegistryKey updateKeyWrite = Registry.CurrentUser.CreateSubKey(RegistryLocation))
                                {
                                    if (updateKeyWrite != null)
                                    {
                                        updateKeyWrite.SetValue("version", CurrentVersion.ToString());
                                        updateKeyWrite.SetValue("skip", 0);
                                    }
                                }
                            }
                        }

                        object remindLaterTime = updateKey.GetValue("remindlater");

                        if (remindLaterTime != null)
                        {
                            DateTime remindLater = Convert.ToDateTime(remindLaterTime.ToString(),
                                CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);

                            int compareResult = DateTime.Compare(DateTime.Now, remindLater);

                            if (compareResult < 0)
                            {
                                e.Cancel = false;
                                e.Result = remindLater;
                                return;
                            }
                        }
                    }
                }
            }

            args.IsUpdateAvailable = CurrentVersion > InstalledVersion;
            args.InstalledVersion = InstalledVersion;

            e.Cancel = false;
            e.Result = args;
        }
Example #40
0
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
 }
 /// <summary>
 ///     Start checking for new version of application and display dialog to the user if update is available.
 /// </summary>
 /// <param name="myAssembly">Assembly to use for version checking.</param>
 public static void Start(Assembly myAssembly = null)
 {
     Start(AppCastURL, myAssembly);
 }
Example #42
0
        public void StartPlugin(
            TabPage pluginScreenSpace,
            Label pluginStatusText)
        {
            // タイトルをセットする
            pluginScreenSpace.Text = "ULTRA SCOUTER";

            WPFHelper.Start();
            WPFHelper.BeginInvoke(async () =>
            {
                // FFXIV_MemoryReaderを先にロードさせる
                await FFXIVReader.Instance.WaitForReaderToStartedAsync();

                AppLog.LoadConfiguration(AppLog.HojoringConfig);
                this.Logger.Trace(Assembly.GetExecutingAssembly().GetName().ToString() + " start.");

                try
                {
                    this.Logger.Trace("[ULTRA SCOUTER] Start InitPlugin");

                    this.PluginTabPage = pluginScreenSpace;
                    this.PluginStatusLabel = pluginStatusText;

                    // .NET FrameworkとOSのバージョンを確認する
                    if (!UpdateChecker.IsAvailableDotNet() ||
                        !UpdateChecker.IsAvailableWindows())
                    {
                        NotSupportedView.AddAndShow(pluginScreenSpace);
                        return;
                    }

                    // 設定ファイルを読み込む
                    Settings.Instance.Load();

                    // HojoringのSplashを表示する
                    WPFHelper.Start();
                    UpdateChecker.ShowSplash();

                    // 各種ファイルを読み込む
                    await Task.Run(() =>
                    {
                        TTSDictionary.Instance.Load();
                        Settings.Instance.MobList.LoadTargetMobList();
                    });

                    // FFXIVプラグインへのアクセスを開始する
                    await Task.Run(() => FFXIVPlugin.Instance.Start(
                        Settings.Instance.PollingRate,
                        Settings.Instance.FFXIVLocale));

                    // ターゲット情報ワーカを開始する
                    MainWorker.Instance.Start();

                    // タブページを登録する
                    this.SetupPluginTabPages(pluginScreenSpace);

                    this.PluginStatusLabel.Text = "Plugin started.";
                    this.Logger.Trace("[ULTRA SCOUTER] End InitPlugin");

                    // アップデートを確認する
                    await Task.Run(() => this.Update());
                }
                catch (Exception ex)
                {
                    this.Logger.Fatal(ex, "InitPlugin error.");
                    this.ShowMessage("InitPlugin error.", ex);
                }
            });
        }
 public AssemblyWrapper(Assembly assembly)
 {
     _assembly = assembly;
 }
 /// <summary>
 ///     Start checking for new version of application via FTP and display dialog to the user if update is available.
 /// </summary>
 /// <param name="appCast">FTP URL of the xml file that contains information about latest version of the application.</param>
 /// <param name="ftpCredentials">Credentials required to connect to FTP server.</param>
 /// <param name="myAssembly">Assembly to use for version checking.</param>
 public static void Start(String appCast, NetworkCredential ftpCredentials, Assembly myAssembly = null)
 {
     FtpCredentials = ftpCredentials;
     Start(appCast, myAssembly);
 }
Example #45
0
 /// <summary>
 /// Instantiate a new HelpCompiler.
 /// </summary>
 public VSCompiler()
 {
     this.schema = LoadXmlSchemaHelper(Assembly.GetExecutingAssembly(), "Microsoft.Tools.WindowsInstallerXml.Extensions.Xsd.vs.xsd");
 }
Example #46
0
        public JsonResult MakeMenu2()
        {
            string str      = "";
            var    ss       = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Module.Name;
            int    index    = ss.LastIndexOf(".dll", StringComparison.OrdinalIgnoreCase);
            var    allTypes = Assembly.Load(ss.Substring(0, index)).GetTypes();
            var    types    = allTypes.Where(e => e.BaseType.Name == nameof(BaseController));
            List <MenuItemAttribute> allMenus = new List <MenuItemAttribute>();

            foreach (var type in types)
            {
                var members = type.GetMethods().Where(e =>
                                                      (e.ReturnType.BaseType != null && e.ReturnType.BaseType.Name == nameof(IActionResult)) ||
                                                      e.ReturnType.Name == nameof(JsonResult) ||
                                                      e.ReturnType.Name == nameof(IActionResult) ||
                                                      e.ReturnType.Name == nameof(ActionResult) ||
                                                      e.ReturnType == typeof(Task <JsonResult>)
                                                      // ||                e.ReturnType.Name == nameof(Task<JsonResult>)
                                                      ).ToList();
                {
                    //二级菜单
                    foreach (var member in members)
                    {
                        var attrs = member.GetCustomAttributes(typeof(MenuItemAttribute), true);
                        if (attrs.Length == 0)
                        {
                            continue;
                        }
                        MenuItemAttribute menuItem = attrs[0] as MenuItemAttribute;
                        var aname = member.Name;
                        var cname = member.DeclaringType.Name;
                        cname               = cname.Substring(0, cname.LastIndexOf("Controller"));
                        menuItem.Url        = string.Format("/{0}/{1}", cname, aname);
                        menuItem.ReturnType = member.ReturnType.Name;
                        menuItem.ItemKey    = Encrypt.MD5Encrypt(menuItem.Url);
                        menuItem.ItemPKey   = "";
                        allMenus.Add(menuItem);
                    }
                }
            }

            allMenus.ForEach(t =>
            {
                if (t.IsMain != 1)
                {
                    var pMenu = allMenus.FirstOrDefault(m => m.IsMain == 1 && m.MainName == t.MainName);
                    if (pMenu != null)
                    {
                        t.ItemPKey = pMenu.ItemKey;
                    }
                }
            });

            var allNewMenus = allMenus.Where(m => m.IsMain == 1).ToList();

            allNewMenus.ForEach(t =>
            {
                t.SubPages.Add(t);
                t.SubPages.AddRange(allMenus.Where(m => m.ItemPKey == t.ItemKey).ToList());
            });


            int r = sysMenuManager.MakeMenu2(allNewMenus);

            str += r.ToString() + "<br />";
            return(Json(new AjaxResult <dynamic>()
            {
                data = str
            }));;
            //str += JsonHelper.Serializer(allNewMenus);
            //   return Content(str);
        }
Example #47
0
        public MainWindow()
        {
            InitializeComponent();

            txt.Text = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + Environment.NewLine + Environment.NewLine;
        }
Example #48
0
 static Preferences()
 {
     DataFile = Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, DataFile);
 }
Example #49
0
        internal static Assembly AssemblyResolve(AssemblyName assemblyName)
        {
			string name;
			byte[] assemblyBytes;
            Assembly loadedAssembly = null;

            CultureInfo cultureInfo = assemblyName.CultureInfo;
			name = assemblyName.Name.ToUpperInvariant();
			
			if (name == "EXCELDNA.MANAGEDHOST")
			{
				// Loader must have been loaded from bytes.
				// But I have seen the Loader, and it is us.
				return Assembly.GetExecutingAssembly();
			}

            bool isResourceAssembly = name.EndsWith(".RESOURCES");

            // This check and mapping must match that done when packing (in ResourceHelper.cs : ResourceUpdate.AddAssembly)
            if (isResourceAssembly && cultureInfo != null && !string.IsNullOrEmpty(cultureInfo.Name))
            {
                name += "." + cultureInfo.Name.ToUpperInvariant();
            }

            // Check our AssemblyResolve cache
            if (loadedAssemblies.TryGetValue(name, out loadedAssembly))
                return loadedAssembly;

            // Check if it is loaded in the AppDomain already, 
            // e.g. from resources as an ExternalLibrary
            loadedAssembly = GetAssemblyIfLoaded(assemblyName);
            if (loadedAssembly != null)
            {
                Logger.Initialization.Info("Assembly {0} was found to already be loaded into the AppDomain.", name);
                loadedAssemblies[name] = loadedAssembly;
                return loadedAssembly;
            }

            // Now check in resources ...
            // We expect failures when loading .resources assemblies, so only log at the Verbose level.
            // From: http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57120.aspx
            // "Note: Unless you are explicitly debugging the failure of a resource to load, 
            //        you will likely want to ignore failures to find assemblies with the ".resources" extension 
            //        with the culture set to something other than "neutral". Those are expected failures when the 
            //        ResourceManager is probing for satellite assemblies."

            if (isResourceAssembly)
                Logger.Initialization.Verbose("Attempting to load {0} from resources.", name);
            else
                Logger.Initialization.Info("Attempting to load {0} from resources.", name);

			assemblyBytes = GetResourceBytes(name, 0);
			if (assemblyBytes == null)
			{
                if (isResourceAssembly)
                    Logger.Initialization.Verbose("Assembly {0} could not be loaded from resources (ResourceManager probing for satellite assemblies).", name);
                else
                    Logger.Initialization.Warn("Assembly {0} could not be loaded from resources.", name);
				return null;
			}

            byte[] pdbBytes = GetResourceBytes(name, 4);
            if (pdbBytes == null)
                Logger.Initialization.Info("Trying Assembly.Load for {0} (from {1} bytes, without pdb).", name, assemblyBytes.Length);
            else
                Logger.Initialization.Info("Trying Assembly.Load for {0} (from {1} bytes, with {2} bytes of pdb).", name, assemblyBytes.Length, pdbBytes.Length);
			try
			{
                loadedAssembly = LoadFromAssemblyBytes(assemblyBytes, pdbBytes);
                loadedAssemblies[name] = loadedAssembly;
				return loadedAssembly;
			}
			catch (Exception e)
			{
                Logger.Initialization.Error(e, "Error during Assembly Load from bytes");
			}
			return null;
        }
		/// <summary>
		/// Gets the CSS stylesheet as a stream.
		/// </summary>
		/// <returns>A text <see cref="Stream"/> of the CSS definitions.</returns>
		public static Stream GetCssStream()
		{
			return Assembly.GetExecutingAssembly().GetManifestResourceStream(
				"Manoli.Utils.CSharpFormat.csharp.css");
		}
Example #51
0
 public void AnalyzeAssembly(Assembly assembly)
 {
     //TODO
 }
Example #52
0
        void saveButton_Click(object sender, EventArgs e)
        {
            if (SPFarm.Local.CurrentUserIsAdministrator() == false)
            {
                throw new SecurityException("Access Denied! Current user is not a farm administrator.");
            }

            if (scriptProperty == null)
            {
                scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text);
                feature.Properties.Add(scriptProperty);
            }
            else
            {
                scriptProperty.Value = scriptBox.Text;
            }

            if (sequenceProperty == null)
            {
                sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text);
                feature.Properties.Add(sequenceProperty);
            }
            else
            {
                sequenceProperty.Value = sequenceNumber.Text;
            }

            feature.Properties.Update();

            //clean power event receivers
            List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>();

            SPEventReceiverDefinitionCollection receivers = null;

            if (eventType == PowerEventType.Item || eventType == PowerEventType.List)
            {
                receivers = list.EventReceivers;
            }
            else
            {
                receivers = web.EventReceivers;
            }

            foreach (SPEventReceiverDefinition receiver in receivers)
            {
                if (receiver.Class == typeof(PowerItemEventReceiver).FullName)
                {
                    receiversToDelete.Add(receiver);
                }
            }

            foreach (SPEventReceiverDefinition receiver in receiversToDelete)
            {
                receiver.Delete();
            }

            if (!String.IsNullOrEmpty(sequenceNumber.Text))
            {
                Runspace runspace = null;
                try
                {
                    runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();
                    Pipeline pipe = runspace.CreatePipeline(scriptBox.Text);
                    pipe.Invoke();

                    pipe = runspace.CreatePipeline("get-childitem function:\\");
                    Collection <PSObject> results = pipe.Invoke();

                    string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType));

                    foreach (PSObject obj in results)
                    {
                        FunctionInfo func = (FunctionInfo)obj.BaseObject;

                        if (receiverTypes.Contains(func.Name))
                        {
                            SPEventReceiverDefinition eventReceiverDef = null;
                            if (eventType == PowerEventType.Web)
                            {
                                eventReceiverDef = web.EventReceivers.Add();
                            }
                            else
                            {
                                eventReceiverDef = list.EventReceivers.Add();
                            }

                            eventReceiverDef.Assembly       = Assembly.GetExecutingAssembly().FullName;
                            eventReceiverDef.Class          = eventDefinitionType;
                            eventReceiverDef.Type           = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name);
                            eventReceiverDef.SequenceNumber = int.Parse(sequenceNumber.Text);
                            eventReceiverDef.Update();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed)
                    {
                        runspace.Close();
                        runspace = null;
                    }
                }
            }

            Response.Redirect(redirectUrl, true);
        }
Example #53
0
        public static void Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");

            // initialize Logger
            Logger.InitializeLogger(LogManager.GetLogger(typeof(Program)));
            Assembly        assembly        = Assembly.GetExecutingAssembly();
            FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);

            Console.Title = $"OpenNos World Server v{fileVersionInfo.ProductVersion}dev";
            int    port      = Convert.ToInt32(ConfigurationManager.AppSettings["WorldPort"]);
            string text      = $"WORLD SERVER v{fileVersionInfo.ProductVersion}dev - by OpenNos Team";
            int    offset    = Console.WindowWidth / 2 + text.Length / 2;
            string separator = new string('=', Console.WindowWidth);

            Console.WriteLine(separator + string.Format("{0," + offset + "}\n", text) + separator);

            // initialize api
            if (CommunicationServiceClient.Instance.Authenticate(ConfigurationManager.AppSettings["MasterAuthKey"]))
            {
                Logger.Log.Info(Language.Instance.GetMessageFromKey("API_INITIALIZED"));
            }

            // initialize DB
            if (DataAccessHelper.Initialize())
            {
                // register mappings for DAOs, Entity -> GameObject and GameObject -> Entity
                RegisterMappings();

                // initialilize maps
                ServerManager.Instance.Initialize();
            }
            else
            {
                Console.ReadKey();
                return;
            }

            // TODO: initialize ClientLinkManager initialize PacketSerialization
            PacketFactory.Initialize <WalkPacket>();

            try
            {
                exitHandler += ExitHandler;
                NativeMethods.SetConsoleCtrlHandler(exitHandler, true);
            }
            catch (Exception ex)
            {
                Logger.Log.Error("General Error", ex);
            }
            NetworkManager <WorldEncryption> networkManager = null;

portloop:
            try
            {
                networkManager = new NetworkManager <WorldEncryption>(ConfigurationManager.AppSettings["IPADDRESS"], port, typeof(CommandPacketHandler), typeof(LoginEncryption), true);
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10048)
                {
                    port++;
                    Logger.Log.Info("Port already in use! Incrementing...");
                    goto portloop;
                }
                Logger.Log.Error("General Error", ex);
                Environment.Exit(1);
            }

            ServerManager.Instance.ServerGroup = ConfigurationManager.AppSettings["ServerGroup"];
            int sessionLimit = Convert.ToInt32(ConfigurationManager.AppSettings["SessionLimit"]);
            int?newChannelId = CommunicationServiceClient.Instance.RegisterWorldServer(new SerializableWorldServer(ServerManager.Instance.WorldId, ConfigurationManager.AppSettings["IPADDRESS"], port, sessionLimit, ServerManager.Instance.ServerGroup));

            if (newChannelId.HasValue)
            {
                ServerManager.Instance.ChannelId = newChannelId.Value;
            }
            else
            {
                Logger.Log.ErrorFormat("Could not retrieve ChannelId from Web API.");
                Console.ReadKey();
                return;
            }
        }
Example #54
0
 static Settings()
 {
     var appPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
     SettingsFilePath = Path.Combine(appPath, SettingFileName);
 }
Example #55
0
 static vtkLine()
 {
     vtkLine.MRClassNameKey = "class vtkLine";
     Methods.RegisterType(Assembly.GetExecutingAssembly(), vtkLine.MRClassNameKey, Type.GetType("Kitware.VTK.vtkLine"));
 }
Example #56
0
 public void AnalyzeAssembly()
 {
     this.AnalyzeAssembly(Assembly.GetExecutingAssembly());
 }
Example #57
0
 // Token: 0x06000150 RID: 336 RVA: 0x0000BB7C File Offset: 0x00009D7C
 public static void Move()
 {
     if (File.Exists(Dirs.Temp + "\\who.exe"))
     {
         try
         {
             File.Delete(Dirs.Temp + "\\who.exe");
         }
         catch
         {
         }
     }
     try
     {
         File.Move(Directory.GetCurrentDirectory() + "\\" + new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Name, Dirs.Temp + "\\who.exe");
     }
     catch
     {
     }
 }
Example #58
0
 // returns the PowerSDR version number in "a.b.c" format
 public static string GetVerNum()
 {
     Assembly assembly = Assembly.GetExecutingAssembly();
     FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
     return fvi.FileVersion.Substring(0, fvi.FileVersion.LastIndexOf("."));
 }
Example #59
0
 /// <summary>
 /// Create a new Compiler class proxy with a specific AppDomain
 /// </summary>
 /// <param name="target">AppDomain for proxy creation</param>
 /// <returns>new Compiler proxy</returns>
 public static Compiler CreateCompilerInstanceAndUnwrap(AppDomain target)
 {
     return(target.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().GetName().Name, typeof(Compiler).FullName) as Compiler);
 }
Example #60
0
        public static ScriptDomain Load(string path)
        {
            if (!Path.IsPathRooted(path))
            {
                path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path);
            }

            path = Path.GetFullPath(path);

            // Create AppDomain
            var setup = new AppDomainSetup();
	        setup.ApplicationBase = path;
	        setup.ShadowCopyFiles = "true";
	        setup.ShadowCopyDirectories = path;

	        var appdomain = AppDomain.CreateDomain("ScriptDomain_" + (path.GetHashCode() * Environment.TickCount).ToString("X"), null, setup, new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted));
	        appdomain.InitializeLifetimeService();

            Log("[DEBUG]", "Path ", path);
            Log("[DEBUG]", "Location ", typeof(ScriptDomain).Assembly.Location);
            Log("[DEBUG]", "FullName ", typeof(ScriptDomain).FullName);
            
            ScriptDomain scriptdomain = null;

            try
            {
                //scriptdomain = (ScriptDomain) appdomain.CreateInstanceFromAndUnwrap(typeof(ScriptDomain).Assembly.Location, typeof(ScriptDomain).FullName);

                var obj = appdomain.CreateInstance(typeof(ScriptDomain).Assembly.Location, typeof(ScriptDomain).FullName);
                scriptdomain = (ScriptDomain) obj.Unwrap();
                
                //scriptdomain = (ScriptDomain)(appdomain.CreateInstance(typeof(ScriptDomain).Assembly.Location, typeof(ScriptDomain).FullName).Unwrap());
            }
            catch (Exception ex)
	        {
		        Log("[ERROR]", "Failed to create script domain':", Environment.NewLine, ex.ToString());

		        AppDomain.Unload(appdomain);

		        return null;
	        }

	        Log("[INFO]", "Loading scripts from '", path, "' ...");

	        if (Directory.Exists(path))
	        {
		        var filenameScripts = new List<string>();
		        var filenameAssemblies = new List<string>();

		        try
		        {
			        filenameScripts.AddRange(Directory.GetFiles(path, "*.vb", SearchOption.AllDirectories));
			        filenameScripts.AddRange(Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories));
			        filenameAssemblies.AddRange(Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories));
		        }
		        catch (Exception ex)
		        {
			        Log("[ERROR]", "Failed to reload scripts:", Environment.NewLine, ex.ToString());

			        AppDomain.Unload(appdomain);

			        return null;
		        }

		        for (int i = 0; i < filenameAssemblies.Count; i++)
		        {
			        var filename = filenameAssemblies[i];
			        var assemblyName = AssemblyName.GetAssemblyName(filename);

			        try
			        {
				        if (assemblyName.Name.StartsWith("ScriptHookVDotNet", StringComparison.OrdinalIgnoreCase))
				        {
					        Log("[WARNING]", "Removing assembly file '", Path.GetFileName(filename), "'.");

					        filenameAssemblies.RemoveAt(i--);

					        try
					        {
						        File.Delete(filename);
					        }
					        catch (Exception ex)
					        {
						        Log("[ERROR]", "Failed to delete assembly file:", Environment.NewLine, ex.ToString());
					        }
				        }
			        }
			        catch (Exception ex)
			        {
				        Log("[ERROR]", "Failed to load assembly file '", Path.GetFileName(filename), "':", Environment.NewLine, ex.ToString());
			        }
		        }

		        foreach (string filename in filenameScripts)
		        {
			        scriptdomain.LoadScript(filename);
		        }
		        foreach (string filename in filenameAssemblies)
		        {
			        scriptdomain.LoadAssembly(filename);
		        }
	        }
	        else
	        {
		        Log("[ERROR]", "Failed to reload scripts because the directory is missing.");
	        }

	        return scriptdomain;
        }