public KeyCommandLauncherFactory( Utility.Assemblies.ManifestResources resources,
            System.Reflection.Assembly assembly, string prefix, CommandControlSet commandControlSet)
        {
            if( assembly == null )
            {
                throw new ArgumentNullException( "assembly" );
            }
            if( prefix == null )
            {
                throw new ArgumentNullException( "prefix" );
            }
            if( commandControlSet == null )
            {
                throw new ArgumentNullException( "commandControlSet" );
            }
            if( resources == null )
            {
                throw new ArgumentNullException( "resources" );
            }

            _resources = resources;
            _assembly = assembly;
            _prefix = prefix;
            _commandControlSet = commandControlSet;
        }
 /// <summary>
 /// The ctor
 /// </summary>
 /// <param name="myPluginAssembly">The pluginassembly which implements the incompatible version.</param>
 /// <param name="myCurrentVersion">The current plugin version.</param>
 /// <param name="myMinVersion">The minimum accepted version.</param>
 /// <param name="myMaxVersion">The maximum accepted version.</param>
 public Error_IncompatiblePluginVersion(System.Reflection.Assembly myPluginAssembly, Version myCurrentVersion, Version myMinVersion, Version myMaxVersion)
 {
     this.PluginAssembly = myPluginAssembly;
     this.CurrentVersion   = myCurrentVersion;
     this.MinVersion       = myMinVersion;
     this.MaxVersion       = myMaxVersion;
 }
示例#3
0
        public static void LoadAssembly(string file_name)
        {
        	//ad = AppDomain.CreateDomain("DebugDomain",null,Path.GetDirectoryName(file_name),Path.GetDirectoryName(file_name),false);
            try
            {
                FileStream fs = File.OpenRead(file_name);
                byte[] buf = new byte[fs.Length];
                fs.Read(buf, 0, (int)fs.Length);
                fs.Close();
                a = System.Reflection.Assembly.Load(buf);

                Type[] tt = a.GetTypes();
                foreach (Type t in tt)
                {
                    if (t.Namespace != null)
                        ns_ht[t.Namespace] = t.Namespace;
                    if (t.Namespace == t.Name)
                    {
                        unit_types.Add(t);
                    }
                    try
                    {
                        object[] attrs = t.GetCustomAttributes(false);
                        foreach (Attribute attr in attrs)
                        {
                            Type attr_t = attr.GetType();
                            if (attr_t.Name == "$UsedNsAttr")
                            {
                                int count = (int)attr_t.GetField("count").GetValue(attr);
                                string ns = attr_t.GetField("ns").GetValue(attr) as string;
                                int j = 0;
                                for (int i = 0; i < count; i++)
                                {
                                    byte str_len = (byte)ns[j];
                                    string ns_s = ns.Substring(j + 1, str_len);
                                    ns_ht[ns_s] = ns_s;
                                    j += str_len + 1;
                                }
                                break;
                            }
                        }
                    }
                    catch
                    {

                    }
                }
            }
            catch (System.Exception e)
            {

            }
//            if (a != null)
//           	{
//           		System.Reflection.AssemblyName[] refs = a.GetReferencedAssemblies();            	
//           		for (int i=0; i<refs.Length; i++)
//           			ref_modules.Add(System.Reflection.Assembly.Load(refs[i]));
//            }
            //a = ad.Load(buf);
        }
示例#4
0
        public MiniAssembly(System.Reflection.Assembly assembly)
        {
            System.Diagnostics.Contracts.Contract.Requires(assembly != null);

            _reflectionAssembly = assembly;
            _representation = Representation.ReflectionAssembly;
        }
 protected GladeWidgetExtract(Assembly assembly, string resource_name, string dialog_name)
     : this(dialog_name)
 {
     // we must do it from *here* otherwise, we get this assembly, not the caller
     glade = new XML (assembly, resource_name, dialog_name, null);
     Init ();
 }
示例#6
0
 public void Add(Assembly assembly)
 {
     if (!Contains(assembly))
     {
         InnerList.Add(assembly);
     }
 }
示例#7
0
		public MapControlSelector() {
			InitializeComponent();

			mAssembly = System.Reflection.Assembly.GetExecutingAssembly();
			listMobPoints.ListViewItemSorter = mListViewColumnSorter;

			Instances.Add( this );
		}
示例#8
0
 public AssemblyReference(System.Reflection.Assembly assembly)
 {
     if (null == assembly)
     {
         throw new System.ArgumentNullException("assembly");
     }
     _assembly = assembly;
 }
示例#9
0
 static SharpZipLib()
 {
     try
     {
         asm = System.Reflection.Assembly.Load("ICSharpCode.SharpZipLib");
     }
     catch{}
 }
示例#10
0
		/// <summary>
		/// Initializes a new instance of the <see cref="StringResources"/> class.
		/// </summary>
		/// <param name="path">The path to the resource. This is usually the default namespace, a dot, and the folders (separated by dots) where the resource file(s) reside. See remarks for how to name the neutral resource files and the resource files for other cultures.</param>
		/// <param name="resourceName">Name of the neutral (english) resource file (without the '.resource' extension.</param>
		/// <param name="assemblyContainingTheResources">The assembly containing the resources.</param>
		/// <remarks>
		/// The naming conventions will be explained using AltaxoCore as example.
		/// <para>The default namespace of the AltaxoCore DLL is 'Altaxo'.</para>
		/// <para>The resource files reside in the source folder 'Resources'.</para>
		/// <para>The neutral resource file is named 'StringResources.resources'.</para>
		/// <para>The resource file for the german culture must be named 'de.StringResources.resources' (two-letter_culture_name + dot + neutral_resource_file_name).</para>
		/// <para>This will lead to the following arguments for creating the instance:</para>
		/// <para>The <paramref name="path"/> argument is 'Altaxo.Resources' (default_namespace + dot + foldername).</para>
		/// <para>The <paramref name="resourceName"/> argument is 'StringResources'.</para>
		/// <para>The <paramref name="assemblyContainingTheResources"/> argument must refer to AltaxoCore.</para>
		/// </remarks>
		public StringResources(string path, string resourceName, System.Reflection.Assembly assemblyContainingTheResources)
		{
			_resourcePath = path;
			_resourceName = resourceName;
			_assemblyContainingTheResources = assemblyContainingTheResources;
			_defaultResourceMgr = new System.Resources.ResourceManager(path + "." + resourceName, assemblyContainingTheResources);
			_resourceManagersByLanguage = new Dictionary<string, System.Resources.ResourceManager>();
			_resourceManagersByLanguage.Add("en", _defaultResourceMgr);
		}
示例#11
0
 public PreviewModel(IComparisonDocument document)
 {
     ComparisonDocument = document;
     FileName = ComparisonDocument.FileName;
     asm = System.Reflection.Assembly.LoadFrom("Workshare.Utilities.dll");
     _lcfm = Activator.CreateInstance(asm.GetType("Workshare.Utilities.LocalCopyOfFileManager"));
     PreviewImages = new List<Bitmap>();
     LoadModel();
 }
        public EmbeddedResourceTemplateLoader(Assembly assembly, string namespaceRoot, bool raiseExceptionForEmptyTemplate)
            : base(namespaceRoot, raiseExceptionForEmptyTemplate)
        {
            if (assembly == null)
                throw new ArgumentNullException("assembly", "An assembly must be specified");

            if (namespaceRoot == null)
                throw new ArgumentNullException("namespaceRoot", "A namespace must be specified");
            this.assembly = assembly;
        }
示例#13
0
 public KeyDataXml()
 {
     _currentassembly = System.Reflection.Assembly.GetExecutingAssembly();
  
     // Initialise our navigator from the embedded XML keys file.
     using (Stream xmlstream = GetXMLDocumentAsStream(_keyfilename))
     {
         XPathDocument document = new XPathDocument(xmlstream);
         _navigator = document.CreateNavigator();
     }
 }
示例#14
0
        public bool Contains(Assembly assembly)
        {
            AssertNotNull(assembly);

            foreach (Assembly existing in InnerList)
            {
                if (AssemblyEqualityComparer.Default.Equals(existing, assembly))
                {
                    return true;
                }
            }
            return false;
        }
示例#15
0
        public ManifestResources( string baseNamespace, System.Reflection.Assembly assembly )
        {
            if( baseNamespace == null )
            {
                throw new ArgumentNullException( "baseNamespace" );
            }
            if( assembly == null )
            {
                throw new ArgumentNullException( "assembly" );
            }

            _baseNamespace = baseNamespace;
            _assembly = assembly;
        }
        /// <summary>
        /// Construct an instance that loads groups/interfaces from the single dir or 
        /// multiple dirs specified and uses the specified encoding.
        /// </summary>
        /// <remarks>
        /// If a specified directory is an absolute path, the full path is used to 
        /// locate the template group or interface file.
        /// 
        /// If a specified directory is a relative path, the path is taken to be
        /// relative to the location of the stringtemplate assembly itself.
        /// 
        /// TODO: Check shadow-copying doesn't knock this outta whack.
        /// </remarks>
        public EmbeddedResourceGroupLoader(
            IStringTemplateGroupFactory factory,
            IStringTemplateErrorListener errorListener,
            Assembly assembly,
            string namespaceRoot)
        {
            if (assembly == null)
                throw new ArgumentNullException("assembly", "An assembly must be specified");

            if (namespaceRoot == null)
                throw new ArgumentNullException("namespaceRoot", "A namespace must be specified");

            this.factory = (factory == null) ? new DefaultGroupFactory() : factory;
            this.errorListener = (errorListener == null) ? NullErrorListener.DefaultNullListener : errorListener;
            this.assembly = assembly;
            this.namespaceRoot = namespaceRoot;
        }
        private void btnOpen_Click(object sender, EventArgs e)
        {
            //attempt to load the assembly using the path from the text box
            try
            {
                LoadedAssemblyFile.loadedAssemblyFile = txtFileName.Text;
                LoadedAssembly = System.Reflection.Assembly.LoadFrom(LoadedAssemblyFile.loadedAssemblyFile);
                frmTreeAndTestCases TreeAndTestCases = new frmTreeAndTestCases();
                TreeAndTestCases.buildTreeFromAssembly(LoadedAssembly);
                TreeAndTestCases.ShowDialog(this);
                //this.Close();

            }
            catch(System.IO.IOException)
            {
                lblErrors.Text = "Error loading file.  Please check that the file exists and is a valid assembly.";
            }
        }
示例#18
0
 private void OpenFile(object sender, EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
       if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
       {
     string path = ofd.FileName;
     var asm = System.Reflection.Assembly.LoadFrom(path);
     string[] resources = asm.GetManifestResourceNames();
     m_assembly = asm;
     m_combo_resource_names.Items.Clear();
     List<string> items = new List<string>();
     foreach (string resource in resources)
     {
       if( resource.EndsWith(".xml",StringComparison.InvariantCultureIgnoreCase) )
     items.Add(resource);
     }
     m_combo_resource_names.Items.AddRange(items.ToArray());
       }
 }
示例#19
0
        void Awake()
        {
            GameCore.Debug.DebugHandler += Debug_DebugHandler;
            GameCore.DesignerDataLoader.GetDataStreamHandler += DesignerDataLoader_GetDataStreamHandler;

            if (string.IsNullOrEmpty(AssemblyPath))
            {
                UnityEngine.Debug.LogError(string.Format(Properties.Resources.NotAssignAssembly, nameof(DesignerDataLoader)));
                return;
            }
            try
            {
                assembly = System.Reflection.Assembly.LoadFrom(Utility.GetAbsolutePath(Environment.CurrentDirectory.AppendBackslashIfNotEndWith(), AssemblyPath));
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError(string.Format(Properties.Resources.ParseAssemblyException, nameof(DesignerDataLoader), e));
            }
        }
        public CommandMenuStripFactory( Utility.Assemblies.ManifestResources resources,
            System.Reflection.Assembly assembly, string prefix, CommandControlSet commandControlSet)
            : base(resources)
        {
            if( assembly == null )
            {
                throw new ArgumentNullException( "assembly" );
            }
            if( prefix == null )
            {
                throw new ArgumentNullException( "prefix" );
            }
            if( commandControlSet == null )
            {
                throw new ArgumentNullException( "commandControlSet" );
            }

            _assembly = assembly;
            _prefix = prefix;
            _commandControlSet = commandControlSet;
        }
示例#21
0
文件: Main.cs 项目: Rrego6/Pass4Win
        /// <summary>
        /// Inits the repo, gpg etc
        /// </summary>
        public frmMain()
        {
            InitializeComponent();

            var bugsnag = new BaseClient("23814316a6ecfe8ff344b6a467f07171");

            EnableTray = false;

            // Getting actual version
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            cfg["version"] = version.Remove(5, 2);

            this.Text = "Pass4Win " + Strings.Version + " " + cfg["version"];

            // checking for update this an async operation
            LatestPass4WinRelease();

            // Do we have a valid password store and settings
            try
            {
                if (cfg["PassDirectory"] == "")
                {
                    // this will fail, I know ugly hack
                }
            }
            catch
            {
                cfg["FirstRun"] = true;
                frmConfig Config       = new frmConfig();
                var       dialogResult = Config.ShowDialog();
            }
            //checking git status
            if (!LibGit2Sharp.Repository.IsValid(cfg["PassDirectory"]))
            {
                // Remote or generate a new one
                if (cfg["UseGitRemote"] == true)
                {
                    // check if server is alive
                    if (IsGITAlive(cfg["UseGitRemote"]) || IsHTTPSAlive(cfg["UseGitRemote"]))
                    {
                        // clone the repo and catch any error
                        try
                        {
                            string clonedRepoPath = LibGit2Sharp.Repository.Clone(cfg["GitRemote"], cfg["PassDirectory"], new CloneOptions()
                            {
                                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                                {
                                    Username = cfg["GitUser"],
                                    Password = DecryptConfig(cfg["GitPass"], "pass4win")
                                }
                            });
                        }
                        catch
                        {
                            MessageBox.Show(Strings.Error_connection, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            toolStripOffline.Visible = true;
                        }
                    }
                    else
                    {
                        MessageBox.Show(Strings.Error_git_unreachable, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        toolStripOffline.Visible = true;
                    }
                }
                else
                {
                    // creating new Git
                    var repo = LibGit2Sharp.Repository.Init(cfg["PassDirectory"], false);
                    toolStripOffline.Visible = true;
                }
            }
            else
            {
                // Do we do remote or not
                CheckOnline(true);
            }

            // Making sure core.autocrlf = true
            using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"]))
            {
                repo.Config.Set("core.autocrlf", true);
            }

            // Init GPG if needed
            string gpgfile = cfg["PassDirectory"];

            gpgfile += "\\.gpg-id";
            // Check if we need to init the directory
            if (!File.Exists(gpgfile))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(gpgfile));
                KeySelect newKeySelect = new KeySelect();
                if (newKeySelect.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter w = new StreamWriter(gpgfile))
                    {
                        w.Write(newKeySelect.gpgkey);
                    }
                    using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"]))
                    {
                        repo.Stage(gpgfile);
                        repo.Commit("gpgid added", new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now));
                    }
                }
                else
                {
                    newKeySelect.Close();
                    MessageBox.Show(Strings.Error_nokey, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Environment.Exit(1);
                }
            }
            // Setting the exe location for the GPG Dll
            GpgInterface.ExePath = cfg["GPGEXE"];

            // Setting up datagrid
            dt.Columns.Add("colPath", typeof(string));
            dt.Columns.Add("colText", typeof(string));

            treeDt.Columns.Add("colPath", typeof(string));
            treeDt.Columns.Add("colText", typeof(string));

            ListDirectory(new DirectoryInfo(cfg["PassDirectory"]), "");
            fillDirectoryTree(dirTreeView, cfg["PassDirectory"]);

            dataPass.DataSource         = dt.DefaultView;
            dataPass.Columns[0].Visible = false;

            EnableTray = true;
        }
