コード例 #1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// a factory method for RecordFilterListProvider
        /// </summary>
        /// <param name="mediator">The mediator.</param>
        /// <param name="propertyTable">The property table</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        static public RecordFilterListProvider Create(Mediator mediator, PropertyTable propertyTable, XmlNode configuration)
        {
            RecordFilterListProvider p = (RecordFilterListProvider)DynamicLoader.CreateObject(configuration);

            if (p != null)
            {
                p.Init(mediator, propertyTable, configuration);
            }
            return(p);
        }
コード例 #2
0
    private void OnTrackingFound()
    {
        DynamicLoader dynamicLoader = FindObjectOfType <DynamicLoader>();
        int           n             = 0;
        bool          isNumeric     = Int32.TryParse(trackableBehaviour.TrackableName, out n);

        if (isNumeric)
        {
            dynamicLoader.getMolekule(n);
        }
    }
コード例 #3
0
        public override bool CompatibleFilter(XmlNode colSpec)
        {
            if (!base.CompatibleFilter(colSpec))
            {
                return(false);
            }
            var typeForLoaderNode = DynamicLoader.TypeForLoaderNode(colSpec);

            // Naturally we are compatible with ourself, and BulkPosEditor has a FilterType which causes
            // a filter of this type to be created, too.
            return(typeForLoaderNode == typeof(BulkPosEditor) || typeForLoaderNode == typeof(PosFilter));
        }
コード例 #4
0
        private void DynamicLoader_OnDynamicLoad(DynamicLoadingState state, DynamicLoader loader, Node node)
        {
            // Locked in edit or render (render) by caller

            if (state == DynamicLoadingState.LOADED || state == DynamicLoadingState.UNLOADED)
            {
                pendingLoaders.Add(new NodeLoadInfo(state, loader, node));
            }
            else
            {
                loader?.ReleaseNoDelete();      // Same here. We are getting refs to objects in scene graph that we shouldnt release in GC
                node?.ReleaseNoDelete();
            }
        }
コード例 #5
0
        /// <summary>
        /// Install a virtual property (often a subclass implementation) from specified XML. Return the tag.
        /// </summary>
        public static int InstallVirtual(FdoCache cache, string source)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(source);
            XmlNode virtualNode = doc.DocumentElement;
            // This one is used so widely we will create it here if not already done.
            IVwVirtualHandler vh = (IVwVirtualHandler)DynamicLoader.CreateObject(
                virtualNode.SelectSingleNode("dynamicloaderinfo"),
                new object[] { virtualNode, cache });

            cache.VwCacheDaAccessor.InstallVirtual(vh);
            return(vh.Tag);
        }
コード例 #6
0
ファイル: Platform.cs プロジェクト: Hengle/Streaming_Map_Demo
            public static bool UnInitialize(bool forceShutdown = false, bool shutdownBase = false)
            {
                NodeLock.WaitLockEdit();

                DynamicLoader.UnInitialize();

                UnInitializeFactories();

                NodeLock.UnLock();

                bool result = Platform_uninitialize(forceShutdown, shutdownBase);

                return(result);
            }
コード例 #7
0
        private GameObject ProcessDynamicLoaderNode(DynamicLoader node, NodeHandle nodeHandle)
        {
            // Possibly we can add action interfaces for dyn load childs as they will get traversable if they have node actons
            if (NodeUtils.FindGameObjectsUnsafe(node.GetNativeReference(), out List <GameObject> list))
            {
                return(list[0]); // We are already in list, lets return first object wich is our main registered node
            }
            // We are not registered
            NodeUtils.AddGameObjectReferenceUnsafe(node.GetNativeReference(), nodeHandle.gameObject);

            nodeHandle.inNodeUtilsRegistry = true;  // Added to registry

            return(null);
        }
コード例 #8
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Incorrect syntax. Provide file for transactions.");
                return;
            }

            // read input file name
            var transactionFilePath = args[0];

            // retrieve root factory and context objects from implementing assembly

            // note that "MobilePay.MerchantFeesCalculator.BasicImplementation.dll" is implemented all internal so that
            // client applications would use API to access the transaction fee computation objects
            var factory = DynamicLoader.LoadModuleType <IMerchantFeesCalculatorFactory>(
                "MobilePay.MerchantFeesCalculator.BasicImplementation.dll");
            var context = DynamicLoader.LoadModuleType <ITransactionContext>(
                "MobilePay.MerchantFeesCalculator.BasicImplementation.dll");

            // generate application objects from implementing assembly
            var source          = factory.CreateTextBasedTransactionSource(transactionFilePath);
            var sourceFormat    = factory.CreateTransactionInputFormat();
            var outputWriter    = factory.CreateOutputWriter();
            var outputFormatter = factory.CreateOutputFormatter();

            // TODO: the fixed 29DKK fee could be refactored into separate object to and implemented
            // TODO: in more elegant fashion as discounts below
            var feeCalculator = factory.CreateTransactionFeeCalculator(29);

            // apply discounts to major companies
            context.ApplyDiscount("TELIA", factory.CreatePercentageDiscount(10));
            context.ApplyDiscount("CIRCLE_K", factory.CreatePercentageDiscount(20));

            // fetch transactions - lazy load
            foreach (var transaction in source.FetchTransactions(sourceFormat, context))
            {
                // log transaction into the system
                context.LogTransaction(transaction);

                // compute the fee
                var fee = feeCalculator.Compute(transaction, context);

                // output
                outputWriter.Write(fee, outputFormatter);
            }

            Console.ReadKey();
        }