示例#22
0
        public void ShowSubForm(object sender, EventArgs e)
        {
            string    AFormName = Microsoft.VisualBasic.Strings.Left(sender.ToString(), 5).Trim();
            MdPubFunc funcs     = new MdPubFunc();

            System.Reflection.Assembly tempAssembly = System.Reflection.Assembly.GetExecutingAssembly();
            string str = tempAssembly.GetName().Name + "." + AFormName;

            Form frm;

            try
            {
                frm = (Form)tempAssembly.CreateInstance(str);
            }
            catch (Exception)
            {
                throw;
            }


            switch (AFormName)
            {
            case "DCM01":
                if (funcs.CheckAuth(AFormName, name) != null)
                {
                    FoodOrder_Frm DCM01_form = new FoodOrder_Frm();
                    DCM01_form.MdiParent   = this;
                    DCM01_form.WindowState = FormWindowState.Maximized;
                    DCM01_form.Show();


                    //            obVal = FindObject(frm, "Panelsys")
                    //If Not obVal Is Nothing Then
                    //    obVal.Parent = SysPage.SelectedTab  '本程序顯示在主窗体的mainpage中 2008-10-01 (Panelsys是在最上面Fill)hyt
                    //    iCurIndex = SysPage.SelectedIndex
                    //    LangDeal(AFormName, SysPage.TabPages.Item(iCurIndex))
                    //End If
                }
                else
                {
                    MessageBox.Show("Bạn không có quyền đề vào chương trình !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                break;

            case "USR01":
                if (funcs.CheckAuth(AFormName, name) != null)
                {
                    QuanliUser ql_form = new QuanliUser(name);
                    ql_form.MdiParent   = this;
                    ql_form.WindowState = FormWindowState.Maximized;
                    ql_form.Show();
                }
                else
                {
                    MessageBox.Show("Bạn không có quyền đề vào chương trình !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                break;

            case "USR03":
                if (funcs.CheckAuth(AFormName, name) != null)
                {
                    RegisterFrm re = new RegisterFrm();
                    // re.MdiParent = this;
                    // re.WindowState = FormWindowState.Maximized;
                    re.Show();
                }
                else
                {
                    MessageBox.Show("Bạn không có quyền đề vào chương trình !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                break;

            case "FGP01":
                if (funcs.CheckAuth(AFormName, name) != null)
                {
                    FingerPrint.FingerPrint fg = new FingerPrint.FingerPrint();
                    fg.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Bạn không có quyền đề vào chương trình !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                break;

            case "About":
                About about = new About();
                about.Show();
                break;

            default:
                MessageBox.Show("Chưa định nghĩa chương trình !!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            }
        }
示例#23
0
        /// <summary>
        /// Attempts to load opencv modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of opencv modules. e.g. "opencv_cxcore.dll" on windows.</param>
        /// <returns>True if all the modules has been loaded successfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if NETFX_CORE
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }

            String subfolder = String.Empty;
            if (Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows) //|| Platform.OperationSystem == Emgu.Util.TypeEnum.OS.WindowsPhone)
            {
                if (IntPtr.Size == 8)
                { //64bit process
#if UNITY_METRO
                    subfolder = "x86_64";
#else
                    subfolder = String.Empty;
#endif
                }
                else
                {
                    subfolder = String.Empty;
                }
            }

            Windows.Storage.StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

#if UNITY_METRO
            loadDirectory = Path.Combine(
                Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(installFolder.Path))))
                , "Plugins", "Metro", subfolder);
#else
            loadDirectory = Path.Combine(installFolder.Path, subfolder);
#endif

            var t = System.Threading.Tasks.Task.Run(async() =>
            {
                List <string> files = new List <string>();
                Windows.Storage.StorageFolder loadFolder = installFolder;
                try
                {
                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        loadFolder = await installFolder.GetFolderAsync(subfolder);
                    }

                    foreach (var file in await loadFolder.GetFilesAsync())
                    {
                        files.Add(file.Name);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Unable to retrieve files in folder '{0}':{1}", loadFolder.Path, e.StackTrace));
                }

                return(files);
            });
            t.Wait();

            List <String> loadableFiles = t.Result;
#else
            if (loadDirectory == null)
            {
                String subfolder = String.Empty;
#if UNITY_EDITOR_WIN
                subfolder = IntPtr.Size == 8 ? "x86_64" : "x86";
#elif UNITY_STANDALONE_WIN
#else
                if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows)
                {
                    subfolder = IntPtr.Size == 8 ? "x64" : "x86";
                }
#endif

                /*
                 * else if (Platform.OperationSystem == Emgu.Util.TypeEnum.OS.MacOS)
                 * {
                 * subfolder = "..";
                 * }*/
#if NETSTANDARD1_4
                loadDirectory = new DirectoryInfo(".").FullName;
#else
                System.Reflection.Assembly asm = typeof(CvInvoke).Assembly; //System.Reflection.Assembly.GetExecutingAssembly();
                if ((String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)))
                {
                    if (String.IsNullOrEmpty(AppDomain.CurrentDomain.BaseDirectory))
                    {
                        loadDirectory = String.Empty;
                    }
                    else
                    {
                        //we may be running in a debugger visualizer under a unit test in this case
                        String        visualStudioDir       = AppDomain.CurrentDomain.BaseDirectory;
                        DirectoryInfo visualStudioDirInfo   = new DirectoryInfo(visualStudioDir);
                        String        debuggerVisualzerPath =
                            Path.Combine(Path.Combine(Path.Combine(
                                                          visualStudioDirInfo.Parent.FullName, "Packages"), "Debugger"), "Visualizers");

                        if (Directory.Exists(debuggerVisualzerPath))
                        {
                            loadDirectory = debuggerVisualzerPath;
                        }
                        else
                        {
                            loadDirectory = String.Empty;
                        }

                        /*
                         *             loadDirectory = Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path);
                         *
                         *             DirectoryInfo dir = new DirectoryInfo(loadDirectory);
                         *             string subdir = String.Join(";", Array.ConvertAll(dir.GetDirectories(), d => d.ToString()));
                         *
                         *             throw new Exception(String.Format(
                         *                "The Emgu.CV.dll assembly path (typeof (CvInvoke).Assembly.Location) '{0}' is invalid." +
                         *                Environment.NewLine
                         + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().Location): '{1}';" +
                         +                Environment.NewLine
                         + " Other possible path (Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path): '{2}';" +
                         +                Environment.NewLine
                         + " Other possible path (System.Reflection.Assembly.GetExecutingAssembly().CodeBase): '{3};'" +
                         +                Environment.NewLine
                         + " Other possible path (typeof(CvInvoke).Assembly.CodeBase): '{4}'" +
                         +                Environment.NewLine
                         + " Other possible path (AppDomain.CurrentDomain.BaseDirectory): '{5}'" +
                         +                Environment.NewLine
                         + " subfolder name: '{6}'",
                         +                asm.Location,
                         +                Path.GetDirectoryName(new UriBuilder(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Path),
                         +                loadDirectory + ": subdir '" + subdir +"'",
                         +                System.Reflection.Assembly.GetExecutingAssembly().CodeBase,
                         +                typeof(CvInvoke).Assembly.Location,
                         +                AppDomain.CurrentDomain.BaseDirectory,
                         +                subfolder
                         +                ));
                         */
                    }
                }
                else
                {
                    loadDirectory = Path.GetDirectoryName(asm.Location);
                }

                /*
                 * FileInfo file = new FileInfo(asm.Location);
                 * //FileInfo file = new FileInfo(asm.CodeBase);
                 * DirectoryInfo directory = file.Directory;
                 * loadDirectory = directory.FullName;
                 */
#endif
                if (!String.IsNullOrEmpty(subfolder))
                {
                    var temp = Path.Combine(loadDirectory, subfolder);
                    if (Directory.Exists(temp))
                    {
                        loadDirectory = temp;
                    }
                    else
                    {
                        loadDirectory = Path.Combine(Path.GetFullPath("."), subfolder);
                    }
                }

#if (UNITY_STANDALONE_WIN && !UNITY_EDITOR_WIN)
                if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                {
                    Debug.WriteLine(String.Format("UNITY_STANDALONE_WIN: asm.Location is invalid: '{0}'", asm.Location));
                    return(false);
                }


                FileInfo      file      = new FileInfo(asm.Location);
                DirectoryInfo directory = file.Directory;
                if (directory.Parent != null)
                {
                    String unityAltFolder = Path.Combine(directory.Parent.FullName, "Plugins");

                    if (Directory.Exists(unityAltFolder))
                    {
                        loadDirectory = unityAltFolder;
                    }
                    else
                    {
                        Debug.WriteLine("No suitable directory found to load unmanaged modules");
                        return(false);
                    }
                }
#elif __ANDROID__ || UNITY_ANDROID || NETSTANDARD1_4
#else
                if (!Directory.Exists(loadDirectory))
                {
                    //try to find an alternative loadDirectory path
                    //The following code should handle finding the asp.NET BIN folder
                    String altLoadDirectory = Path.GetDirectoryName(asm.CodeBase);
                    if (!String.IsNullOrEmpty(altLoadDirectory) && altLoadDirectory.StartsWith(@"file:\"))
                    {
                        altLoadDirectory = altLoadDirectory.Substring(6);
                    }

                    if (!String.IsNullOrEmpty(subfolder))
                    {
                        altLoadDirectory = Path.Combine(altLoadDirectory, subfolder);
                    }

                    if (!Directory.Exists(altLoadDirectory))
                    {
                        if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                        {
                            Debug.WriteLine(String.Format("asm.Location is invalid: '{0}'", asm.Location));
                            return(false);
                        }
                        FileInfo      file      = new FileInfo(asm.Location);
                        DirectoryInfo directory = file.Directory;
#if UNITY_EDITOR_WIN
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(
                                    Path.Combine(Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Emgu.CV"), "Plugins"),
                                    subfolder);

                            Debug.WriteLine("Trying unityAltFolder: " + unityAltFolder);
                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                Debug.WriteLine("No suitable directory found to load unmanaged modules");
                                return(false);
                            }
                        }
                        else
#elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
                        if (directory.Parent != null && directory.Parent.Parent != null)
                        {
                            String unityAltFolder =
                                Path.Combine(Path.Combine(Path.Combine(
                                                              Path.Combine(Path.Combine(directory.Parent.Parent.FullName, "Assets"), "Plugins"),
                                                              "emgucv.bundle"), "Contents"), "MacOS");

                            if (Directory.Exists(unityAltFolder))
                            {
                                loadDirectory = unityAltFolder;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
#endif
                        {
                            Debug.WriteLine("No suitable directory found to load unmanaged modules");
                            return(false);
                        }
                    }
                    else
                    {
                        loadDirectory = altLoadDirectory;
                    }
                }
#endif
            }
#if !(NETSTANDARD1_4)
            String oldDir = Environment.CurrentDirectory;
            if (!String.IsNullOrEmpty(loadDirectory) && Directory.Exists(loadDirectory))
            {
                Environment.CurrentDirectory = loadDirectory;
            }
#endif
#endif

            System.Diagnostics.Debug.WriteLine(String.Format("Loading open cv binary from {0}", loadDirectory));
            bool success = true;

            string prefix = string.Empty;

            foreach (String module in unmanagedModules)
            {
                string mName = module;

                //handle special case for universal build
                if (
                    mName.StartsWith("opencv_videoio_ffmpeg") && //opencv_ffmpegvvv(_64).dll
                    (IntPtr.Size == 4)   //32bit application
                    )
                {
                    mName = module.Replace("_64", String.Empty);
                }

                String fullPath = Path.Combine(prefix, mName);

#if NETFX_CORE
                if (loadableFiles.Exists(sf => sf.Equals(fullPath)))
                {
                    IntPtr handle = Toolbox.LoadLibrary(fullPath);
                    success &= (!IntPtr.Zero.Equals(handle));
                }
                else
                {
                    success = false;
                }
#else
                //Use absolute path for Windows Desktop
                fullPath = Path.Combine(loadDirectory, fullPath);

                bool fileExist = File.Exists(fullPath);
                if (!fileExist)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} do not exist.", fullPath));
                }
                bool fileExistAndLoaded = fileExist && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                if (fileExist && (!fileExistAndLoaded))
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("File {0} cannot be loaded.", fullPath));
                }
                success &= fileExistAndLoaded;
#endif
            }

#if !(NETFX_CORE || NETSTANDARD1_4)
            Environment.CurrentDirectory = oldDir;
#endif
            return(success);
        }
        private void Metodo_VariablesStatic()
        {
            Ensamblado = System.Reflection.Assembly.GetExecutingAssembly();
            try
            {
                appPath = Application.ExecutablePath;

                var usuariosBL = new usuariosBL();
                var COD_USU = Convert.ToString(VariablesPublicas.Usuar);
                dtMenuItems = usuariosBL.GenerarMenuXperfil(VariablesPublicas.EmpresaID, COD_USU, perfil).Tables[0];

                mainMenu.Items.Clear();
                appPath = appPath.Substring(0, 28) + "Iconos\\";

                for (var nMain = 0; nMain < dtMenuItems.Rows.Count; nMain++)
                {
                    if (dtMenuItems.Rows[nMain]["menid"].Equals(dtMenuItems.Rows[nMain]["padid"]))
                    {
                        var tsmMain = new ToolStripMenuItem(dtMenuItems.Rows[nMain]["descr"].ToString());
                        if (dtMenuItems.Rows[nMain]["icono"].ToString().Trim().Length > 0)
                        {
                            tsmMain.Image = Bitmap.FromFile(appPath + dtMenuItems.Rows[nMain]["icono"].ToString().Trim());
                        }
                        mainMenu.Items.Add(tsmMain);
                        AddSubMenu(dtMenuItems.Rows[nMain]["menid"].ToString(), tsmMain);
                    }
                }
                Controls.Add(mainMenu);
            }
            catch
            {
            }
        }
        private void Metodo_VariablesStatic()
        {
            Ensamblado = System.Reflection.Assembly.GetExecutingAssembly();
            try
            {
                appPath = Application.ExecutablePath;

                //perfil items Usuario
                usuariosBL usuariosBL = new usuariosBL();
                tb_usuarios tb_usuarios = new tb_usuarios();
                string COD_USU = Convert.ToString(VariablesPublicas.Usuar);
                dtMenuItems = usuariosBL.GenerarMenuXperfil(VariablesPublicas.EmpresaID, COD_USU, _perfil).Tables[0];

                mainMenu.Items.Clear();
                appPath = appPath.Substring(0, 28) + "Iconos\\";

                /*************************************************************************/
                //MenuStrip menu = new MenuStrip();
                for (int nMain = 0; nMain < dtMenuItems.Rows.Count; nMain++)
                {
                    if (dtMenuItems.Rows[nMain]["menid"].Equals(dtMenuItems.Rows[nMain]["padid"]))
                    {
                        ToolStripMenuItem tsmMain = new ToolStripMenuItem(dtMenuItems.Rows[nMain]["descr"].ToString());
                        //tsmMain.DisplayStyle = ToolStripItemDisplayStyle.Text;
                        if (dtMenuItems.Rows[nMain]["icono"].ToString().Trim().Length > 0)
                        {
                            tsmMain.Image = Bitmap.FromFile(appPath + dtMenuItems.Rows[nMain]["icono"].ToString().Trim());
                        }
                        mainMenu.Items.Add(tsmMain);
                        AddSubMenu(dtMenuItems.Rows[nMain]["menid"].ToString(), tsmMain);
                    }
                }
                this.Controls.Add(mainMenu);
            }
            catch
            {
                //Response.Redirect("~/Login02.aspx");
            }
        }
示例#26
0
        /// <summary>
        /// This constructor is used for launching as a CXP capability.
        /// </summary>
        public ViewerForm()
        {
            Application.EnableVisualStyles();
            //Application.DoEvents();  //Note: this seems to cause problems in the CXP Capability context.

#if DEBUG && LOGGING
            LoggingService logger = new LoggingService();
#endif
            PresenterModel model = new PresenterModel();
            m_Loader = new DefaultDeckMarshalService();

            this.SuspendLayout();
            this.m_EventQueue = new ControlEventQueue(this);

            this.m_Model   = model;
            this.m_Marshal = m_Loader;

            UpdateTitle();

            this.Name = "ViewerForm";

            //Retrieve the icon
            System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            this.Icon = new Icon(thisExe.GetManifestResourceStream("UW.ClassroomPresenter.Presenter.ico"));

            this.StartPosition = FormStartPosition.Manual;
            this.loadRegSettings();
            this.MinimumSize = new Size(440, 330);

            Menus.FileMenu.CloseFormDelegate cfd = new UW.ClassroomPresenter.Viewer.Menus.FileMenu.CloseFormDelegate(this.Close);
            this.Menu = new Menus.ViewerMainMenu(this.m_EventQueue, this.m_Model, m_Loader, cfd);


            this.m_MainToolBars       = new MainToolBars(this.m_Model, this.m_EventQueue);
            this.m_PresentationLayout = new ViewerPresentationLayout(this.m_Model);
            //this.m_MainToolBar.Dock = DockStyle.Top;
            this.m_PresentationLayout.Dock = DockStyle.Fill;

            this.Controls.Add(this.m_PresentationLayout);

            // Hack: toggle the second monitor to make it scale correctly when using Surface Pro 3.
            // Bounds need to be set after the ViewerPresentationLayout control is added,
            // Otherwise DPI scaling appears to be done incorrectly.  This issue so far
            // appears to be unique to the Surface Pro 3.
            using (Synchronizer.Lock(model.ViewerState.SyncRoot)) {
                if (model.ViewerState.SecondMonitorEnabled)
                {
                    model.ViewerState.SecondMonitorEnabled = false;
                    model.ViewerState.SecondMonitorEnabled = true;
                }
            }

            this.Controls.Add(this.m_MainToolBars.m_MainToolBar);
            this.Controls.Add(this.m_MainToolBars.m_MainClassmateToolBar);
            this.Controls.Add(this.m_MainToolBars.m_ExtraClassmateToolBar);

            this.ResumeLayout(false);

            this.KeyDown   += new KeyEventHandler(this.OnKeyDown);
            this.KeyPreview = true;

            ///add listeners for HumanName, Role, Stylus properties
            role_listener_       = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.ParticipantRoleChanged));
            stylus_listener_     = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.StylusChanged));
            instructor_listener_ = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.InstructorChanged));

            this.m_Model.Participant.Changed["Role"].Add(role_listener_.Dispatcher);
            this.m_Model.Changed["Stylus"].Add(stylus_listener_.Dispatcher);
            this.m_Model.Network.Changed["Association"].Add(instructor_listener_.Dispatcher);

            //Add listener for the version exchange warning pop-up
            this.m_VersionExchangePopUpListener = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.PopUpWarningHandler));
            this.m_Model.VersionExchange.Changed["PopUpWarningMessage"].Add(m_VersionExchangePopUpListener.Dispatcher);

            //Add listener for NetworkStatus
            m_NetworkStatusListener = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.NetworkStatusChanged));
            this.m_Model.Network.Changed["NetworkStatus"].Add(m_NetworkStatusListener.Dispatcher);

            this.m_FullScreenAdapter = new FullScreenAdapter(this.m_Model, this.m_PresentationLayout);

            instructor_listener_.Dispatcher(this, null);
            role_listener_.Dispatcher(this, null);
            stylus_listener_.Dispatcher(this, null);

            this.FormClosing += this.SaveClose;

            //Store local DPI settings which are used to make sure ink is scaled correctly.
            using (Graphics g = this.CreateGraphics()) {
                ViewerStateModel.SetLocalDpi(g.DpiX, g.DpiY);
            }

            m_ViewerState = new ViewerStateService(model.ViewerState);
            m_Registry    = new RegistryService(model.ViewerState);