コード例 #9
0
ファイル: QuantFund.cs プロジェクト: w1r2p1/Core-2
        /// <summary>
        /// Initializes the specified assembly.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="fundinfo">The fundinfo.</param>
        public void Initialize(Assembly assembly, AddFundMessage fundinfo)
        {
            try
            {
                //Set state
                State = FundState.Initializing;

                //Set fund universe
                Universe = Universe.Create(fundinfo.UniverseName, Portfolio.BrokerAccount.Securities, fundinfo.Universe);

                //Set fund modules
                foreach (var modulename in fundinfo.ModuleNames)
                {
                    //Try and get the module instance
                    if (!DynamicLoader.TryGetInstance(assembly, modulename, out IModule instance))
                    {
                        throw new Exception($"Could not find module {modulename} in provided assembly. Did you add the export attribute?");
                    }

                    //Set quantfund
                    instance.SetQuantFund(this);

                    //Set parameters
                    fundinfo.Parameters.Where(x => x.ModuleName == modulename)
                    .ForEach(parm => instance.SetParameter(parm.Name, parm.Value));

                    //Add to modules
                    _modules.Add(instance);
                }

                //Set universe to position tracker
                Positions.SetUniverse(Universe.Securities.Select(x => x.Ticker).ToArray());

                //Set benchmark
                Benchmark.OnCalc(x => Universe.Sum(s => s.Price * Universe.GetWeight(s)));

                //Subscribe to all ticker symbols by default
                Universe.ForEach(x => Portfolio.Subscription.AddSubscription(this, x, new TickQuoteBarAggregator(TimeSpan.FromMinutes(1)), fundinfo.ForceTick));

                //Initialize all modules
                _modules.ForEach(m => m.Initialize());
            }
            catch (Exception exc)
            {
                _log.Error(exc, $"Could not initialize quant fund with name {Name} due to error: {exc.Message}");
                Portfolio.ExceptionHandler.HandleException(exc, FundId);
                State = FundState.DeployError;
            }
        }
コード例 #10
0
        public void SortersEtc()
        {
            PropertyRecordSorter prs = new PropertyRecordSorter("longName");
            // Save and restore!
            string      xml = DynamicLoader.PersistObject(prs, "sorter");
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);

            // And check all the pieces...
            PropertyRecordSorter prsOut = DynamicLoader.RestoreObject(doc.DocumentElement) as PropertyRecordSorter;

            prsOut.Cache = Cache;
            Assert.AreEqual("longName", prsOut.PropertyName);
        }
コード例 #11
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlSeqView"/> class.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public XmlSeqView(FdoCache cache, int hvoRoot, int flid, XmlNode xnSpec, ISilDataAccessManaged sda, IApp app, ICmPossibility publication)
            : base(null)
        {
            m_app = app;
            var useSda        = sda;
            var decoratorSpec = XmlUtils.FindNode(xnSpec, "decoratorClass");

            if (decoratorSpec != null)
            {
                // For example, this may create a DictionaryPublicationDecorator.
                useSda = (ISilDataAccessManaged)DynamicLoader.CreateObject(decoratorSpec,
                                                                           new object[] { cache, sda, flid, publication });
            }
            InitXmlViewRootSpec(hvoRoot, flid, xnSpec, useSda);
        }
コード例 #12
0
        static public RecordBarHandler Create(Mediator mediator, PropertyTable propertyTable, XmlNode toolConfiguration)
        {
            RecordBarHandler handler;
            XmlNode          node = toolConfiguration.SelectSingleNode("treeBarHandler");

            if (node == null)
            {
                handler = new RecordBarListHandler();
            }
            else
            {
                handler = (TreeBarHandler)DynamicLoader.CreateObject(node);
            }
            handler.Init(mediator, propertyTable, node);
            return(handler);
        }
コード例 #13
0
        /// <summary>
        /// Looks for a node called "virtuals" and under it collects nodes of type "virtual",
        /// each having at least "modelclass", "virtualfield", "assemblyPath", and "class".
        /// Here 'class' is the name of the C# class that implements the VH, while 'modelclass'
        /// is the name of the virtual property. The node is passed to the VH as a constructor
        /// argument, so other attributes may be required.
        /// </summary>
        /// <returns>the list of installed virtual handlers</returns>
        public static List <IVwVirtualHandler> InstallVirtuals(XmlNode virtualsNode, FdoCache cache, bool okToFail)
        {
            List <IVwVirtualHandler> installedHandlers = new List <IVwVirtualHandler>();

            foreach (XmlNode virtualNode in virtualsNode.SelectNodes("virtual"))
            {
                IVwCacheDa        cda = cache.MainCacheAccessor as IVwCacheDa;
                IVwVirtualHandler vh  = cda.GetVirtualHandlerName(
                    XmlUtils.GetManditoryAttributeValue(virtualNode, "modelclass"),
                    XmlUtils.GetManditoryAttributeValue(virtualNode, "virtualfield"));
                if (vh != null && vh is BaseVirtualHandler)
                {
                    // already exists, hope it's the same one. Make sure its cache is valid.
                    (vh as BaseVirtualHandler).Reinitialize(virtualNode, cache);
                    installedHandlers.Add(vh);
                    continue;
                }

                try
                {
                    vh = (IVwVirtualHandler)DynamicLoader.CreateObject(
                        virtualNode.SelectSingleNode("dynamicloaderinfo"),
                        new object[] { virtualNode, cache });
                }
                catch (Exception err)
                {
                    if (!okToFail)
                    {
                        throw err;
                    }
                    // Otherwise we're in some special test situation or really just want the IText ones
                    // and we ignore the problem.
                    continue;
                }
                try
                {
                    cda.InstallVirtual(vh);
                }
                catch (Exception err)
                {
                    Debug.WriteLine(err.Message);
                    throw err;
                }
                installedHandlers.Add(vh);
            }
            return(installedHandlers);
        }
コード例 #14
0
ファイル: TestPersistence.cs プロジェクト: sillsdev/WorldPad
        public void PersistSimpleSorter()
        {
            IcuComparer     icomp = new IcuComparer("fr");
            GenRecordSorter grs   = new GenRecordSorter(icomp);
            string          xml   = DynamicLoader.PersistObject(grs, "sorter");
            XmlDocument     doc   = new XmlDocument();

            doc.LoadXml(xml);
            Assert.AreEqual("sorter", doc.DocumentElement.Name);
            object obj = DynamicLoader.RestoreObject(doc.DocumentElement);

            Assert.IsTrue(obj is GenRecordSorter);
            GenRecordSorter grsOut  = obj as GenRecordSorter;
            IComparer       compOut = grsOut.Comparer;

            Assert.IsTrue(compOut is IcuComparer);
            Assert.AreEqual("fr", (compOut as IcuComparer).WsCode);
        }
コード例 #15
0
ファイル: Platform.cs プロジェクト: Hengle/Streaming_Map_Demo
            public static bool Initialize()
            {
                bool result = GizmoBase.Platform.Initialize();

                if (result)
                {
                    result = Platform_initialize();
                }

                if (result)
                {
                    InitializeFactories();
                }

                DynamicLoader.Initialize();

                return(result);
            }
コード例 #16
0
ファイル: RecordEditView.cs プロジェクト: scottsds/FieldWorks
        private XmlDocView CreateDocView(XmlNode parentConfigNode)
        {
            Debug.Assert(parentConfigNode != null,
                         "Can't create a view without the XML control configuration.");
            XmlDocView docView;

            try
            {
                docView = (XmlDocView)DynamicLoader.CreateObjectUsingLoaderNode(parentConfigNode);
            }
            catch (Exception e)
            {
                return(null);
            }
            // TODO: Not right yet!
            docView.Init(m_mediator, parentConfigNode.SelectSingleNode("parameters"));
            return(docView);
        }
コード例 #17
0
        public bool InitializeInternal()
        {
            _actionReceiver = new NodeAction("DynamicLoadManager");

            _actionReceiver.OnAction += ActionReceiver_OnAction;

            _zflipMatrix = new Matrix4x4(new Vector4(1, 0, 0), new Vector4(0, 1, 0), new Vector4(0, 0, -1), new Vector4(0, 0, 0, 1));

            GizmoSDK.GizmoBase.Message.Send("SceneManager", MessageLevel.DEBUG, "Loading Graph");

            NodeLock.WaitLockEdit();

            try // We are now locked in edit
            {
                _native_camera              = new PerspCamera("Test");
                _native_camera.RoiPosition  = true;
                MapControl.SystemMap.Camera = _native_camera;

                _native_scene = new Scene("TestScene");

                _native_context = new Context();

#if DEBUG_CAMERA
                _native_camera.Debug(_native_context);      // Enable to debug view
#endif // DEBUG_CAMERA

                _native_traverse_action = new CullTraverseAction();

                DynamicLoader.OnDynamicLoad += DynamicLoader_OnDynamicLoad;

                _native_camera.Scene = _native_scene;
            }
            finally
            {
                NodeLock.UnLock();
            }


            DynamicLoader.UsePreCache(true);                    // Enable use of mipmap creation on dynamic loading
            DynamicLoaderManager.SetNumberOfActiveLoaders(4);   // Lets start with 4 parallell threads
            DynamicLoaderManager.StartManager();

            return(true);
        }
コード例 #18
0
ファイル: Platform.cs プロジェクト: Hengle/Streaming_Map_Demo
 static public void UnInitializeFactories()
 {
     Node.UnInitializeFactory();
     Group.UnInitializeFactory();
     Transform.UnInitializeFactory();
     Lod.UnInitializeFactory();
     State.UnInitializeFactory();
     Geometry.UnInitializeFactory();
     Scene.UnInitializeFactory();
     PerspCamera.UnInitializeFactory();
     DynamicLoader.UnInitializeFactory();
     CullTraverseAction.UnInitializeFactory();
     NodeAction.UnInitializeFactory();
     Context.UnInitializeFactory();
     Texture.UnInitializeFactory();
     Roi.UnInitializeFactory();
     RoiNode.UnInitializeFactory();
     ExtRef.UnInitializeFactory();
 }
コード例 #19
0
        public void SetDlgInfo(Mediator mediator, XmlNode configurationParameters)
        {
            CheckDisposed();

            Debug.Assert(mediator != null);
            Debug.Assert(configurationParameters != null);

            m_mediator = mediator;
            // <parameters title="FieldWorks Project Utilities" filename="Language Explorer\Configuration\UtilityCatalogInclude.xml"/>
            this.Text = XmlUtils.GetLocalizedAttributeValue(mediator.StringTbl, configurationParameters,
                                                            "title", "FieldWorks Project Utilities");
            string utilsPathname = Path.Combine(FwDirectoryFinder.CodeDirectory,
                                                XmlUtils.GetManditoryAttributeValue(configurationParameters, "filename"));
            // Get the folder path:
            string utilsFolderName = Path.GetDirectoryName(utilsPathname);
            // Get the file name:
            string utilsFileName = Path.GetFileName(utilsPathname);
            // Insert an asterisk before the ".XML" so we can search for similar files:
            string searchPattern = utilsFileName.Replace(".", "*.");

            string[] files = Directory.GetFiles(utilsFolderName, searchPattern, SearchOption.TopDirectoryOnly);
            foreach (string pathname in files)
            {
                XmlDocument document = new XmlDocument();
                document.Load(pathname);
                foreach (XmlNode node in document.SelectNodes("utilityCatalog/utility"))
                {
                    /*
                     * <utilityCatalog>
                     *      <utility assemblyPath="LexEdDll.dll" class="SIL.FieldWorks.XWorks.LexEd.HomographResetter"/>
                     * </utilityCatalog>
                     */
                    IUtility util = DynamicLoader.CreateObject(node) as IUtility;
                    util.Dialog = this;                     // Must be set before adding it to the control.
                    util.LoadUtilities();
                }
            }
            m_clbUtilities.Sorted = true;
            if (m_clbUtilities.Items.Count > 0)
            {
                m_clbUtilities.SelectedIndex = 0;
            }
        }