#if DEBUG && LOGGING
            logger.AttachToModel(model.ViewerState);
#endif
            PrintingService printing = new PrintingService(model.ViewerState);
            m_Undo = new WorkspaceUndoService(this.m_EventQueue, model);

            m_Association = new NetworkAssociationService(this.m_EventQueue, model);
            m_DeckMatcher = new DeckMatcherService(this.m_EventQueue, model);
        }
示例#27
0
 public static Type[] GetTypesOfAssembly(System.Reflection.Assembly assembly)
 {
     throw new NotImplementedException();
 }
示例#28
0
        static void Identify(TextWriter oport, string prefix)
        {
            appName = AppDomain.CurrentDomain.FriendlyName;
            // You may conduct internal benchmark testing of the .NET Framework
            // component of the OS Components (".NET Component").  You may disclose
            // the results of any benchmark test of the .NET Component, provided
            // that you comply with the following terms:
            // (1) you must disclose all the information necessary for replication
            // of the tests, including complete and accurate details of your benchmark
            // testing methodology, the test scripts/cases, tuning parameters applied,
            // hardware and software platforms tested, the name and version number of
            // any third-party testing tool used to conduct the testing, and complete
            // source code for the benchmark suite/harness that is developed by or for
            // you and used to test both the .NET Component and the competing
            // implementation(s);


            foreach (ManagementObject mo in new ManagementObjectSearcher(new SelectQuery("Win32_ComputerSystemProduct")).Get())
            {
                oport.WriteLine("{0}{1} {2}", prefix,
                                mo.GetPropertyValue("Vendor").ToString(),
                                mo.GetPropertyValue("Version").ToString());
            }
            oport.WriteLine("{0}{1} processor{2}", prefix, System.Environment.ProcessorCount, System.Environment.ProcessorCount == 1 ? "" : "s");
            foreach (ManagementObject proc in new ManagementObjectSearcher(new SelectQuery("Win32_Processor")).Get())
            {
                oport.WriteLine("{0}    {1}", prefix, proc.GetPropertyValue("Manufacturer").ToString());
                oport.WriteLine("{0}    {1}", prefix, proc.GetPropertyValue("Name").ToString());
                oport.WriteLine("{0}    {1}", prefix, proc.GetPropertyValue("Description").ToString());
                oport.WriteLine("{0}    {1} MHz", prefix, proc.GetPropertyValue("CurrentClockSpeed").ToString());
            }
            oport.WriteLine("{0}Working set:  {1}", prefix, System.Environment.WorkingSet);
            oport.WriteLine("{0}Overflow checking is {1}abled.", prefix, (CheckOverflowChecking() ? "en" : "dis"));
#if DEBUG
            oport.WriteLine("{0}Compiled in DEBUG mode.", prefix);
#else
            oport.WriteLine("{0}Compiled in RELEASE mode.", prefix);
#endif
            //Debug.Listeners.Add (new TextWriterTraceListener (Console.Out));
            //Debug.WriteLine ("DEBUG build");
            oport.WriteLine("{0}Debugger is {1}attached.", prefix, Debugger.IsAttached ? "" : "not ");
            oport.WriteLine("{0}Stopwatch is {1}high resolution.  {2} ticks per second.", prefix, Stopwatch.IsHighResolution ? "" : "NOT", Stopwatch.Frequency);
            oport.WriteLine("{0}", prefix);

            // (2) you must disclose the date(s) that you conducted the benchmark tests,
            // along with specific version information for all Microsoft software products
            // tested, including the .NET Component;

            oport.WriteLine("{0}{1}", prefix, DateTime.Now.ToUniversalTime());
            oport.WriteLine("{0}{1}", prefix, System.Environment.OSVersion.ToString());
            oport.WriteLine("{0}CLR {1}", prefix, System.Environment.Version);
            oport.WriteLine("{0}", prefix);
            // (4) it shall be sufficient if you make the disclosures provided for above
            // at a publicly available location such as a Web site, so long as every public
            // disclosure of the results of your benchmark test expressly identifies the
            // public site containing all required disclosures;
            oport.WriteLine("{0}See http://eval.apply.googlepages.com/ for further information.", prefix);
            oport.WriteLine("{0}", prefix);

            oport.WriteLine("{0}{1}", prefix, System.Reflection.Assembly.GetExecutingAssembly());
            System.Reflection.Assembly me = System.Reflection.Assembly.GetExecutingAssembly();
            foreach (DebuggableAttribute debuggable in me.GetCustomAttributes(typeof(DebuggableAttribute), false))
            {
                oport.WriteLine("{0}Debugging Flags: {1}", prefix, debuggable.DebuggingFlags);
                oport.WriteLine("{0}JIT Optimizer {1}abled", prefix, debuggable.IsJITOptimizerDisabled ? "dis" : "en");
                oport.WriteLine("{0}JIT Tracking {1}abled", prefix, debuggable.IsJITTrackingEnabled ? "en" : "dis");
            }
        }
 public static Mono.CompilerServices.SymbolWriter.MonoSymbolFile ReadSymbolFile(System.Reflection.Assembly assembly)
 {
     throw null;
 }
示例#30
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>ju
        static public void Run(string[] args)
        {
            System.Reflection.Assembly           asm          = null;
            Alachisoft.NCache.Config.Dom.Class[] queryClasses = null;
            string failedNodes = string.Empty;
            bool   sucessful   = false;
            string serverName  = string.Empty;

            try
            {
                object param = new RemoveQueryIndexParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam = (RemoveQueryIndexParam)param;
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }
                if (!ValidateParameters())
                {
                    return;
                }
                if (cParam.Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }
                if (cParam.Server != null && cParam.Server != string.Empty)
                {
                    NCache.ServerName = cParam.Server;
                }
                if (cParam.Port != -1)
                {
                    NCache.Port = cParam.Port;
                }

                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));


                if (cacheServer != null)
                {
                    Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(cParam.CacheId);
                    serverName = cacheServer.GetClusterIP();
                    if (cacheServer.IsRunning(cParam.CacheId))
                    {
                        throw new Exception(cParam.CacheId + " is Running on " + serverName + "Stop the cache first.");
                    }



                    if (serverConfig == null)
                    {
                        throw new Exception("Specified cache is not registered on given server.");
                    }


                    Console.WriteLine("Removing query indexes on node '{0}' from cache '{1}'.",
                                      serverName, cParam.CacheId);
                    if (serverConfig.CacheSettings.QueryIndices != null)
                    {
                        if (serverConfig.CacheSettings.QueryIndices.Classes != null)
                        {
                            queryClasses = serverConfig.CacheSettings.QueryIndices.Classes;
                        }
                        else
                        {
                            return;
                        }

                        if (queryClasses != null)
                        {
                            serverConfig.CacheSettings.QueryIndices.Classes = GetSourceClass(GetClass(queryClasses));
                            if (serverConfig.CacheSettings.QueryIndices.Classes != null)
                            {
                                for (int i = 0; i < serverConfig.CacheSettings.QueryIndices.Classes.Length; i++)
                                {
                                    if (serverConfig.CacheSettings.QueryIndices.Classes[i].AttributesTable.Count < 1)
                                    {
                                        serverConfig.CacheSettings.QueryIndices.Classes[i] = null;
                                    }
                                }
                                bool NoClasses = true;
                                foreach (Class cls in serverConfig.CacheSettings.QueryIndices.Classes)
                                {
                                    if (cls != null)
                                    {
                                        NoClasses = false;
                                        break;
                                    }
                                }
                                if (NoClasses)
                                {
                                    serverConfig.CacheSettings.QueryIndices = null;
                                }
                            }
                            else
                            {
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("No such Query Index class found. ");
                        return;
                    }
                    if (serverConfig.CacheSettings.CacheType == "clustered-cache")
                    {
                        foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                        {
                            NCache.ServerName = node.IpAddress.ToString();
                            try
                            {
                                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                if (cacheServer.IsRunning(cParam.CacheId))
                                {
                                    throw new Exception(cParam.CacheId + " is Running on " + serverName + "Stop the cache first.");
                                }
                                cacheServer.RegisterCache(cParam.CacheId, serverConfig, "", true, cParam.IsHotApply);
                            }
                            catch (Exception ex)
                            {
                                Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);
                                failedNodes = failedNodes + "/n" + node.IpAddress.ToString();
                                LogEvent(ex.Message);
                                sucessful = false;
                            }
                            finally
                            {
                                cacheServer.Dispose();
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            cacheServer.RegisterCache(cParam.CacheId, serverConfig, "", true, cParam.IsHotApply);
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);
                            LogEvent(ex.Message);
                            sucessful = false;
                        }
                        finally
                        {
                            cacheServer.Dispose();
                        }
                    }
                }
                sucessful = true;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Failed to Remove Query Index on node '{0}'. ", serverName);
                Console.Error.WriteLine("Error : {0}", e.Message);
                LogEvent(e.Message);
                sucessful = false;
            }
            finally
            {
                NCache.Dispose();
                if (sucessful && !cParam.IsUsage)
                {
                    Console.WriteLine("Query indexes successfully removed.");
                }
            }
        }