コード例 #20
0
        private void DynamicLoader_OnDynamicLoad(DynamicLoadingState state, DynamicLoader loader, Node node)
        {
            // Locked in edit or render (render) by caller

            if (state == DynamicLoadingState.LOADED || state == DynamicLoadingState.UNLOADED)
            {
                //if(node != null && node.IsValid())
                //    Message.Send("Unity", MessageLevel.DEBUG, state + " " + node.GetName());
                //else if (loader != null && loader.IsValid())
                //    Message.Send("Unity", MessageLevel.DEBUG, state + " " + loader.GetName());

                pendingLoaders.Add(new NodeLoadInfo(state, loader, node));
            }
            else
            {
                loader?.ReleaseNoDelete();      // Same here. We are getting refs to objects in scene graph that we shouldnt release in GC
                node?.ReleaseNoDelete();
            }
        }
コード例 #21
0
        /// <summary>
        /// In SE Fieldworks we can't depend upon ScrControls.dll We need some decoupling to
        /// prevent the linker from trying to load ScrControls.dll and crashing.
        /// This seems to work. (Although I wonder if we could get away with just calling this method
        /// if IsTEInstalled?)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void LaunchFilterTextsDialog(object sender, EventArgs args)
        {
            IFilterTextsDialog <IStText> dlg = null;

            try
            {
                var interestingTextsList = InterestingTextsDecorator.GetInterestingTextList(m_mediator, m_cache.ServiceLocator);
                var textsToChooseFrom    = new List <IStText>(interestingTextsList.InterestingTexts);
                if (!FwUtils.IsTEInstalled)
                {                   // TE is not installed, so remove scripture from the list
                    textsToChooseFrom = textsToChooseFrom.Where(text => !ScriptureServices.ScriptureIsResponsibleFor(text)).ToList();
                }
                var interestingTexts = textsToChooseFrom.ToArray();
                if (FwUtils.IsTEInstalled)
                {
                    dlg = (IFilterTextsDialog <IStText>)DynamicLoader.CreateObject(
                        "ScrControls.dll", "SIL.FieldWorks.Common.Controls.FilterTextsDialogTE",
                        m_cache, interestingTexts, m_mediator.HelpTopicProvider, m_bookImporter);
                }
                else
                {
                    dlg = new FilterTextsDialog(m_cache, interestingTexts, m_mediator.HelpTopicProvider);
                }
                // LT-12181: Was 'PruneToSelectedTexts(text) and most others were deleted.
                // We want 'PruneToInterestingTextsAndSelect(interestingTexts, selectedText)'
                dlg.PruneToInterestingTextsAndSelect(interestingTexts, (IStText)m_objRoot);
                // LT-12140 Dialog name shouldn't change from Choose Texts
                //dlg.Text = ITextStrings.ksExportInterlinearizedTexts;
                dlg.TreeViewLabel = ITextStrings.ksSelectSectionsExported;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    m_objs.AddRange(dlg.GetListOfIncludedTexts());
                }
            }
            finally
            {
                if (dlg != null)
                {
                    ((IDisposable)dlg).Dispose();
                }
            }
        }
コード例 #22
0
        public void TestSimpleFormatter()
        {
            var factory = DynamicLoader.LoadModuleType <IMerchantFeesCalculatorFactory>(
                "MobilePay.MerchantFeesCalculator.BasicImplementation.dll");
            var formatter = factory.CreateOutputFormatter();

            var transactionMock = new Moq.Mock <ITransaction>();

            transactionMock.SetupGet(m => m.Amount).Returns(100m);

            var transactionFeeMock = new Moq.Mock <ITransactionFee>();

            transactionFeeMock.SetupGet(m => m.Transaction.Date).Returns(DateTime.Parse("2001-02-03"));
            transactionFeeMock.SetupGet(m => m.Transaction.Merchant.Name).Returns("NORFA");
            transactionFeeMock.SetupGet(m => m.Value).Returns(20);

            var line = formatter.Format(transactionFeeMock.Object);

            Assert.AreEqual("2001-02-03 NORFA      $20.00", line);
        }
コード例 #23
0
        private void ReadParameters()
        {
            m_sRegKeyName          = XmlUtils.GetManditoryAttributeValue(m_configurationParameters, "regKeyName");
            m_sProgressDialogTitle = XmlUtils.GetManditoryAttributeValue(m_configurationParameters, "dialogTitle");
            m_sFileNameKey         = XmlUtils.GetManditoryAttributeValue(m_configurationParameters, "fileNameKey");
            m_sStringsPath         = XmlUtils.GetManditoryAttributeValue(m_configurationParameters, "stringsPath");

            foreach (XmlNode rNode in m_configurationParameters.ChildNodes)
            {
                if (rNode.Name == "retriever")
                {
                    m_retrieverNode = rNode;
                    m_retriever     = (IDataRetriever)DynamicLoader.CreateObject(m_retrieverNode.SelectSingleNode("dynamicloaderinfo"));
                }
                else if (rNode.Name == "transforms")
                {
                    m_transformsNode = rNode;
                }
            }
        }
コード例 #24
0
 static public void InitializeFactories()
 {
     Node.InitializeFactory();
     Group.InitializeFactory();
     Transform.InitializeFactory();
     Lod.InitializeFactory();
     State.InitializeFactory();
     Geometry.InitializeFactory();
     Scene.InitializeFactory();
     PerspCamera.InitializeFactory();
     DynamicLoader.InitializeFactory();
     CullTraverseAction.InitializeFactory();
     NodeAction.InitializeFactory();
     Context.InitializeFactory();
     Texture.InitializeFactory();
     Roi.InitializeFactory();
     RoiNode.InitializeFactory();
     ExtRef.InitializeFactory();
     Crossboard.InitializeFactory();
 }