示例#31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddOptions();

            // Add Cors service.
            services.AddCors(options =>
            {
                options
                .AddPolicy("CorsPolicy", p => p
                           .AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader()
                           );
            });

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
            services.AddRouting(options => options.LowercaseUrls  = true);

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure <AppConnections>(Configuration.GetSection("ConnectionStrings"));

            services.AddSingleton <IConfiguration>(Configuration);

            var appSettings = new AppSettings();

            Configuration.Bind("AppSettings", appSettings);
            services.AddSingleton <AppSettings>(appSettings);

            var appConnections = new AppConnections();

            Configuration.Bind("ConnectionStrings", appConnections);
            services.AddSingleton <AppConnections>(appConnections);

            var authenticationCfg = new AuthenticationCfg();

            Configuration.Bind("Authentication", authenticationCfg);
            services.AddSingleton <AuthenticationCfg>(authenticationCfg);

            services.AddHttpContextAccessor();
            services.AddTransient <ClaimsPrincipal>(x =>
            {
                IHttpContextAccessor currentContext = x.GetService <IHttpContextAccessor>();
                return(currentContext.HttpContext.User);
            });

            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IAuthorRepository, AuthorRepository>();
            services.AddScoped <ICategoryRepository, CategoryRepository>();
            services.AddScoped <IAudioBookRepository, AudioBookRepository>();
            services.AddScoped <IAudioBookTrackRepository, AudioBookTrackRepository>();
            services.AddScoped <IBookReaderRepository, BookReaderRepository>();

            // Mediator
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(CommonPipelineBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>));
            System.Reflection.Assembly assembly = AppDomain.CurrentDomain.Load("AudioBook.Api");
            services.AddMediatR(assembly);

            services
            .AddControllers(options =>
            {
                options.RespectBrowserAcceptHeader = true;     // false by default
            })
            .AddJsonOptions(options =>
            {
                // Use the default property (Pascal) casing.
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.AllowTrailingCommas  = true;
                //options.JsonSerializerOptions.IgnoreNullValues = true;
                // Configure a custom converter.
                //options.SerializerOptions.Converters.Add(new MyCustomJsonConverter());
            })
            //.AddJsonFormatters()
            //.AddJsonOptions(option =>
            //{
            //    option.SerializerSettings.ContractResolver = new DefaultContractResolver
            //    {
            //        NamingStrategy = new SnakeCaseNamingStrategy()
            //    };
            //})
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddFluentValidation(option =>
            {
                option.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
                option.RegisterValidatorsFromAssembly(assembly);
            });

            // Customise default API behaviour
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters        = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors         = true;
                options.ClientErrorMapping[404].Link    =
                    "https://httpstatuses.com/404";
            });

            services
            .AddApiVersioning(options =>
            {
                options.ApiVersionReader = new MediaTypeApiVersionReader();
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
                options.ReportApiVersions  = true;
            })
            .AddVersionedApiExplorer(options =>
            {
                // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
                // note: the specified format code will format the version as "'v'major[.minor][-status]"
                options.GroupNameFormat = "'v'VVV";

                // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                // can also be used to control the format of the API version in route templates
                options.SubstituteApiVersionInUrl = true;
            });

            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            ////.AddJwtBearer(o =>
            ////{
            ////    o.Authority = "http://localhost:5000";
            ////    o.Audience = "audiobooks";
            ////    o.RequireHttpsMetadata = false;
            ////});
            //.AddIdentityServerAuthentication(options =>
            //{
            //    options.Authority = authenticationCfg.Authority;
            //    options.ApiName = authenticationCfg.Audience;
            //    options.RequireHttpsMetadata = false;
            //    options.SaveToken = true;
            //});

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>();
            services.AddSwaggerGen(
                options =>
            {
                // add a custom operation filter which sets default values
                options.OperationFilter <SwaggerDefaultValues>();
            });
        }
示例#32
0
 public static System.Diagnostics.SwitchAttribute[] GetAll(System.Reflection.Assembly assembly)
 {
     return(default(System.Diagnostics.SwitchAttribute[]));
 }
        // http://stackoverflow.com/questions/2684278/why-does-microsoft-jscript-work-in-the-code-behind-but-not-within-a
        public static object Eval(string vbCode)
        {
            object retValue;

            System.Text.StringBuilder sb = new System.Text.StringBuilder("");

            sb.AppendLine("using System;");
            // sb.Append("Imports System.Xml" & vbCrLf);
            // sb.Append("Imports System.Data" & vbCrLf);
            // sb.Append("Imports System.Data.SqlClient" & vbCrLf);
            // sb.Append("Imports System.Math" & vbCrLf);
            sb.AppendLine("using Microsoft.VisualBasic;");

            sb.Append("namespace MyEvalNamespace_2C04AF0B_8EC8_4D84_AD83_51FFBBBBC8C6BFAC7762_5502_40C9_AE35_A545434012A4528B58FB_641E_4D61_BA15_E64C58CD8CFC  " + Constants.vbCrLf);
            sb.AppendLine("{ ");
            sb.AppendLine("     public class MyEvalClass ");
            sb.AppendLine("     { ");

            sb.AppendLine("        public object EvalCode() ");
            sb.AppendLine("        { ");
            // sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()");
            sb.Append("            ");
            sb.AppendLine(vbCode);
            sb.AppendLine("        } "); // End Function
            sb.AppendLine("    } ");     // End Class
            sb.AppendLine("} ");         // End Namespace

            // Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string

            string codeToCompile = sb.ToString();

            sb.Clear();
            sb = null;


            // System.Console.WriteLine(codeToCompile)


            using (Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                // System.CodeDom.Compiler.ICodeCompiler icc = codeProvider.CreateCompiler();
                System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();

                cp.ReferencedAssemblies.Add("System.dll");
                // cp.ReferencedAssemblies.Add("System.Xml.dll");
                // cp.ReferencedAssemblies.Add("System.Data.dll");
                // cp.ReferencedAssemblies.Add("Microsoft.JScript.dll");

                // Sample code for adding your own referenced assemblies
                // cp.ReferencedAssemblies.Add(@"C:\YourProjectDir\bin\YourBaseClass.dll");
                // cp.ReferencedAssemblies.Add("YourBaseclass.dll");

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


                // System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromSource(cp, codeToCompile);
                System.CodeDom.Compiler.CompilerResults cr = codeProvider.CompileAssemblyFromSource(cp, codeToCompile);

                System.Reflection.Assembly a = cr.CompiledAssembly;

                object      o = a.CreateInstance("MyEvalNamespace_2C04AF0B_8EC8_4D84_AD83_51FFBBBBC8C6BFAC7762_5502_40C9_AE35_A545434012A4528B58FB_641E_4D61_BA15_E64C58CD8CFC.MyEvalClass");
                System.Type t = o.GetType();
                System.Reflection.MethodInfo mi = t.GetMethod("EvalCode");

                retValue = mi.Invoke(o, null);
            } // End Using codeProvider


            return(retValue);
        } // End Function Eval
示例#34
0
        /// <summary>
        /// This constructor is for the case where the app is started normally (not as a CXP capability).
        /// </summary>
        /// <param name="loader"></param>
        /// <param name="model"></param>
        public ViewerForm(DeckMarshalService loader, PresenterModel model)
        {
            Trace.WriteLine("Start ViewerForm Ctor");
            this.SuspendLayout();
            this.m_EventQueue = new ControlEventQueue(this);

            this.m_Model   = model;
            this.m_Marshal = loader;

            UpdateTitle();

            FontSetting();

            this.Font = ViewerStateModel.FormFont;
            this.Name = "ViewerForm";

            //Retrieve the icon
            System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            Trace.WriteLine("Get Icon");

            this.Icon = new Icon(thisExe.GetManifestResourceStream("UW.ClassroomPresenter.Presenter.ico"));

            this.StartPosition = FormStartPosition.Manual;
            this.loadRegSettings();
            this.MinimumSize = new Size(440, 330);

            Menus.FileMenu.CloseFormDelegate cfd = new UW.ClassroomPresenter.Viewer.Menus.FileMenu.CloseFormDelegate(this.Close);
            this.Menu = new Menus.ViewerMainMenu(this.m_EventQueue, this.m_Model, loader, cfd);

            Trace.WriteLine("Create tool bars");

            this.m_MainToolBars = new MainToolBars(this.m_Model, this.m_EventQueue);
            //this.m_ClassroomBrowser = new AutoDisplayClassroomsBrowser(this.m_Model);
            Trace.WriteLine("Make StartupForm");

            this.m_StartupForm = new StartupForm(this.m_Model, this.m_EventQueue);
            Trace.WriteLine("Make ViewerPresentationLayout");

            this.m_PresentationLayout = new ViewerPresentationLayout(this.m_Model);

            //this.m_ClassroomBrowser.Dock = DockStyle.Fill;
            this.m_PresentationLayout.Dock = DockStyle.Fill;

            this.Controls.Add(this.m_PresentationLayout);

            // Hack: toggle the second monitor to make it scale correctly when using Surface Pro 3.
            // Bounds need to be set after the ViewerPresentationLayout control is added,
            // Otherwise DPI scaling appears to be done incorrectly.  This issue so far
            // appears to be unique to the Surface Pro 3.
            using (Synchronizer.Lock(model.ViewerState.SyncRoot)) {
                if (model.ViewerState.SecondMonitorEnabled)
                {
                    model.ViewerState.SecondMonitorEnabled = false;
                    model.ViewerState.SecondMonitorEnabled = true;
                }
            }

            //this.Controls.Add(this.m_ClassroomBrowser);
            this.m_StartupForm.Visible = false;

            this.Controls.Add(this.m_MainToolBars.m_MainToolBar);
            this.Controls.Add(this.m_MainToolBars.m_MainClassmateToolBar);
            this.Controls.Add(this.m_MainToolBars.m_ExtraClassmateToolBar);

            this.ResumeLayout(false);

            Trace.WriteLine("Make KeyEventHandler");

            this.KeyDown   += new KeyEventHandler(this.OnKeyDown);
            this.KeyPreview = true;

            ///add listeners for HumanName, Role, Stylus properties
            role_listener_       = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.ParticipantRoleChanged));
            stylus_listener_     = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.StylusChanged));
            instructor_listener_ = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.InstructorChanged));


            this.m_Model.Participant.Changed["Role"].Add(role_listener_.Dispatcher);
            this.m_Model.Changed["Stylus"].Add(stylus_listener_.Dispatcher);
            this.m_Model.Network.Changed["Association"].Add(instructor_listener_.Dispatcher);

            //Add listener for the version exchange warning pop-up
            this.m_VersionExchangePopUpListener = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.PopUpWarningHandler));
            this.m_Model.VersionExchange.Changed["PopUpWarningMessage"].Add(m_VersionExchangePopUpListener.Dispatcher);

            Trace.WriteLine("Make EventDispatcher");

            //Add listener for NetworkStatus
            m_NetworkStatusListener = new EventQueue.PropertyEventDispatcher(this.m_EventQueue, new PropertyEventHandler(this.NetworkStatusChanged));
            this.m_Model.Network.Changed["NetworkStatus"].Add(m_NetworkStatusListener.Dispatcher);

            Trace.WriteLine("Make FullScreenAdapter");

            this.m_FullScreenAdapter = new FullScreenAdapter(this.m_Model, this.m_PresentationLayout);

            instructor_listener_.Dispatcher(this, null);
            role_listener_.Dispatcher(this, null);
            stylus_listener_.Dispatcher(this, null);

            this.Activated   += this.ShowStartup;
            this.FormClosing += this.SaveClose;

            //Store local DPI settings which are used to make sure ink is scaled correctly.
            using (Graphics g = this.CreateGraphics()) {
                ViewerStateModel.SetLocalDpi(g.DpiX, g.DpiY);
            }
            Trace.WriteLine("ViewerForm Ctor done.");
        }
示例#35
0
		private void frmMain_Load( object sender, EventArgs e ) {
			mAssembly = System.Reflection.Assembly.GetExecutingAssembly();

			Text += string.Format( " v{0} - by GodLesZ", mAssembly.ShortVersion() );

			mSignatur = new Signatur( mAssembly, signaturImage, comboCustomFont );
			mInputTimer = new Timer();
			mInputTimer.Interval = 350;
			mInputTimer.Tick += new EventHandler( mInputTimer_Tick );
			mInputTimer.Enabled = true;
			mInputTimer.Stop();

			InitializeBackgrounds();
			InitializeCombos( true, true );

			InitializeSignatur();
			mSignatur.Update();
		}
示例#36
0
 public ShadowAssemblyType(System.Reflection.Assembly shadowAssembly, string originalAssemblyPath)
 {
     ShadowAssembly = shadowAssembly;
     OriginalAssemblyPath = originalAssemblyPath;
 }
示例#37
0
        private void startService(string service, string entryPoint, string[] args)
        {
            lock (this)
            {
                //
                // Extract the assembly name and the class name.
                //
                string err    = "ServiceManager: unable to load service '" + entryPoint + "': ";
                int    sepPos = entryPoint.IndexOf(':');
                if (sepPos != -1)
                {
                    const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    if (entryPoint.Length > 3 &&
                        sepPos == 1 &&
                        driveLetters.IndexOf(entryPoint[0]) != -1 &&
                        (entryPoint[2] == '\\' || entryPoint[2] == '/'))
                    {
                        sepPos = entryPoint.IndexOf(':', 3);
                    }
                }
                if (sepPos == -1)
                {
                    FailureException e = new FailureException();
                    e.reason = err + "invalid entry point format";
                    throw e;
                }

                System.Reflection.Assembly serviceAssembly = null;
                string assemblyName = entryPoint.Substring(0, sepPos);
                string className    = entryPoint.Substring(sepPos + 1);

                try
                {
                    //
                    // First try to load the assembly using Assembly.Load, which will succeed
                    // if a fully-qualified name is provided or if a partial name has been qualified
                    // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed
                    // if a file name is configured or a partial name is configured and DEVPATH is used.
                    //
                    try
                    {
                        serviceAssembly = System.Reflection.Assembly.Load(assemblyName);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName);
                        }
                        catch (Exception)
                        {
                            throw ex;
                        }
                    }
                }
                catch (Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "unable to load assembly: " + assemblyName;
                    throw e;
                }

                //
                // Instantiate the class.
                //
                Type c = null;
                try
                {
                    c = serviceAssembly.GetType(className, true);
                }
                catch (Exception ex)
                {
                    FailureException e = new FailureException(ex);
                    e.reason = err + "GetType failed for '" + className + "'";
                    throw e;
                }

                ServiceInfo info = new ServiceInfo();
                info.name   = service;
                info.status = ServiceStatus.Stopped;
                info.args   = args;

                //
                // If IceBox.UseSharedCommunicator.<name> is defined, create a
                // communicator for the service. The communicator inherits
                // from the shared communicator properties. If it's not
                // defined, add the service properties to the shared
                // commnunicator property set.
                //
                Ice.Communicator communicator;
                if (_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0)
                {
                    Debug.Assert(_sharedCommunicator != null);
                    communicator = _sharedCommunicator;
                }
                else
                {
                    //
                    // Create the service properties. We use the communicator properties as the default
                    // properties if IceBox.InheritProperties is set.
                    //
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties(service);
                    if (info.args.Length > 0)
                    {
                        //
                        // Create the service properties with the given service arguments. This should
                        // read the service config file if it's specified with --Ice.Config.
                        //
                        initData.properties = Ice.Util.createProperties(ref info.args, initData.properties);

                        //
                        // Next, parse the service "<service>.*" command line options (the Ice command
                        // line options were parsed by the createProperties above)
                        //
                        info.args = initData.properties.parseCommandLineOptions(service, info.args);
                    }

                    //
                    // Clone the logger to assign a new prefix. If one of the built-in loggers is configured
                    // don't set any logger.
                    //
                    if (initData.properties.getProperty("Ice.LogFile").Length == 0)
                    {
                        initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName"));
                    }

                    //
                    // If Admin is enabled on the IceBox communicator, for each service that does not set
                    // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then
                    // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>.
                    //
                    string serviceFacetNamePrefix = "IceBox.Service." + service + ".";
                    bool   addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix);

                    //
                    // Remaining command line options are passed to the communicator. This is
                    // necessary for Ice plug-in properties (e.g.: IceSSL).
                    //
                    info.communicator = Ice.Util.initialize(ref info.args, initData);
                    communicator      = info.communicator;

                    if (addFacets)
                    {
                        // Add all facets created on the service communicator to the IceBox communicator
                        // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet
                        // which is never added
                        foreach (KeyValuePair <string, Ice.Object> p in communicator.findAllAdminFacets())
                        {
                            if (!p.Key.Equals("Process"))
                            {
                                _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key);
                            }
                        }
                    }
                }

                try
                {
                    //
                    // Instantiate the service.
                    //
                    try
                    {
                        //
                        // If the service class provides a constructor that accepts an Ice.Communicator argument,
                        // use that in preference to the default constructor.
                        //
                        Type[] parameterTypes = new Type[1];
                        parameterTypes[0] = typeof(Ice.Communicator);
                        System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes);
                        if (ci != null)
                        {
                            try
                            {
                                object[] parameters = new object[1];
                                parameters[0] = _communicator;
                                info.service  = (Service)ci.Invoke(parameters);
                            }
                            catch (MethodAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)";
                                throw e;
                            }
                        }
                        else
                        {
                            //
                            // Fall back to the default constructor.
                            //
                            try
                            {
                                info.service = (Service)IceInternal.AssemblyUtil.createInstance(c);
                                if (info.service == null)
                                {
                                    FailureException e = new FailureException();
                                    e.reason = err + "no default constructor for '" + className + "'";
                                    throw e;
                                }
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                FailureException e = new FailureException(ex);
                                e.reason = err + "unauthorized access to default service constructor for " + className;
                                throw e;
                            }
                        }
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (InvalidCastException ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "service does not implement IceBox.Service";
                        throw e;
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        if (ex.InnerException is FailureException)
                        {
                            throw ex.InnerException;
                        }
                        else
                        {
                            FailureException e = new FailureException(ex.InnerException);
                            e.reason = err + "exception in service constructor for " + className;
                            throw e;
                        }
                    }
                    catch (Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = err + "exception in service constructor " + className;
                        throw e;
                    }

                    try
                    {
                        info.service.start(service, communicator, info.args);
                    }
                    catch (FailureException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        FailureException e = new FailureException(ex);
                        e.reason = "exception while starting service " + service;
                        throw e;
                    }

                    info.status = ServiceStatus.Started;
                    _services.Add(info);
                }
                catch (Exception)
                {
                    if (info.communicator != null)
                    {
                        destroyServiceCommunicator(service, info.communicator);
                    }

                    throw;
                }
            }
        }
示例#38
0
        /// <summary>
        /// Attempts to load tensorflow modules from the specific location
        /// </summary>
        /// <param name="loadDirectory">The directory where the unmanaged modules will be loaded. If it is null, the default location will be used.</param>
        /// <param name="unmanagedModules">The names of tensorflow modules. </param>
        /// <returns>True if all the modules has been loaded successfully</returns>
        /// <remarks>If <paramref name="loadDirectory"/> is null, the default location on windows is the dll's path appended by either "x64" or "x86", depends on the applications current mode.</remarks>
        public static bool LoadUnmanagedModules(String loadDirectory, params String[] unmanagedModules)
        {
#if UNITY_WSA || UNITY_STANDALONE || UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS
            if (loadDirectory != null)
            {
                throw new NotImplementedException("Loading modules from a specific directory is not implemented in Windows Store App");
            }
            //Let unity handle the library loading
            return(true);
#else
            String oldDir = String.Empty;

            if (loadDirectory == null)
            {
                List <String> subfolderOptions = new List <string>();

                if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows) ||
                    System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)
                    )
                {
                    if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
                    {
                        if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                        {
                            throw new Exception("Emgu TF Lite is only compatible with 64bit mode in Windows (not compatible with 32bit x86 mode)");
                            //subfolderOptions.Add(Path.Combine("runtimes", "win-x86", "native"));
                        }
                        subfolderOptions.Add("x86");
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
                    {
                        if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                        {
                            subfolderOptions.Add(Path.Combine("runtimes", "win-x64", "native"));
                        }
                        subfolderOptions.Add("x64");
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm)
                    {
                        subfolderOptions.Add("arm");
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
                    {
                        subfolderOptions.Add("arm64");
                    }

                    //if ("x86".Equals(subfolder) && System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                    //{
                    //    throw new Exception("Emgu TF Lite is only compatible with 64bit mode in Windows (not compatible with 32bit x86 mode)");
                    //}
                }
                String subfolder = String.Empty;

                System.Reflection.Assembly asm = typeof(TfLiteInvoke).Assembly; //System.Reflection.Assembly.GetExecutingAssembly();
                if ((String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location)))
                {
                    if (String.IsNullOrEmpty(AppDomain.CurrentDomain.BaseDirectory))
                    {
                        loadDirectory = String.Empty;
                    }
                    else
                    {
                        //we may be running in a debugger visualizer under a unit test in this case
                        String        baseDirectory          = AppDomain.CurrentDomain.BaseDirectory;
                        DirectoryInfo baseDirectoryInfo      = new DirectoryInfo(baseDirectory);
                        String        debuggerVisualizerPath = String.Empty;
                        if (baseDirectoryInfo.Parent != null)
                        {
                            debuggerVisualizerPath = Path.Combine(baseDirectoryInfo.Parent.FullName, "Packages", "Debugger", "Visualizers");
                        }

                        if (!debuggerVisualizerPath.Equals(String.Empty) && Directory.Exists(debuggerVisualizerPath))
                        {
                            loadDirectory = debuggerVisualizerPath;
                        }
                        else
                        {
                            loadDirectory = baseDirectoryInfo.FullName;
                        }
                        subfolder = FindValidSubfolders(loadDirectory, subfolderOptions);
                    }
                }
                else
                {
                    loadDirectory = Path.GetDirectoryName(asm.Location);
                    if (loadDirectory != null)
                    {
                        subfolder = FindValidSubfolders(loadDirectory, subfolderOptions);
                    }
                }

                if (!String.IsNullOrEmpty(subfolder))
                {
                    if (Directory.Exists(Path.Combine(loadDirectory, subfolder)))
                    {
                        loadDirectory = Path.Combine(loadDirectory, subfolder);
                    }
                    else
                    {
                        loadDirectory = Path.Combine(Path.GetFullPath("."), subfolder);
                    }
                }


                System.Reflection.Assembly monoAndroidAssembly = Emgu.TF.Util.Toolbox.FindAssembly("Mono.Android.dll");
                if (monoAndroidAssembly == null)
                {
                    //Not running on Android
                    if (!Directory.Exists(loadDirectory))
                    {
                        //try to find an alternative loadDirectory path
                        //The following code should handle finding the asp.NET BIN folder
                        if (String.IsNullOrEmpty(asm.Location) || !File.Exists(asm.Location))
                        {
                            Debug.WriteLine(String.Format("asm.Location is invalid: '{0}'", asm.Location));
                        }
                        else
                        {
                            FileInfo      file      = new FileInfo(asm.Location);
                            DirectoryInfo directory = file.Directory;
                            if ((directory != null) && (!String.IsNullOrEmpty(subfolder)) && Directory.Exists(Path.Combine(directory.FullName, subfolder)))
                            {
                                loadDirectory = Path.Combine(directory.FullName, subfolder);
                            }
                            else if (directory != null && Directory.Exists(directory.FullName))
                            {
                                loadDirectory = directory.FullName;
                            }
                        }
                    }
                }
            }

            bool setDllDirectorySuccess = false;
            if (!String.IsNullOrEmpty(loadDirectory) && Directory.Exists(loadDirectory))
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    setDllDirectorySuccess = Emgu.TF.Util.Toolbox.SetDllDirectory(loadDirectory);
                    if (!setDllDirectorySuccess)
                    {
                        System.Diagnostics.Debug.WriteLine(String.Format("Failed to set dll directory: {0}", loadDirectory));
                    }
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                }
                else if (Emgu.TF.Util.Toolbox.FindAssembly("Xamarin.iOS.dll") != null)
                {
                    //do nothing
                    System.Diagnostics.Debug.WriteLine("iOS required static linking, setting load directory is not supported");
                }
                else
                {
                    oldDir = Environment.CurrentDirectory;
                    Environment.CurrentDirectory = loadDirectory;
                }
            }

            if (setDllDirectorySuccess)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    System.Diagnostics.Debug.WriteLine(
                        String.Format(
                            "Loading TF Lite binary for default locations. Current directory: {0}; Additional load folder: {1}",
                            Environment.CurrentDirectory,
                            loadDirectory));
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(
                    String.Format(
                        "Loading TF Lite binary for default locations. Current directory: {0}",
                        Environment.CurrentDirectory));
            }

            System.Diagnostics.Trace.WriteLine(String.Format("Loading tensorflow lite binary from {0}", loadDirectory));
            bool success = true;

            string prefix       = string.Empty;
            String formatString = GetModuleFormatString();
            foreach (String module in unmanagedModules)
            {
                string mName = String.Format(formatString, module);

                String fullPath = Path.Combine(prefix, mName);

                //Use absolute path for Windows Desktop
                fullPath = Path.Combine(loadDirectory, fullPath);

                bool fileExist = File.Exists(fullPath);
                if (!fileExist)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format("File {0} do not exist.", fullPath));
                }

                /*
                 * bool loaded;
                 * if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                 * {
                 *  loaded = fileExist && !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                 *  if (loaded)
                 *  {
                 *      System.Diagnostics.Trace.WriteLine(String.Format("File {0} loaded.", fullPath));
                 *  }
                 *  else
                 *  {
                 *      System.Diagnostics.Trace.WriteLine(String.Format("File {0} cannot be loaded.", fullPath));
                 *  }
                 * }
                 * else
                 * {
                 *  loaded = true;
                 * }
                 *
                 * success &= (fileExist && loaded); */
                bool optionalComponent = false;

                bool loaded = false;

                if (fileExist)
                {
                    //Try to load using the full path
                    System.Diagnostics.Trace.WriteLine(String.Format("Found full path {0} for {1}. Trying to load it.", fullPath, mName));
                    loaded = !IntPtr.Zero.Equals(Toolbox.LoadLibrary(fullPath));
                    if (loaded)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} loaded.", mName));
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("Failed to load {0} from {1}.", mName, fullPath));
                    }
                }
                if (!loaded)
                {
                    //Try to load without the full path
                    System.Diagnostics.Trace.WriteLine(String.Format("Trying to load {0} using default path.", mName));
                    loaded = !IntPtr.Zero.Equals(Toolbox.LoadLibrary(mName));
                    if (loaded)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("{0} loaded using default path", mName));
                    }
                    else
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("Failed to load {0} using default path", mName));
                    }
                }

                if (!loaded)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format("!!! Failed to load {0}.", mName));
                }

                if (!optionalComponent)
                {
                    success &= loaded;
                }
            }

            if (!oldDir.Equals(String.Empty))
            {
                Environment.CurrentDirectory = oldDir;
            }

            return(success);
#endif
        }
示例#39
0
 public StringTemplateGroup( string name, string rootDir, Type lexer, Assembly rootAssembly )
 {
     this._name = name;
     this._rootDir = rootDir;
     this._rootAssembly = rootAssembly;
     _lastCheckedDisk = DateTime.Now;
     TemplateLexerClass = lexer;
     StringTemplateGroup._nameToGroupMap[name] = this;
 }
 public EmbeddedResourceFileInfo(System.Reflection.Assembly assembly, string resourcePath, string name, System.DateTimeOffset lastModified)
 {
 }