コード例 #25
0
        private void AddConfigurableControls()
        {
            // Load the controls.

            // 1. Initialize the preview pane (lower pane)
            m_previewPane            = new XmlView(0, "publicationNew", false);
            m_previewPane.Cache      = m_cache;
            m_previewPane.StyleSheet = FontHeightAdjuster.StyleSheetFromPropertyTable(m_propertyTable);

            BasicPaneBarContainer pbc = new BasicPaneBarContainer();

            pbc.Init(m_mediator, m_propertyTable, m_previewPane);
            pbc.Dock         = DockStyle.Fill;
            pbc.PaneBar.Text = LexEdStrings.ksFindExampleSentenceDlgPreviewPaneTitle;
            panel2.Controls.Add(pbc);
            if (m_previewPane.RootBox == null)
            {
                m_previewPane.MakeRoot();
            }

            // 2. load the browse view. (upper pane)
            XmlNode xnBrowseViewControlParameters = this.BrowseViewControlParameters;

            // First create our Clerk, since we can't set it's OwningObject via the configuration/mediator/PropertyTable info.
            m_clerk = RecordClerkFactory.CreateClerk(m_mediator, m_propertyTable, xnBrowseViewControlParameters, true);
            m_clerk.OwningObject = m_owningSense;

            m_rbv = DynamicLoader.CreateObject(xnBrowseViewControlParameters.ParentNode.SelectSingleNode("dynamicloaderinfo")) as ConcOccurrenceBrowseView;
            m_rbv.Init(m_mediator, m_propertyTable, xnBrowseViewControlParameters, m_previewPane, m_clerk.VirtualListPublisher);
            m_rbv.CheckBoxChanged += m_rbv_CheckBoxChanged;
            // add it to our controls.
            BasicPaneBarContainer pbc1 = new BasicPaneBarContainer();

            pbc1.Init(m_mediator, m_propertyTable, m_rbv);
            pbc1.BorderStyle  = BorderStyle.FixedSingle;
            pbc1.Dock         = DockStyle.Fill;
            pbc1.PaneBar.Text = LexEdStrings.ksFindExampleSentenceDlgBrowseViewPaneTitle;
            panel1.Controls.Add(pbc1);

            CheckAddBtnEnabling();
        }
コード例 #26
0
        static public RecordBarHandler Create(XCore.Mediator mediator, XmlNode toolConfiguration)
        {
            RecordBarHandler handler = null;
            XmlNode          node    = toolConfiguration.SelectSingleNode("treeBarHandler");

            //if (node != null)
            //{
            //    handler = (TreeBarHandler)DynamicLoader.CreateObject(node);
            //    handler.Init(mediator, node);
            //}
            if (node == null)
            {
                handler = new RecordBarListHandler();
            }
            else
            {
                handler = (TreeBarHandler)DynamicLoader.CreateObject(node);
            }
            handler.Init(mediator, node);
            return(handler);
        }
コード例 #27
0
        public void TestCase1(string implementerAssemblyName)
        {
            var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var factory = DynamicLoader.LoadModuleType <IMerchantFeesCalculatorFactory>(Path.Combine(assemblyPath, implementerAssemblyName));
            var context = DynamicLoader.LoadModuleType <ITransactionContext>(Path.Combine(assemblyPath, implementerAssemblyName));

            var source          = new TestHelper();
            var outputWriter    = source;
            var sourceFormat    = factory.CreateTransactionInputFormat();
            var feeCalculator   = factory.CreateTransactionFeeCalculator(0);
            var outputFormatter = factory.CreateOutputFormatter();

            foreach (var transaction in source.FetchTransactions(sourceFormat, context))
            {
                context.LogTransaction(transaction);

                var fee = feeCalculator.Compute(transaction, context);
                outputWriter.Write(fee, outputFormatter);
            }
        }
コード例 #28
0
        private static void LibraryInit()
        {
            // Load the library.
            DynamicLoader.LoadLibrary(libraryPath);

            // Create a logger with outputs to sys.stderr
            RealVNC.VncSdk.Logger.CreateStderrLogger();

            // Create a file DataStore for storing persistent data for the viewer.
            // Ideally this would be created in a directory that only the viewer
            // user has access to.
            DataStore.CreateFileStore("dataStore.txt");

            // Now initialise the library proper.
            Library.Init();

            if (!string.IsNullOrEmpty(DirectTcpAddOnCode))
            {
                Library.EnableAddOn(DirectTcpAddOnCode);
            }
        }
コード例 #29
0
    //
    // Kompilierung durch mcs-Compiler
    //
    public AssemblyBuilder Compile(AppDomain domain, bool generateInMemory)
    {
        Debug.Log("Aufruf Compiler");

        //settings.SourceFiles des CompilerContextes hält alle dll's und das noch zu kompilierende Script
        CompilerSettings settings = compilerContext.Settings;
        AssemblyBuilder  assembly = null;
        ModuleContainer  module   = new ModuleContainer(compilerContext);

        Parse(module);

        //benötigte Klassen die in der Compile-Methode des mcs Compiler enthalten sind
        AssemblyDefinitionDynamic assemblyDef = new AssemblyDefinitionDynamic(module, settings.OutputFile, settings.OutputFile);

        module.SetDeclaringAssembly(assemblyDef);

        ReflectionImporter importer = new ReflectionImporter(module, compilerContext.BuiltinTypes);

        assemblyDef.Importer = importer;

        DynamicLoader loader = new DynamicLoader(importer, compilerContext);

        loader.LoadReferences(module);

        compilerContext.BuiltinTypes.CheckDefinitions(module);
        assemblyDef.Create(domain, AssemblyBuilderAccess.RunAndSave);

        module.CreateContainer();
        loader.LoadModules(assemblyDef, module.GlobalRootNamespace);
        module.InitializePredefinedTypes();

        module.Define();
        assemblyDef.Resolve();
        assemblyDef.Emit();
        module.CloseContainer();

        return(assemblyDef.Builder);
    }