示例#41
0
 public static void InitializeTypes(bool forceFullInitialization, System.Reflection.Assembly assembly = null)
 {
     throw new NotImplementedException();
 }
        public override string ToText(Subtitle subtitle, string title)
        {
            Errors = null;
            var ss = Configuration.Settings.SubtitleSettings;

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaEditRate))
            {
                string[] temp = ss.CurrentDCinemaEditRate.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                double   d1, d2;
                if (temp.Length == 2 && double.TryParse(temp[0], out d1) && double.TryParse(temp[1], out d2))
                {
                    _frameRate = d1 / d2;
                }
            }

            string xmlStructure =
                "<dcst:SubtitleReel xmlns:dcst=\"http://www.smpte-ra.org/schemas/428-7/2007/DCST\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine +
                "  <dcst:Id>urn:uuid:7be835a3-cfb4-43d0-bb4b-f0b4c95e962e</dcst:Id>" + Environment.NewLine +
                "  <dcst:ContentTitleText></dcst:ContentTitleText> " + Environment.NewLine +
                "  <dcst:AnnotationText>This is a subtitle file</dcst:AnnotationText>" + Environment.NewLine +
                "  <dcst:IssueDate>2012-06-26T12:33:59.000-00:00</dcst:IssueDate>" + Environment.NewLine +
                "  <dcst:ReelNumber>1</dcst:ReelNumber>" + Environment.NewLine +
                "  <dcst:Language>en</dcst:Language>" + Environment.NewLine +
                "  <dcst:EditRate>25 1</dcst:EditRate>" + Environment.NewLine +
                "  <dcst:TimeCodeRate>25</dcst:TimeCodeRate>" + Environment.NewLine +
                "  <dcst:StartTime>00:00:00:00</dcst:StartTime> " + Environment.NewLine +
                "  <dcst:LoadFont ID=\"theFontId\">urn:uuid:3dec6dc0-39d0-498d-97d0-928d2eb78391</dcst:LoadFont>" + Environment.NewLine +
                "  <dcst:SubtitleList>" + Environment.NewLine +
                "    <dcst:Font ID=\"theFontId\" Size=\"39\" Weight=\"normal\" Color=\"FFFFFFFF\" Effect=\"border\" EffectColor=\"FF000000\">" + Environment.NewLine +
                "    </dcst:Font>" + Environment.NewLine +
                "  </dcst:SubtitleList>" + Environment.NewLine +
                "</dcst:SubtitleReel>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);
            xml.PreserveWhitespace = true;
            var nsmgr = new XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("dcst", xml.DocumentElement.NamespaceURI);

            if (string.IsNullOrEmpty(ss.CurrentDCinemaMovieTitle))
            {
                ss.CurrentDCinemaMovieTitle = title;
            }

            if (ss.CurrentDCinemaFontSize == 0 || string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect))
            {
                Configuration.Settings.SubtitleSettings.InitializeDCinameSettings(true);
            }

            xml.DocumentElement.SelectSingleNode("dcst:ContentTitleText", nsmgr).InnerText = ss.CurrentDCinemaMovieTitle;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaSubtitleId) || !ss.CurrentDCinemaSubtitleId.StartsWith("urn:uuid:"))
            {
                ss.CurrentDCinemaSubtitleId = "urn:uuid:" + Guid.NewGuid();
            }
            xml.DocumentElement.SelectSingleNode("dcst:Id", nsmgr).InnerText         = ss.CurrentDCinemaSubtitleId;
            xml.DocumentElement.SelectSingleNode("dcst:ReelNumber", nsmgr).InnerText = ss.CurrentDCinemaReelNumber;
            xml.DocumentElement.SelectSingleNode("dcst:IssueDate", nsmgr).InnerText  = ss.CurrentDCinemaIssueDate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaLanguage))
            {
                ss.CurrentDCinemaLanguage = "en";
            }
            xml.DocumentElement.SelectSingleNode("dcst:Language", nsmgr).InnerText = ss.CurrentDCinemaLanguage;
            if (ss.CurrentDCinemaEditRate == null && ss.CurrentDCinemaTimeCodeRate == null)
            {
                if (Configuration.Settings.General.CurrentFrameRate == 24)
                {
                    ss.CurrentDCinemaEditRate     = "24 1";
                    ss.CurrentDCinemaTimeCodeRate = "24";
                }
                else
                {
                    ss.CurrentDCinemaEditRate     = "25 1";
                    ss.CurrentDCinemaTimeCodeRate = "25";
                }
            }
            xml.DocumentElement.SelectSingleNode("dcst:EditRate", nsmgr).InnerText     = ss.CurrentDCinemaEditRate;
            xml.DocumentElement.SelectSingleNode("dcst:TimeCodeRate", nsmgr).InnerText = ss.CurrentDCinemaTimeCodeRate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaStartTime))
            {
                ss.CurrentDCinemaStartTime = "00:00:00:00";
            }
            xml.DocumentElement.SelectSingleNode("dcst:StartTime", nsmgr).InnerText = ss.CurrentDCinemaStartTime;
            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).InnerText  = ss.CurrentDCinemaFontUri;
            int    fontSize     = ss.CurrentDCinemaFontSize;
            string loadedFontId = "Font1";

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontId))
            {
                loadedFontId = ss.CurrentDCinemaFontId;
            }
            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).Attributes["ID"].Value = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Size"].Value        = fontSize.ToString();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Color"].Value       = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontColor).TrimStart('#').ToUpper();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["ID"].Value          = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Effect"].Value      = ss.CurrentDCinemaFontEffect;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["EffectColor"].Value = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontEffectColor).TrimStart('#').ToUpper();

            XmlNode mainListFont = xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr);
            int     no           = 0;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                if (p.Text != null)
                {
                    XmlNode subNode = xml.CreateElement("dcst:Subtitle", "dcst");

                    XmlAttribute id = xml.CreateAttribute("SpotNumber");
                    id.InnerText = (no + 1).ToString();
                    subNode.Attributes.Append(id);

                    XmlAttribute fadeUpTime = xml.CreateAttribute("FadeUpTime");
                    fadeUpTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString();
                    subNode.Attributes.Append(fadeUpTime);

                    XmlAttribute fadeDownTime = xml.CreateAttribute("FadeDownTime");
                    fadeDownTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString();
                    subNode.Attributes.Append(fadeDownTime);

                    XmlAttribute start = xml.CreateAttribute("TimeIn");
                    start.InnerText = ConvertToTimeString(p.StartTime);
                    subNode.Attributes.Append(start);

                    XmlAttribute end = xml.CreateAttribute("TimeOut");
                    end.InnerText = ConvertToTimeString(p.EndTime);
                    subNode.Attributes.Append(end);

                    bool alignLeft = p.Text.StartsWith("{\\a1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) ||      // sub station alpha
                                     p.Text.StartsWith("{\\an1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an7}", StringComparison.Ordinal);     // advanced sub station alpha

                    bool alignRight = p.Text.StartsWith("{\\a3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) ||    // sub station alpha
                                      p.Text.StartsWith("{\\an3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal);    // advanced sub station alpha

                    bool alignVTop = p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) ||      // sub station alpha
                                     p.Text.StartsWith("{\\an7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an8}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal);     // advanced sub station alpha

                    bool alignVCenter = p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a10}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) || // sub station alpha
                                        p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal);  // advanced sub station alpha

                    string text = Utilities.RemoveSsaTags(p.Text);

                    var lines      = text.SplitToLines();
                    int vPos       = 1 + lines.Length * 7;
                    int vPosFactor = (int)Math.Round(fontSize / 7.4);
                    if (alignVTop)
                    {
                        vPos = Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }
                    else if (alignVCenter)
                    {
                        vPos = (int)Math.Round((lines.Length * vPosFactor * -1) / 2.0);
                    }
                    else
                    {
                        vPos = (lines.Length * vPosFactor) - vPosFactor + Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }

                    bool           isItalic   = false;
                    int            fontNo     = 0;
                    Stack <string> fontColors = new Stack <string>();
                    foreach (string line in lines)
                    {
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");

                        XmlAttribute vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        XmlAttribute vAlign = xml.CreateAttribute("Valign");
                        if (alignVTop)
                        {
                            vAlign.InnerText = "top";
                        }
                        else if (alignVCenter)
                        {
                            vAlign.InnerText = "center";
                        }
                        else
                        {
                            vAlign.InnerText = "bottom";
                        }
                        textNode.Attributes.Append(vAlign); textNode.Attributes.Append(vAlign);

                        XmlAttribute hAlign = xml.CreateAttribute("Halign");
                        if (alignLeft)
                        {
                            hAlign.InnerText = "left";
                        }
                        else if (alignRight)
                        {
                            hAlign.InnerText = "right";
                        }
                        else
                        {
                            hAlign.InnerText = "center";
                        }
                        textNode.Attributes.Append(hAlign);

                        XmlAttribute direction = xml.CreateAttribute("Direction");
                        direction.InnerText = "ltr";
                        textNode.Attributes.Append(direction);

                        int     i        = 0;
                        var     txt      = new StringBuilder();
                        var     html     = new StringBuilder();
                        XmlNode nodeTemp = xml.CreateElement("temp");
                        while (i < line.Length)
                        {
                            if (!isItalic && line.Substring(i).StartsWith("<i>"))
                            {
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt.Clear();
                                }
                                isItalic = true;
                                i       += 2;
                            }
                            else if (isItalic && line.Substring(i).StartsWith("</i>"))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    XmlAttribute italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);

                                    if (line.Length > i + 5 && line.Substring(i + 4).StartsWith("</font>"))
                                    {
                                        XmlAttribute fontColor = xml.CreateAttribute("Color");
                                        fontColor.InnerText = fontColors.Pop();
                                        fontNode.Attributes.Append(fontColor);
                                        fontNo--;
                                        i += 7;
                                    }

                                    fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt.Clear();
                                }
                                isItalic = false;
                                i       += 3;
                            }
                            else if (line.Substring(i).StartsWith("<font color=") && line.Substring(i + 3).Contains('>'))
                            {
                                int endOfFont = line.IndexOf('>', i);
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt.Clear();
                                }
                                string c = line.Substring(i + 12, endOfFont - (i + 12));
                                c = c.Trim('"').Trim('\'').Trim();
                                if (c.StartsWith('#'))
                                {
                                    c = c.TrimStart('#').ToUpper().PadLeft(8, 'F');
                                }
                                fontColors.Push(c);
                                fontNo++;
                                i += endOfFont - i;
                            }
                            else if (fontNo > 0 && line.Substring(i).StartsWith("</font>"))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    XmlAttribute fontColor = xml.CreateAttribute("Color");
                                    fontColor.InnerText = fontColors.Pop();
                                    fontNode.Attributes.Append(fontColor);

                                    if (line.Length > i + 9 && line.Substring(i + 7).StartsWith("</i>"))
                                    {
                                        XmlAttribute italic = xml.CreateAttribute("Italic");
                                        italic.InnerText = "yes";
                                        fontNode.Attributes.Append(italic);
                                        isItalic = false;
                                        i       += 4;
                                    }

                                    fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt.Clear();
                                }
                                fontNo--;
                                i += 6;
                            }
                            else
                            {
                                txt.Append(line[i]);
                            }
                            i++;
                        }

                        if (fontNo > 0)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                XmlAttribute fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                if (isItalic)
                                {
                                    XmlAttribute italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);
                                }

                                fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                html.Append(fontNode.OuterXml);
                            }
                            else if (html.Length > 0 && html.ToString().StartsWith("<dcst:Font "))
                            {
                                XmlDocument temp = new XmlDocument();
                                temp.LoadXml("<root>" + html.ToString().Replace("dcst:Font", "Font") + "</root>");
                                XmlNode fontNode = xml.CreateElement("dcst:Font");
                                fontNode.InnerXml = temp.DocumentElement.SelectSingleNode("Font").InnerXml;
                                foreach (XmlAttribute a in temp.DocumentElement.SelectSingleNode("Font").Attributes)
                                {
                                    XmlAttribute newA = xml.CreateAttribute(a.Name);
                                    newA.InnerText = a.InnerText;
                                    fontNode.Attributes.Append(newA);
                                }

                                XmlAttribute fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                html.Clear();
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else if (isItalic)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                XmlAttribute italic = xml.CreateAttribute("Italic");
                                italic.InnerText = "yes";
                                fontNode.Attributes.Append(italic);

                                fontNode.InnerText = HtmlUtil.RemoveHtmlTags(line);
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else
                        {
                            if (txt.Length > 0)
                            {
                                nodeTemp.InnerText = txt.ToString();
                                html.Append(nodeTemp.InnerXml);
                            }
                        }
                        textNode.InnerXml = html.ToString();

                        subNode.AppendChild(textNode);
                        if (alignVTop)
                        {
                            vPos += vPosFactor;
                        }
                        else
                        {
                            vPos -= vPosFactor;
                        }
                    }
                    if (subNode.InnerXml.Length == 0)
                    { // Empty text is just one space
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");
                        textNode.InnerXml = " ";
                        subNode.AppendChild(textNode);

                        XmlAttribute vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        XmlAttribute vAlign = xml.CreateAttribute("Valign");
                        vAlign.InnerText = "bottom";
                        textNode.Attributes.Append(vAlign);
                    }
                    mainListFont.AppendChild(subNode);
                    no++;
                }
            }
            string result = ToUtf8XmlString(xml).Replace("encoding=\"utf-8\"", "encoding=\"UTF-8\"").Replace(" xmlns:dcst=\"dcst\"", string.Empty);

            const string res = "Nikse.SubtitleEdit.Resources.SMPTE-428-7-2007-DCST.xsd.gz";

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            Stream strm = asm.GetManifestResourceStream(res);

            if (strm != null)
            {
                try
                {
                    var xmld = new XmlDocument();
                    var rdr  = new StreamReader(strm);
                    var zip  = new GZipStream(rdr.BaseStream, CompressionMode.Decompress);
                    xmld.LoadXml(result);
                    using (var xr = XmlReader.Create(zip))
                    {
                        xmld.Schemas.Add(null, xr);
                        xmld.Validate(ValidationCallBack);
                    }
                }
                catch (Exception exception)
                {
                    Errors = "Error validating xml via SMPTE - 428 - 7 - 2007 - DCST.xsd: " + exception.Message;
                }
            }
            return(DCinemaSmpte2010.FixDcsTextSameLine(result));
        }
示例#43
0
 private static void AssertNotNull(Assembly assembly)
 {
     if (null == assembly) throw new ArgumentNullException("assembly");
 }
示例#44
0
 public static DbUp.Builder.UpgradeEngineBuilder WithScriptsAndCodeEmbeddedInAssembly(this DbUp.Builder.UpgradeEngineBuilder builder, System.Reflection.Assembly assembly, DbUp.Engine.SqlScriptOptions sqlScriptOptions)
 {
 }
示例#45
0
 public WCellAddonContext(FileInfo file, System.Reflection.Assembly asm)
 {
     m_file = file;
     m_assembly = asm;
 }
 public EmbeddedFileProvider(System.Reflection.Assembly assembly)
 {
 }
示例#47
0
        void OnGUI()
        {
            GUILayout.Label("Select source files to compile");

            string path = "";

            if (GUILayout.Button("Add File", GUILayout.Width(500)))
            {
                path = EditorUtility.OpenFilePanelWithFilters("", Application.dataPath, new string[] { "CSharp", "cs" });
                if (filesToCompile.Contains(path))
                {
                    Debug.Log("This file is already selected");
                    return;
                }
                else if (File.Exists(path))
                {
                    filesToCompile.Add(path);
                }
                else
                {
                    Debug.Log("Please select a valid file");
                }
            }

            EditorGUILayout.Space();


            if (filesToCompile != null && filesToCompile.Count > 0)
            {
                if (GUILayout.Button("Compile"))
                {
                    try
                    {
                        System.Reflection.Assembly assembly = Compiler.CompileSource(filesToCompile.ToArray(), false, false);
                        Debug.Log(string.Format("Assembly {0} created", assembly.GetName().Name));
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError(ex.Message);
                    }
                }
            }

            EditorGUILayout.Space();

            showFilesFoldout = GUILayoutHelper.Foldout(showFilesFoldout, new GUIContent("Files"), () =>
            {
                scrollPos = GUILayoutHelper.ScrollView(scrollPos, () =>
                {
                    for (int i = 0; i < filesToCompile.Count; i++)
                    {
                        EditorGUILayout.Space();

                        GUILayoutHelper.Horizontal(() =>
                        {
                            EditorGUI.indentLevel++;

                            Vector2 textDimensions = GUI.skin.label.CalcSize(new GUIContent(filesToCompile[i]));
                            EditorGUILayout.LabelField(new GUIContent(filesToCompile[i]), GUILayout.Width(textDimensions[0])); //EditorGUILayout.SelectableLabel(filesToCompile[i]);

                            EditorGUI.indentLevel++;

                            if (GUILayout.Button("Remove", GUILayout.MinWidth(10), GUILayout.Width(60)))
                            {
                                RemoveFileFromList(i);
                                EditorGUILayout.Space();
                            }

                            EditorGUI.indentLevel--;
                            EditorGUI.indentLevel--;
                        });
                    }
                });
            });
        }
 public ManifestEmbeddedFileProvider(System.Reflection.Assembly assembly, string root, string manifestName, System.DateTimeOffset lastModified)
 {
 }
示例#49
0
文件: Assembly.cs 项目: danaxa/Pencil
 internal Assembly(ITypeLoader typeLoader, ReflectionAssembly assembly)
 {
     this.typeLoader = typeLoader;
     this.assembly = assembly;
 }
 public ManifestEmbeddedFileProvider(System.Reflection.Assembly assembly, string root)
 {
 }
 public static string GetCopyrightInfo()
 {
     System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
     FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
     return fvi.LegalCopyright;
 }
 public EmbeddedFileProvider(System.Reflection.Assembly assembly, string baseNamespace)
 {
 }
示例#53
0
 public AssemblyImpl(System.Reflection.Assembly assembly)
 {
     Debug.Assert(assembly != null);
     this.Assembly = assembly;
 }
示例#54
0
 public Hash(System.Reflection.Assembly assembly)
 {
 }
        public override void GenerateLayout()
        {
            if (collection.Count == 0)
            {
                return;
            }

            base.GenerateLayout();

            IBrowsableItem [] photos = collection.Items;

            int i;

            for (i = 0; i < photos.Length; i++)
            {
                SavePhotoHtmlIndex(i);
            }

            for (i = 0; i < PageCount; i++)
            {
                SaveHtmlIndex(i);
            }

            MakeDir(SubdirPath("style"));
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly();
            using (Stream s = assembly.GetManifestResourceStream(stylesheet)) {
                using (Stream fs = System.IO.File.Open(SubdirPath("style", stylesheet), System.IO.FileMode.Create)) {
                    byte [] buffer = new byte [8192];
                    int     n;
                    while ((n = s.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, n);
                    }
                }
            }

            /* quick and stupid solution
             * this should have been iterated over an array of stylesheets, really
             */
            using (Stream s = assembly.GetManifestResourceStream(altstylesheet)) {
                using (Stream fs = System.IO.File.Open(SubdirPath("style", altstylesheet), System.IO.FileMode.Create)) {
                    byte [] buffer = new byte [8192];
                    int     n      = 0;
                    while ((n = s.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, n);
                    }
                }
            }

            /* Javascript for persistant style change */
            MakeDir(SubdirPath("script"));
            using (Stream s = assembly.GetManifestResourceStream(javascript)) {
                using (Stream fs = System.IO.File.Open(SubdirPath("script", javascript), System.IO.FileMode.Create)) {
                    byte [] buffer = new byte [8192];
                    int     n      = 0;
                    while ((n = s.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, n);
                    }
                }
            }
        }