コード例 #30
0
ファイル: TestPersistence.cs プロジェクト: sillsdev/WorldPad
        public void SortersEtc()
        {
            PropertyRecordSorter prs = new PropertyRecordSorter("longName");
            // Save and restore!
            string      xml = DynamicLoader.PersistObject(prs, "sorter");
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);

            // And check all the pieces...
            PropertyRecordSorter prsOut = DynamicLoader.RestoreObject(doc.DocumentElement) as PropertyRecordSorter;

            prsOut.Cache = m_cache;
            Assert.AreEqual("longName", prsOut.PropertyName);

            // Putting an IntStringComparer here is utterly bizarre, but it tests out one more class.
            StringFinderCompare sfComp = new StringFinderCompare(new OwnMonoPropFinder(m_cache.MainCacheAccessor, 445),
                                                                 new ReverseComparer(new IntStringComparer()));

            sfComp.SortedFromEnd = true;
            // Save and restore!
            xml = DynamicLoader.PersistObject(sfComp, "comparer");
            doc = new XmlDocument();
            doc.LoadXml(xml);
            // And check all the pieces...
            StringFinderCompare sfCompOut = DynamicLoader.RestoreObject(doc.DocumentElement) as StringFinderCompare;

            sfCompOut.Cache = m_cache;

            Assert.IsTrue(sfCompOut.Finder is OwnMonoPropFinder);
            Assert.IsTrue(sfCompOut.SubComparer is ReverseComparer);
            Assert.IsTrue(sfCompOut.SortedFromEnd);

            ReverseComparer rcOut = sfCompOut.SubComparer as ReverseComparer;

            Assert.IsTrue(rcOut.SubComp is IntStringComparer);
        }