示例#56
0
        static public void MainMenu(string additionalMessage, bool clear)
        {
            try
            {
                var settingCheck = GetSetting("qvPath");
            }
            catch
            {
                Console.Clear();
                Console.WriteLine("Something wrong with the setting file");
                Console.Write("Restore to default config? (y/n)");
                string restore = Console.ReadLine();

                if (restore == "y")
                {
                    File.WriteAllBytes("./_config/solution.config.yaml", Properties.Resources.solution_config);
                    Console.Clear();
                    Console.WriteLine("Config file restored. Please start the app again.");
                    Environment.Exit(0);
                }
                else
                {
                    Console.Clear();
                    Console.WriteLine("Bye");
                    Environment.Exit(0);
                }
            }

            //var t = GetSettingNodes("replacements");

            //string script = "testasdasd$(test)testasdasdasd$(test)";

            //foreach (var entry in t.Children)
            //{
            //    string search = entry.Key.ToString();
            //    string replace = entry.Value.ToString();

            //    script = script.Replace(search, @replace);
            //}


            //WebRequest request = WebRequest.Create("https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger");
            //WebResponse response = request.GetResponse();
            //Console.WriteLine(response.ResponseUri);

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            string solutionPath = System.IO.Directory.GetCurrentDirectory().ToString();

            solutionPath = Path.GetFullPath(Path.Combine(solutionPath, @".\src\scripts"));
            string[] availableProjects = Directory.GetDirectories(solutionPath);
            string   selectedProject   = "";

            Console.Clear();
            string welcome = "Wellcome to Qlik Solutions Helper (" + version + ")" + Environment.NewLine + "Enter the needed number or enter 0 to exit in any menu" + Environment.NewLine + "" + Environment.NewLine;

            if (additionalMessage != "")
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(additionalMessage);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine();
            }

            var options = PrintOptions(welcome + "* Main Menu *", new string[] { "1. Add new ...",
                                                                                 "2. Build ...",
                                                                                 "3. Remove ..",
                                                                                 "4. Open step qvw",
                                                                                 "5. Publish" }, clear);


            switch (options)
            {
            case 1:
                options = PrintOptions("* Create *", new string[] { "1. Project to the solution",
                                                                    "2. New step to project" }, clear);


                switch (options)
                {
                case 1:         // new project
                    Console.Write("What is the project name? ");
                    string prjName = Console.ReadLine();

                    string path    = System.IO.Directory.GetCurrentDirectory().ToString();
                    string newPath = Path.GetFullPath(Path.Combine(path, @".\src"));

                    if (System.IO.Directory.Exists(newPath + "\\scripts\\" + prjName))
                    {
                        Console.Write("Project already exists. Overwrite? (y/n): ");
                        string response = Console.ReadLine().ToLower();

                        if (response == "y")
                        {
                            CreatePrjFolders(newPath, prjName, false);
                            MainMenu("Project folders are created", false);
                        }
                        else
                        {
                            MainMenu("", true);
                        }
                    }
                    else
                    {
                        CreatePrjFolders(newPath, prjName, false);
                        MainMenu("Project folders are created", false);
                    }


                    break;

                case 2:         // new step
                    //string solutionPath = System.IO.Directory.GetCurrentDirectory().ToString();
                    //solutionPath = Path.GetFullPath(Path.Combine(solutionPath, @".\src\scripts"));
                    //string[] availableProjects = Directory.GetDirectories(solutionPath);

                    Console.Clear();
                    Console.WriteLine("* Create new step *");
                    Console.WriteLine();

                    for (var i = 0; i < availableProjects.Length; i++)
                    {
                        Console.WriteLine((i + 1) + ". " + new DirectoryInfo(availableProjects[i]).Name);
                    }

                    Console.WriteLine();
                    Console.Write("In which project? ");
                    selectedProject = Console.ReadLine();
                    selectedProject = availableProjects[Convert.ToInt32(selectedProject) - 1];

                    Console.Write("What is the step name? ");
                    string stepName = Console.ReadLine();

                    string[] availablerSteps = Directory.GetDirectories(selectedProject);
                    int      stepId          = -1;
                    string   newStepId       = "0";
                    string   lastStepFolder  = "";

                    if (availablerSteps.Length == 0)
                    {
                        stepId    = 1;
                        newStepId = stepId.ToString("D2");
                        CreatePrjFolders(selectedProject, newStepId + "" + stepName, true);
                    }
                    else
                    {
                        lastStepFolder = new DirectoryInfo(availablerSteps[availablerSteps.Length - 1]).Name;
                        stepId         = int.Parse(lastStepFolder.Substring(0, 2)) + 1;
                        newStepId      = stepId.ToString("D2");
                        CreatePrjFolders(selectedProject, newStepId + "" + stepName, true);
                    }

                    CreateQVW(selectedProject, newStepId + "" + stepName, lastStepFolder);

                    MainMenu("New step was created", false);

                    break;
                }
                break;

            case 2:

                Console.Clear();
                Console.WriteLine("* Build project *");
                Console.WriteLine();

                for (var i = 0; i < availableProjects.Length; i++)
                {
                    Console.WriteLine((i + 1) + ". " + new DirectoryInfo(availableProjects[i]).Name);
                }

                Console.WriteLine();
                Console.Write("Which project? ");
                selectedProject = Console.ReadLine();
                selectedProject = availableProjects[Convert.ToInt32(selectedProject) - 1];
                string[] projectFolders = Directory.GetDirectories(selectedProject);
                string   projectScript  = "";
                string   projectName    = Path.GetFileName(selectedProject);

                for (int i = 0; i < projectFolders.Length; i++)
                {
                    string[] files = System.IO.Directory.GetFiles(projectFolders[i], "*.qvs");
                    if (files.Length > 0)
                    {
                        for (int f = 0; f < files.Length; f++)
                        {
                            string fileName = Path.GetFileNameWithoutExtension(files[f]);
                            projectScript += "///$tab " + fileName;

                            using (StreamReader sr = File.OpenText(files[f]))
                            {
                                string s = String.Empty;
                                while ((s = sr.ReadLine()) != null)
                                {
                                    if (s.ToLower().IndexOf("binary") == -1)
                                    {
                                        projectScript += Environment.NewLine + s + Environment.NewLine;
                                    }
                                }
                            }
                        }
                    }
                }

                File.Copy(projectFolders[projectFolders.Length - 1].Replace(@"\scripts\", @"\qvw\") + ".qvw", @".\build\" + projectName + ".qvw", true);


                string tempScript = projectName + ".qvs";     //Guid.NewGuid().ToString();

                projectScript = Replacements(projectScript);
                File.WriteAllText(@".\temp\" + tempScript, projectScript);

                //Console.WriteLine(@"script_edit.vbs /tempfile:" + Path.GetFullPath(@".\temp\" + tempScript) + " /qvw:" + Path.GetFullPath(@".\build\" + projectName + ".qvw") + " /saveempty:" + "true");
                //Console.ReadLine();

                Console.WriteLine("Building ...");
                Console.WriteLine("(building time depends on the last step qvw open and save time)");
                Process scriptProc = new Process();
                scriptProc.StartInfo.FileName         = @"cscript";
                scriptProc.StartInfo.WorkingDirectory = @".\bin\vbs\";             //<---very important
                scriptProc.StartInfo.Arguments        = @"script_edit.vbs /tempfile:" + Path.GetFullPath(@".\temp\" + tempScript) + " /qvw:" + Path.GetFullPath(@".\build\" + projectName + ".qvw") + " /saveempty:" + "true";
                scriptProc.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden; //prevent console window from popping up
                scriptProc.Start();
                scriptProc.WaitForExit();                                          // <-- Optional if you want program running until your script exit
                scriptProc.Close();

                if (GetSetting("deleteTempScript") == "true")
                {
                    File.Delete(@".\temp\" + tempScript);
                }

                Console.Clear();
                Environment.Exit(0);

                break;

            case 3:
                options = PrintOptions("* Remove *", new string[] { "1. Project",
                                                                    "2. Step from project",
                                                                    "3. Empty all QVW (open without data and save" }, true);
                switch (options)
                {
                case 1:
                    //string solutionPath = System.IO.Directory.GetCurrentDirectory().ToString();
                    //solutionPath = Path.GetFullPath(Path.Combine(solutionPath, @".\src\scripts"));
                    //string[] availableProjects = Directory.GetDirectories(solutionPath);

                    Console.Clear();
                    Console.WriteLine("* Remove project *");
                    Console.WriteLine();

                    for (var i = 0; i < availableProjects.Length; i++)
                    {
                        Console.WriteLine((i + 1) + ". " + new DirectoryInfo(availableProjects[i]).Name);
                    }

                    Console.WriteLine();
                    Console.Write("Which project? ");
                    selectedProject = Console.ReadLine();
                    selectedProject = availableProjects[Convert.ToInt32(selectedProject) - 1];

                    Console.Write("Are you shure? This will remove all qvw, data and script files! (y/n) ");
                    string deleteProjectResponse = Console.ReadLine();

                    if (deleteProjectResponse.ToLower() == "y")
                    {
                        RemoveProject(selectedProject);
                        MainMenu("Project deleted!", false);
                    }
                    else
                    {
                        MainMenu("", true);
                    }

                    break;

                case 2:
                    Console.Clear();
                    Console.WriteLine("* Remove step project *");
                    Console.WriteLine();
                    string[] projects = GetProjects();

                    for (var i = 0; i < projects.Length; i++)
                    {
                        Console.WriteLine((i + 1) + ". " + new DirectoryInfo(projects[i]).Name);
                    }


                    Console.WriteLine();
                    Console.Write("Which project? ");
                    string project = Console.ReadLine();
                    selectedProject = projects[Convert.ToInt32(project) - 1];

                    Console.Clear();
                    Console.WriteLine("* Which step? *");
                    Console.WriteLine();

                    string[] availableSteps = Directory.GetDirectories(selectedProject);

                    for (var i = 0; i < availableSteps.Length; i++)
                    {
                        Console.WriteLine((i + 1) + ". " + new DirectoryInfo(availableSteps[i]).Name);
                    }

                    string step         = Console.ReadLine();
                    string selectedStep = availableSteps[Convert.ToInt32(step) - 1];

                    RemoveStep(selectedStep);

                    break;

                case 3:
                    MainMenu("Not implemented yet", false);
                    break;
                }
                break;

            case 4:
                Console.Clear();
                Console.WriteLine("* Open step qvw *");
                Console.WriteLine();
                string[] avProjects = GetProjects();

                for (var i = 0; i < avProjects.Length; i++)
                {
                    Console.WriteLine((i + 1) + ". " + new DirectoryInfo(avProjects[i]).Name);
                }


                Console.WriteLine();
                Console.Write("Which project? ");
                string projectqvw   = Console.ReadLine();
                string selectedProj = avProjects[Convert.ToInt32(projectqvw) - 1];

                Console.Clear();
                Console.WriteLine("* Which step? *");
                Console.WriteLine();

                string[] availableStepsqvw = Directory.GetDirectories(selectedProj);

                for (var i = 0; i < availableStepsqvw.Length; i++)
                {
                    Console.WriteLine((i + 1) + ". " + new DirectoryInfo(availableStepsqvw[i]).Name);
                }

                string stepqvw         = Console.ReadLine();
                string selectedStepqvw = availableStepsqvw[Convert.ToInt32(stepqvw) - 1];
                selectedStepqvw = selectedStepqvw.Replace("\\scripts\\", "\\qvw\\") + ".qvw";

                var qvPath = GetSetting("qvPath");

                if (qvPath == null)
                {
                    Console.Clear();
                    Console.WriteLine("'qvPath' parameter was not found in config.yaml!");
                    Environment.Exit(0);
                }
                else
                {
                    System.Diagnostics.Process.Start("", selectedStepqvw);
                    MainMenu("", true);
                }


                break;

            case 5:



                break;

            default:
                throw new ArgumentOutOfRangeException("Unknown value");
            }
        }
示例#57
0
        /// <summary>Builds a connection string for an EntityConnection.</summary>
        /// <param name='baseModelName'>Base name for all files (baseModelName.csdl, baseModelName.msl and baseModelName.ssdl)</param>
        /// <param name='connectionString'>Connection string for a provider (specified for ProviderName).</param>
        /// <param name="assembly">Assembly where the model resources are held</param>
        /// <returns>The connection string to be used with <see cref="System.Data.EntityClient.EntityConnection"/>.</returns>
        public static string BuildEntityConnection(string baseModelName, string connectionString, System.Reflection.Assembly assembly)
        {
            string[]      extensions  = new string[] { ".csdl", ".msl", ".ssdl" };
            string        prefix      = String.Empty;
            StringBuilder metaBuilder = new StringBuilder();

            foreach (string extension in extensions)
            {
                metaBuilder.Append(prefix).Append("res://*/").Append(IOUtil.FindResourceNameForPath(assembly, baseModelName + extension));
                prefix = "|";
            }

            System.Data.EntityClient.EntityConnectionStringBuilder builder = new System.Data.EntityClient.EntityConnectionStringBuilder();
            builder.Provider = ProviderName;
            builder.ProviderConnectionString = connectionString;
            builder.Metadata = metaBuilder.ToString();
            return(builder.ConnectionString);
        }
示例#58
0
        public static int LoadPlugIn(string path)
        {
            HostUtils.SendDebugToCommandLine = true;
            HostUtils.DebugString("[MonoHost::LoadPlugIn] Start");
            if (!m_bUsingMono)
            {
                m_bUsingMono = true;
                // Don't turn visual styles on yet, they seem pretty flakey as of
                // Mono 2.4.2
                //System.Windows.Forms.Application.EnableVisualStyles();

                InitializeExceptionHandling();
                HostUtils.InitializeRhinoCommon();

                HostUtils.DebugString("Attempt to initialize MonoMac");
                Type t = typeof(System.Windows.Forms.Application);
                if (t != null)
                {
                    System.Reflection.MethodInfo mi = t.GetMethod("MonoMacInit", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
                    if (mi != null)
                    {
                        HostUtils.DebugString("Got methodinfo for MonoMacInit");
                        mi.Invoke(null, null);
                    }
                }
            }

            // 7 Apr 2013, S. Baer
            // Mac plug-ins can now be located inside of OSX plug-in bundles.
            // The native plug-in manager may just pass us the bundle path
            // See if the path refers to a bundle. If that is the case,
            // look inside the bundle to find the actual assembly
            var temp_path = System.IO.Path.Combine(path, "Contents");

            temp_path = System.IO.Path.Combine(temp_path, "Mono");
            if (System.IO.Directory.Exists(temp_path))
            {
                var files = System.IO.Directory.GetFiles(temp_path, "*.rhp");
                if (files != null && files.Length > 0)
                {
                    path = files[0];
                }
            }

            HostUtils.DebugString("path = " + path);

            // Reflection Load assembly first in order to check versioning
            // and make sure the plug-in hasn't already been loaded
            System.Reflection.Assembly plugin_assembly;
            try
            {
                plugin_assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(path);
            }
            catch (Exception) { plugin_assembly = null; }
            HostUtils.DebugString("ReflectionOnlyLoadFrom succeeded");

            if (null == plugin_assembly)
            {
                return((int)MonoLoadResult.error_not_dotnet);
            }

            //make sure this assembly has not alread been loaded
            for (int i = 0; i < PlugIn.m_plugins.Count; i++)
            {
                System.Reflection.Assembly loadedAssembly = PlugIn.m_plugins[i].Assembly;
                if (string.Compare(loadedAssembly.FullName, plugin_assembly.FullName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return((int)MonoLoadResult.error_already_loaded);
                }
            }

            // Check version of RhinoCommon that this plug-in uses
            // Don't allow plug-ins built against earlier versions of RhinoCommon to load
            bool passesVersionCheck = false;

            try
            {
                System.Reflection.AssemblyName[] referenced_assemblies = plugin_assembly.GetReferencedAssemblies();
                for (int i = 0; i < referenced_assemblies.Length; i++)
                {
                    if (referenced_assemblies[i].Name.Equals("RhinoCommon", StringComparison.OrdinalIgnoreCase))
                    {
                        Version referenced_version = referenced_assemblies[i].Version;
                        Version this_version       = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                        HostUtils.DebugString("Installed RhinoCommon version = {0}", this_version);
                        HostUtils.DebugString("Plug-In built against = {0}", referenced_version);
                        // major and minor MUST match
                        if (referenced_version.Major == this_version.Major && referenced_version.Minor == this_version.Minor)
                        {
                            // At this point the SDK is changing too rapidly to allow for "safe" updates
                            // build of this_version must be == build of referenced version
                            // revision of this_version must be >= build of referenced version
                            if (this_version.Build == referenced_version.Build)
                            {
                                if (this_version.Revision >= referenced_version.Revision)
                                {
                                    passesVersionCheck = true;
                                }
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                HostUtils.DebugString("Exception while checking versions");
                HostUtils.DebugString(ex.Message);
            }
            if (!passesVersionCheck)
            {
                return((int)MonoLoadResult.error_incompatible_version);
            }


            // TODO: Check version of RhinoCommon that this plug-in uses for versioning

            // At this point, we have determined that this is a RhinoCommon plug-in
            // We've done all the checking that we can do without actually loading
            // the DLL ( and resolving links)
            try
            {
                plugin_assembly = System.Reflection.Assembly.LoadFrom(path);
            }
            catch (Exception)
            {
                plugin_assembly = null;
            }
            if (null == plugin_assembly)
            {
                return((int)MonoLoadResult.error_unable_to_load);
            }
            HostUtils.DebugString("Assembly loaded for real... GetExportedTypes");

            Type[] internal_types = null;
            try
            {
                internal_types = plugin_assembly.GetExportedTypes();
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                HostUtils.DebugString("Caught reflection exception");
                Type[] loaded_types = ex.Types;
                if (loaded_types != null)
                {
                    HostUtils.DebugString("Got {0} loaded types", loaded_types.Length);
                    for (int i = 0; i < loaded_types.Length; i++)
                    {
                        Type t = loaded_types[i];
                        if (t != null)
                        {
                            HostUtils.DebugString("{0} - {1}", i, t);
                        }
                    }
                    HostUtils.DebugString(loaded_types.ToString());
                }
                Exception[] e = ex.LoaderExceptions;
                if (e != null)
                {
                    HostUtils.DebugString("Got some loader exceptions");
                    for (int i = 0; i < e.Length; i++)
                    {
                        HostUtils.DebugString(ex.ToString());
                        internal_types = null;
                    }
                }
            }
            catch (Exception ex)
            {
                HostUtils.DebugString("Caught generic exception");
                HostUtils.DebugString(ex.ToString());
                internal_types = null;
                //        HostUtils.ExceptionReport(ex);
            }

            if (null == internal_types)
            {
                return((int)MonoLoadResult.error_unable_to_load);
            }

            HostUtils.DebugString("{0} Exported Types", internal_types.Length);

            // walk through list of exported types and find a single class
            // that derives from PlugIn
            Type plugin_type = typeof(PlugIn);
            int  type_index  = -1;

            try
            {
                for (int i = 0; i < internal_types.Length; i++)
                {
                    if (plugin_type.IsAssignableFrom(internal_types[i]))
                    {
                        if (type_index >= 0)
                        {
                            return((int)MonoLoadResult.error_create_plugin);
                        }
                        type_index = i;
                    }
                }
            }
            catch (Exception ex)
            {
                HostUtils.DebugString("Exception occured while trying to find type that is derived from PlugIn");
                HostUtils.ExceptionReport(ex);
                type_index = -1;
            }
            if (type_index < 0)
            {
                return((int)MonoLoadResult.error_create_plugin);
            }
            plugin_type = internal_types[type_index];
            HostUtils.DebugString("Found type derived from PlugIn  (" + plugin_type.ToString() + ")");

            object[] name = plugin_assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), false);
            string   plugin_name;

            if (name != null && name.Length > 0)
            {
                plugin_name = ((System.Reflection.AssemblyTitleAttribute)name[0]).Title;
            }
            else
            {
                plugin_name = plugin_assembly.GetName().Name;
            }

            string plugin_version = plugin_assembly.GetName().Version.ToString();

            HostUtils.DebugString("  name = {0}; version = {1}", plugin_name, plugin_version);

            object[] descriptionAtts = plugin_assembly.GetCustomAttributes(typeof(PlugInDescriptionAttribute), false);
            if (descriptionAtts != null)
            {
                const int idxAddress      = 0;
                const int idxCountry      = 1;
                const int idxEmail        = 2;
                const int idxFax          = 3;
                const int idxOrganization = 4;
                const int idxPhone        = 5;
                const int idxUpdateUrl    = 6;
                const int idxWebsite      = 7;

                for (int i = 0; i < descriptionAtts.Length; i++)
                {
                    PlugInDescriptionAttribute description = (PlugInDescriptionAttribute)descriptionAtts[i];
                    switch (description.DescriptionType)
                    {
                    case DescriptionType.Address:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxAddress, description.Value);
                        break;

                    case DescriptionType.Country:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxCountry, description.Value);
                        break;

                    case DescriptionType.Email:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxEmail, description.Value);
                        break;

                    case DescriptionType.Fax:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxFax, description.Value);
                        break;

                    case DescriptionType.Organization:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxOrganization, description.Value);
                        break;

                    case DescriptionType.Phone:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxPhone, description.Value);
                        break;

                    case DescriptionType.UpdateUrl:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxUpdateUrl, description.Value);
                        break;

                    case DescriptionType.WebSite:
                        UnsafeNativeMethods.RhMono_SetPlugInLoadString(idxWebsite, description.Value);
                        break;
                    }
                    HostUtils.DebugString("  {0} - {1}", description.DescriptionType, description.Value);
                }
            }

            PlugIn plugin = PlugIn.Create(plugin_type, plugin_name, plugin_version);

            if (plugin == null)
            {
                return((int)MonoLoadResult.error_create_plugin);
            }

            // We've created a plug-in so we're pretty committed at this point
            PlugIn.m_plugins.Add(plugin);

            // create all commands in the plug-in
            HostUtils.CreateCommands(plugin);
            HostUtils.DebugString("Created {0} commands", plugin.GetCommands().Length);
            HostUtils.DebugString("[MonoHost::LoadPlugIn] - DONE");

            return((int)MonoLoadResult.success);
        }
示例#59
0
    /// <summary>
    /// Returns the license client assembly.
    /// </summary>
    private static System.Reflection.Assembly GetLicenseClientAssembly()
    {
      try
      {
        if (null == m_license_client_assembly)
        {
          const string filename = "ZooClient.dll";
          System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();
          if (thisAssembly != null)
          {
            string path = thisAssembly.Location;
            path = System.IO.Path.GetDirectoryName(path);
            path = string.IsNullOrEmpty(path) ? filename : System.IO.Path.Combine(path, filename);
            if (System.IO.File.Exists(path))
            {
              m_license_client_assembly = System.Reflection.Assembly.LoadFrom(path);
            }
          }
        }
        return m_license_client_assembly;
      }
      catch (Exception ex)
      {
        Rhino.Runtime.HostUtils.ExceptionReport(ex);
      }

      return null;
    }
示例#60
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public FileResourceProvider(string baseName, System.Reflection.Assembly assembly)
     : base(baseName, assembly)
 {
 }