コード例 #31
0
ファイル: PlatformManager.cs プロジェクト: WolfgangSt/axiom
		/// <summary>
		///     Internal constructor.  This class cannot be instantiated externally.
		/// </summary>
		internal PlatformManager()
		{
			// First look in current Executing assembly for a PlatformManager
			if ( instance == null )
			{
				DynamicLoader platformMgr = new DynamicLoader();
				IList<ObjectCreator> platforms = platformMgr.Find( typeof( IPlatformManager ) );
				if ( platforms.Count != 0 )
				{
					instance = platformMgr.Find( typeof( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
				}
			}

#if !( XBOX || XBOX360 )
			// Then look in loaded assemblies
			if ( instance == null )
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				for ( int index = 0; index < assemblies.Length && instance == null; index++ )
				{
					//TODO: NRSC Added: Deal with Dynamic Assemblies not having a Location
                    //if (assemblies[index].IsDynamic)
                    //    continue;
					try {
					DynamicLoader platformMgr = new DynamicLoader( assemblies[ index ].Location );
					IList<ObjectCreator> platforms = platformMgr.Find( typeof( IPlatformManager ) );
					if ( platforms.Count != 0 )
					{
						instance = platformMgr.Find( typeof( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
					}
					} catch (Exception)
					{
					    System.Diagnostics.Debug.WriteLine( String.Format( "Failed to load assembly: {0}.", assemblies[index].FullName ) );	
					}
				}
			}
#endif

			// Then look in external assemblies
			if ( instance == null )
			{
				// find and load a platform manager assembly
				string[] files = Directory.GetFiles( ".", "Axiom.Platforms.*.dll" );
				string file = "";

				// make sure there is 1 platform manager available
				if ( files.Length == 0 )
				{
					throw new PluginException( "A PlatformManager was not found in the execution path, and is required." );
				}
				else
				{
					bool isWindows = IsWindowsOS;
					string platform = IsWindowsOS ? "Win32" : "OpenTK";

					if ( files.Length == 1 )
					{
						file = files[ 0 ];
					}
					else
					{
						for ( int i = 0; i < files.Length; i++ )
						{
							if ( ( files[ i ].IndexOf( platform ) != -1 ) == true )
							{
								file = files[ i ];
							}
						}
					}

					System.Diagnostics.Debug.WriteLine( String.Format( "Selected the PlatformManager contained in {0}.", file ) );
				}

				string path = Path.Combine( System.IO.Directory.GetCurrentDirectory(), file );

				DynamicLoader platformMgr = new DynamicLoader( path );
				IList<ObjectCreator> platforms = platformMgr.Find( typeof( IPlatformManager ) );
				if ( platforms.Count != 0 )
				{
					instance = platformMgr.Find( typeof( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
				}

			}

			// All else fails, yell loudly
			if ( instance == null )
				throw new PluginException( "The available Platform assembly did not contain any subclasses of PlatformManager, which is required." );
		}
コード例 #32
0
ファイル: driver.cs プロジェクト: furesoft/NRefactory
		//
		// Main compilation method
		//
		public bool Compile ()
		{
			var settings = ctx.Settings;

			//
			// If we are an exe, require a source file for the entry point or
			// if there is nothing to put in the assembly, and we are not a library
			//
			if (settings.FirstSourceFile == null &&
				((settings.Target == Target.Exe || settings.Target == Target.WinExe || settings.Target == Target.Module) ||
				settings.Resources == null)) {
				Report.Error (2008, "No files to compile were specified");
				return false;
			}

			if (settings.Platform == Platform.AnyCPU32Preferred && (settings.Target == Target.Library || settings.Target == Target.Module)) {
				Report.Error (4023, "Platform option `anycpu32bitpreferred' is valid only for executables");
				return false;
			}

			TimeReporter tr = new TimeReporter (settings.Timestamps);
			ctx.TimeReporter = tr;
			tr.StartTotal ();

			var module = new ModuleContainer (ctx);
			RootContext.ToplevelTypes = module;

			tr.Start (TimeReporter.TimerType.ParseTotal);
			Parse (module);
			tr.Stop (TimeReporter.TimerType.ParseTotal);

			if (Report.Errors > 0)
				return false;

			if (settings.TokenizeOnly || settings.ParseOnly) {
				tr.StopTotal ();
				tr.ShowStats ();
				return true;
			}

			var output_file = settings.OutputFile;
			string output_file_name;
			if (output_file == null) {
				var source_file = settings.FirstSourceFile;

				if (source_file == null) {
					Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
					return false;
				}

				output_file_name = source_file.Name;
				int pos = output_file_name.LastIndexOf ('.');

				if (pos > 0)
					output_file_name = output_file_name.Substring (0, pos);
				
				output_file_name += settings.TargetExt;
				output_file = output_file_name;
			} else {
				output_file_name = Path.GetFileName (output_file);

				if (string.IsNullOrEmpty (Path.GetFileNameWithoutExtension (output_file_name)) ||
					output_file_name.IndexOfAny (Path.GetInvalidFileNameChars ()) >= 0) {
					Report.Error (2021, "Output file name is not valid");
					return false;
				}
			}

#if STATIC
			var importer = new StaticImporter (module);
			var references_loader = new StaticLoader (importer, ctx);

			tr.Start (TimeReporter.TimerType.AssemblyBuilderSetup);
			var assembly = new AssemblyDefinitionStatic (module, references_loader, output_file_name, output_file);
			assembly.Create (references_loader.Domain);
			tr.Stop (TimeReporter.TimerType.AssemblyBuilderSetup);

			// Create compiler types first even before any referenced
			// assembly is loaded to allow forward referenced types from
			// loaded assembly into compiled builder to be resolved
			// correctly
			tr.Start (TimeReporter.TimerType.CreateTypeTotal);
			module.CreateContainer ();
			importer.AddCompiledAssembly (assembly);
			references_loader.CompiledAssembly = assembly;
			tr.Stop (TimeReporter.TimerType.CreateTypeTotal);

			references_loader.LoadReferences (module);

			tr.Start (TimeReporter.TimerType.PredefinedTypesInit);
			if (!ctx.BuiltinTypes.CheckDefinitions (module))
				return false;

			tr.Stop (TimeReporter.TimerType.PredefinedTypesInit);

			references_loader.LoadModules (assembly, module.GlobalRootNamespace);
#else
			var assembly = new AssemblyDefinitionDynamic (module, output_file_name, output_file);
			module.SetDeclaringAssembly (assembly);

			var importer = new ReflectionImporter (module, ctx.BuiltinTypes);
			assembly.Importer = importer;

			var loader = new DynamicLoader (importer, ctx);
			loader.LoadReferences (module);

			if (!ctx.BuiltinTypes.CheckDefinitions (module))
				return false;

			if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
				return false;

			module.CreateContainer ();

			loader.LoadModules (assembly, module.GlobalRootNamespace);
#endif
			module.InitializePredefinedTypes ();

			tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
			module.Define ();
			tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);

			if (Report.Errors > 0)
				return false;

			if (settings.DocumentationFile != null) {
				var doc = new DocumentationBuilder (module);
				doc.OutputDocComment (output_file, settings.DocumentationFile);
			}

			assembly.Resolve ();
			
			if (Report.Errors > 0)
				return false;


			tr.Start (TimeReporter.TimerType.EmitTotal);
			assembly.Emit ();
			tr.Stop (TimeReporter.TimerType.EmitTotal);

			if (Report.Errors > 0){
				return false;
			}

			tr.Start (TimeReporter.TimerType.CloseTypes);
			module.CloseContainer ();
			tr.Stop (TimeReporter.TimerType.CloseTypes);

			tr.Start (TimeReporter.TimerType.Resouces);
			if (!settings.WriteMetadataOnly)
				assembly.EmbedResources ();
			tr.Stop (TimeReporter.TimerType.Resouces);

			if (Report.Errors > 0)
				return false;

			assembly.Save ();

#if STATIC
			references_loader.Dispose ();
#endif
			tr.StopTotal ();
			tr.ShowStats ();

			return Report.Errors == 0;
		}
コード例 #33
0
ファイル: PluginManager.cs プロジェクト: ryan-bunker/axiom3d
		/// <summary>
		///		Scans for plugin files in the current directory.
		/// </summary>
		///<param name="folder"></param>
		///<returns></returns>
		protected IList<ObjectCreator> ScanForPlugins( string folder )
		{
			var pluginFactories = new List<ObjectCreator>();

#if NET_40 && !( XBOX || XBOX360 || WINDOWS_PHONE )
			this.SatisfyImports(folder);
			foreach (var plugin in plugins)
			{
				pluginFactories.Add(new ObjectCreator(plugin.GetType()));
				Debug.WriteLine(String.Format("MEF IPlugin: {0}.", plugin));
			}
#elif !( WINDOWS_PHONE )
			if ( Directory.Exists( folder ) )
			{
				var files = Directory.GetFiles( folder );
				//var assemblyName = Assembly.GetExecutingAssembly().GetName().Name + ".dll";

				foreach ( var file in files )
				{
					var currentFile = Path.GetFileName( file );

					if ( Path.GetExtension( file ) != ".dll" /*|| currentFile == assemblyName */ )
					{
						continue;
					}
					var fullPath = Path.GetFullPath( file );

					if ( !_isValidModule( fullPath ) )
					{
						Debug.WriteLine( String.Format( "Skipped {0} [Not managed]", fullPath ) );
						continue;
					}

					var loader = new DynamicLoader( fullPath );

					pluginFactories.AddRange( loader.Find( typeof ( IPlugin ) ) );
				}
			}
#endif
			return pluginFactories;
		}
コード例 #34
0
ファイル: Gameplay.cs プロジェクト: BenouKat/Unity-HiddenFox
 // Use this for initialization
 void Start()
 {
     dl = GetComponent<DynamicLoader>();
     triggerLevelStarted = false;
     levelStarted = false;
     gameOver = false;
     globalLevelTime = 0f;
 }
コード例 #35
0
		/// <summary>
		///    Loads the given assembly and exposes the API to the user.
		/// </summary>
		public void LoadAssembly (string file)
		{
			var loader = new DynamicLoader (importer, ctx);
			var assembly = loader.LoadAssemblyFile (file, false);
			if (assembly == null)
				return;

			lock (evaluator_lock){
				importer.ImportAssembly (assembly, module.GlobalRootNamespace);
			}
		}
コード例 #36
0
		void Init ()
		{
			var loader = new DynamicLoader (importer, ctx);

			RootContext.ToplevelTypes = module;

			//var startup_files = new List<string> ();
			//foreach (CompilationUnit file in Location.SourceFiles)
			//    startup_files.Add (file.Path);

			loader.LoadReferences (module);
			ctx.BuiltinTypes.CheckDefinitions (module);
			module.InitializePredefinedTypes ();

			inited = true;
		}
コード例 #37
0
		/// <summary>
		///     Internal constructor.  This class cannot be instantiated externally.
		/// </summary>
		internal PlatformManager()
		{
			// First look in current Executing assembly for a PlatformManager
			if ( instance == null )
			{
				var platformMgr = new DynamicLoader();
				var platforms = platformMgr.Find( typeof ( IPlatformManager ) );
				if ( platforms.Count != 0 )
				{
					instance = platformMgr.Find( typeof ( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
				}
			}

#if NET_40 && !( XBOX || XBOX360 || WINDOWS_PHONE )
			if (instance == null)
			{
				this.SatisfyImports(".");
				if (platforms != null && platforms.Count() != 0)
				{
					instance = platforms.First();
					System.Diagnostics.Debug.WriteLine(String.Format("MEF IPlatformManager: {0}.", instance));
				}
			}
#endif

#if !( SILVERLIGHT || WINDOWS_PHONE || XBOX || XBOX360 || NETFX_CORE)
			// Then look in loaded assemblies
			if ( instance == null )
			{
				var assemblies = AppDomain.CurrentDomain.GetAssemblies();
				for ( var index = 0; index < assemblies.Length && instance == null; index++ )
				{
					//TODO: NRSC Added: Deal with Dynamic Assemblies not having a Location
					//if (assemblies[index].IsDynamic)
					//    continue;
					try
					{
						var platformMgr = new DynamicLoader( assemblies[ index ] );
						var platforms = platformMgr.Find( typeof ( IPlatformManager ) );
						if ( platforms.Count != 0 )
						{
							instance = platformMgr.Find( typeof ( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
						}
					}
					catch ( Exception )
					{
						System.Diagnostics.Debug.WriteLine( String.Format( "Failed to load assembly: {0}.", assemblies[ index ].FullName ) );
					}
				}
			}

			// Then look in external assemblies
			if ( instance == null )
			{
				// find and load a platform manager assembly
				var cwd = Assembly.GetExecutingAssembly().CodeBase;
				var uri = new Uri( cwd );
				if ( uri.IsFile )
					cwd = Path.GetDirectoryName(uri.LocalPath);
				var files = Directory.GetFiles( cwd, "Axiom.Platforms.*.dll" ).ToArray();
				var file = "";

				// make sure there is 1 platform manager available
				if ( files.Length == 0 )
				{
					throw new PluginException( "A PlatformManager was not found in the execution path, and is required." );
				}
				else
				{
					var isWindows = IsWindowsOS;
					var platform = IsWindowsOS ? "Windows" : "Linux";

					if ( files.Length == 1 )
					{
						file = files[ 0 ];
					}
					else
					{
						for ( var i = 0; i < files.Length; i++ )
						{
							if ( ( files[ i ].IndexOf( platform ) != -1 ) == true )
							{
								file = files[ i ];
							}
						}
					}

					System.Diagnostics.Debug.WriteLine( String.Format( "Selected the PlatformManager contained in {0}.", file ) );
				}

				var path = Path.Combine( System.IO.Directory.GetCurrentDirectory(), file );

				var platformMgr = new DynamicLoader( path );
				var platforms = platformMgr.Find( typeof ( IPlatformManager ) );
				if ( platforms.Count != 0 )
				{
					instance = platformMgr.Find( typeof ( IPlatformManager ) )[ 0 ].CreateInstance<IPlatformManager>();
				}
			}
#endif

			// All else fails, yell loudly
			if ( instance == null )
			{
				throw new PluginException( "The available Platform assembly did not contain any subclasses of PlatformManager, which is required." );
			}
		}
コード例 #38
0
ファイル: PluginManager.cs プロジェクト: WolfgangSt/axiom
	    /// <summary>
		///		Scans for plugin files in the current directory.
		/// </summary>
		///<param name="folder"></param>
		///<returns></returns>
		protected IList<ObjectCreator> ScanForPlugins( string folder )
		{
            var pluginFactories = new List<ObjectCreator>();

            if (Directory.Exists(folder))
			{
                var files = Directory.GetFiles(folder);
                var assemblyName = Assembly.GetExecutingAssembly().GetName().Name + ".dll";

                foreach (var file in files)
				{
                    var currentFile = Path.GetFileName(file);

                    if (Path.GetExtension(file) != ".dll" || currentFile == assemblyName)
                        continue;
                    var fullPath = Path.GetFullPath(file);

                    if (!IsValidModule(fullPath))
                    {
                        Debug.WriteLine(String.Format("Skipped {0} [Not managed]", fullPath));
                        continue;
                    }

                    var loader = new DynamicLoader(fullPath);

				    pluginFactories.AddRange( loader.Find( typeof ( IPlugin ) ) );
				}
            }

			return pluginFactories;
		}