示例#1
0
 public void it_should_provide_a_configuration_context_to_scope_configuration()
 {
     PersistenceContext<DummyBackingStore> actual = null;
     var sut = new Registrar<DummyBackingStore>(new DummyBackingStore());
     sut.PerformRegistration(context => { actual = context; });
     actual.ShouldNotBeNull();
 }
示例#2
0
文件: Hotkeys.cs 项目: Enoz/InfiniPad
 public void Register(Action runFunc, string identifier, int fsModifiers, int vk)
 {
     DeleteHotkey(identifier);
     var rr = new Registrar(runFunc, identifier, fsModifiers, vk, curID);
     curID++;
     RegisterHotKey(this.Handle, rr.hkID, rr.Modifiers, rr.vk);
     hooks.Add(rr);
 }
示例#3
0
		public void TestConstructor ()
		{
			var registrar = new Registrar<MockRenderer> ();

			var renderer = registrar.GetHandler (typeof (Button));

			Assert.Null (renderer);
		}
示例#4
0
        public RegistrarTest()
        {
            this.factory = A.Fake<IFactory>();
            this.eventTopicHost = A.Fake<IEventTopicHost>();
            this.eventInspector = A.Fake<IEventInspector>();
            this.extensionsHost = A.Fake<IExtensionHost>();

            this.testee = new Registrar(this.factory, this.eventTopicHost, this.eventInspector, this.extensionsHost);
        }
示例#5
0
        static void Main()
        {
            var registrar = new Registrar();
            var pluginAsm = Assembly.LoadFrom(Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, "Automaton.Plugins.dll"));
            foreach (var pluginType in pluginAsm.GetTypes()
                .Where(t => t.GetInterfaces().Contains(typeof(IPlugin))))
            {
                var constructor = pluginType.GetConstructor(Type.EmptyTypes);
                if (constructor == null)
                {
                    Logger.WarnFormat(
                        "Empty constructor for plugin {0} not found. Skipping.",
                        pluginType.FullName);
                    continue;
                }
                var plugin = (IPlugin) Activator.CreateInstance(pluginType);
                plugin.Register(registrar);
            }

            
            var interpreter = new Interpreter(registrar, false);
            string next = null;
            while (true)
            {
                if (next == null)
                {
                    Console.WriteLine("Please ask a question:");
                    Console.Write(">> ");
                    next = Console.ReadLine();
                }

                var c = interpreter.Interpret(next).ToList();
                if (c.Count <= 0)
                {
                    Logger.Info("No commands found.");
                    next = null;
                    continue;
                }
                var elem = c[0];
                Logger.InfoFormat("Parsed command '{0}': {1}",
                    elem.Service.Name, elem.Similarity);
                var convo = elem.Service.StartConversation(elem.Arguments);

                var response = convo.Next();
                do
                {
                    Console.WriteLine(response);
                    Console.Write(">> ");
                    next = Console.ReadLine();
                }
                while (convo.TrySend(next, out response));
            }
        }
        protected override void Given()
        {
            var intBackingStore = new BerkeleyBackingStore(new DefaultBerkeleyBackingStoreEnvironment(TempDir));
            var registrar = new Registrar<BerkeleyBackingStore>(intBackingStore);
            registrar.PerformRegistration(
                context =>
                    {
                        context.Graph<GraphAffectedByNewIndex>();
                        context.Index(new ExistingIndex());
                    });
            registrar.ApplyRegistration();
            var intRegistry = registrar.Registry;
            var intSessFactory = new SessionFactory(intRegistry);

            using(var session = intSessFactory.GetSession())
            {
                session.Endure(new GraphAffectedByNewIndex { Text = "TheGraph"});
            }

            intBackingStore.Close();
        }
示例#7
0
        static void SetupInit(
            IMauiContext mauiContext,
            WindowsBasePage mainWindow,
            IEnumerable <Assembly> rendererAssemblies = null,
            InitializationOptions?maybeOptions        = null)
        {
            MauiContext = mauiContext;
            Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim);

            var accent = (WSolidColorBrush)Microsoft.UI.Xaml.Application.Current.Resources["SystemColorControlAccentBrush"];

            KnownColor.SetAccent(accent.ToColor());

            if (!IsInitialized)
            {
                Log.Listeners.Add(new DelegateLogListener((c, m) => Debug.WriteLine(LogFormat, c, m)));
            }

            if (!UI.Xaml.Application.Current.Resources.ContainsKey("RootContainerStyle"))
            {
                UI.Xaml.Application.Current.Resources.MergedDictionaries.Add(GetTabletResources());
            }

            try
            {
                if (!WinUIResourcesAdded)
                {
                    WinUIResourcesAdded = true;
                    UI.Xaml.Application.Current.Resources.MergedDictionaries.Add(new UI.Xaml.Controls.XamlControlsResources());
                }
            }
            catch
            {
                Log.Warning("Resources", "Unable to load WinUI resources. Try adding Microsoft.Maui.Controls.Compatibility nuget to UWP project");
            }

            Device.SetIdiom(TargetIdiom.Tablet);
            Device.SetFlowDirection(GetFlowDirection());

            Device.SetFlags(s_flags);
            Device.Info = new WindowsDeviceInfo();

            //TODO WINUI3
            //// use field and not property to avoid exception in getter
            //if (Device.info != null)
            //{
            //	Device.info.Dispose();
            //	Device.info = null;
            //}
            //Device.Info = new WindowsDeviceInfo();

            //TODO WINUI3
            //switch (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily)
            //{
            //	case "Windows.Desktop":
            //		if (Windows.UI.ViewManagement.UIViewSettings.GetForCurrentView().UserInteractionMode ==
            //			Windows.UI.ViewManagement.UserInteractionMode.Touch)
            //			Device.SetIdiom(TargetIdiom.Tablet);
            //		else
            //			Device.SetIdiom(TargetIdiom.Desktop);
            //		break;
            //	case "Windows.Mobile":
            //		Device.SetIdiom(TargetIdiom.Phone);
            //		break;
            //	case "Windows.Xbox":
            //		Device.SetIdiom(TargetIdiom.TV);
            //		break;
            //	default:
            //		Device.SetIdiom(TargetIdiom.Unsupported);
            //		break;
            //}

            ExpressionSearch.Default = new WindowsExpressionSearch();

            Registrar.ExtraAssemblies = rendererAssemblies?.ToArray();

            var dispatcher = mainWindow?.DispatcherQueue ?? System.DispatcherQueue.GetForCurrentThread();

            var platformServices = new WindowsPlatformServices(dispatcher);

            Device.PlatformServices    = platformServices;
            Device.PlatformInvalidator = platformServices;

            if (maybeOptions?.Flags.HasFlag(InitializationFlags.SkipRenderers) != true)
            {
                RegisterCompatRenderers();
            }

            if (mainWindow != null)
            {
                MainWindow = mainWindow;

                //TODO WINUI3
                Platform.UWP.Platform.SubscribeAlertsAndActionSheets();

                mainWindow.LoadApplication(mainWindow.CreateApplication());
                mainWindow.Activate();
            }

            IsInitialized = true;
        }
示例#8
0
        public void Resolving_a_object_should_be_a_transient_by_default()
        {
            var registrar = new Registrar().Satisfy<ClassWithNoArguments>().With<ClassWithNoArguments>();

            var firstResolveObject = new Resolver(registrar.Registrations).Resolve<ClassWithNoArguments>();
            var secondResolveObject = new Resolver(registrar.Registrations).Resolve<ClassWithNoArguments>();

            Assert.That(ReferenceEquals(firstResolveObject, secondResolveObject), Is.False, "Object lifetime should be transient by default!");
        }
示例#9
0
		public void TestGetRendererForUnknownSubclass ()
		{
			var registrar = new Registrar<MockRenderer> ();

			registrar.Register (typeof (View), typeof (MockRenderer));

			var renderer = registrar.GetHandler (typeof (Button));

			Assert.That (renderer, Is.InstanceOf<MockRenderer>());
		}
示例#10
0
		public void TestGetRendererWithRegisteredSubclass ()
		{
			var registrar = new Registrar<MockRenderer> ();

			registrar.Register (typeof (View), typeof (MockRenderer));
			registrar.Register (typeof (Button), typeof (ButtonMockRenderer));

			var buttonRenderer = registrar.GetHandler (typeof (Button));
			var viewRenderer = registrar.GetHandler (typeof (View));

			Assert.That (buttonRenderer, Is.InstanceOf<ButtonMockRenderer>());
			Assert.That (viewRenderer, Is.Not.InstanceOf<ButtonMockRenderer>());
			Assert.That (viewRenderer, Is.InstanceOf<MockRenderer>());
		}
示例#11
0
 public void Setup()
 {
     _registrar = new Registrar();
 }
示例#12
0
 /// <summary> Sends the event to the specified list of instance identities or names (case-insensitive) </summary>
 public int SendTo(int waitTime, IEnumerable <string> instances, string eventName, params string[] arguments)
 {
     return(InternalSend(waitTime, Registrar.GetRegisteredInstances(ChannelName, instances), eventName, arguments));
 }
示例#13
0
 public CallRouter(Registrar registrar)
 {
     _registrar = registrar;
 }
示例#14
0
 public static Dictionary <Type, Type> GetAllRenderers(this Registrar <View, IViewHandler> registar) => registar.Handler;
示例#15
0
        static void SetupInit(
            IMauiContext context,
            Assembly resourceAssembly,
            InitializationOptions?maybeOptions = null
            )
        {
            var activity = context.Context;

            Profile.FrameBegin();
            Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim);

            // Allow this multiple times to support the app and then the activity
            ApplicationContext = activity.ApplicationContext;
            MauiContext        = context;

            if (!IsInitialized)
            {
                // Only need to do this once
                Profile.FramePartition("ResourceManager.Init");
                ResourceManager.Init(resourceAssembly);
            }

            Profile.FramePartition("Color.SetAccent()");
            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // This could change if the UI mode changes (e.g., if night mode is enabled)
            Color.SetAccent(GetAccentColor(activity));
            _ColorButtonNormalSet = false;

            if (!IsInitialized)
            {
                // Only need to do this once
                Profile.FramePartition("Log.Listeners");
                Internals.Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c)));
            }

            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // because AndroidPlatformServices needs a current activity to launch URIs from
            Profile.FramePartition("Device.PlatformServices");

            var androidServices = new AndroidPlatformServices(activity);

            Device.PlatformServices    = androidServices;
            Device.PlatformInvalidator = androidServices;

            // use field and not property to avoid exception in getter
            if (Device.info != null)
            {
                ((AndroidDeviceInfo)Device.info).Dispose();
                Device.info = null;
            }

            // We want this to be updated when we have a new activity (e.g. on a configuration change)
            // because Device.Info watches for orientation changes and we need a current activity for that
            Profile.FramePartition("create AndroidDeviceInfo");
            Device.Info = new AndroidDeviceInfo(activity);

            Profile.FramePartition("setFlags");
            Device.SetFlags(s_flags);

            Profile.FramePartition("AndroidTicker");
            Ticker.SetDefault(null);

            Profile.FramePartition("RegisterAll");

            if (maybeOptions?.Flags.HasFlag(InitializationFlags.SkipRenderers) != true)
            {
                RegisterCompatRenderers(maybeOptions);
            }

            Profile.FramePartition("Epilog");

            var currentIdiom = TargetIdiom.Unsupported;

            // First try UIModeManager
            using (var uiModeManager = UiModeManager.FromContext(ApplicationContext))
            {
                try
                {
                    var uiMode = uiModeManager?.CurrentModeType ?? UiMode.TypeUndefined;
                    currentIdiom = DetectIdiom(uiMode);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Unable to detect using UiModeManager: {ex.Message}");
                }
            }

            // Then try Configuration
            if (TargetIdiom.Unsupported == currentIdiom)
            {
                var configuration = activity.Resources.Configuration;

                if (configuration != null)
                {
                    var minWidth = configuration.SmallestScreenWidthDp;
                    var isWide   = minWidth >= TabletCrossover;
                    currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                }
                else
                {
                    // Start clutching at straws
                    var metrics = activity.Resources?.DisplayMetrics;

                    if (metrics != null)
                    {
                        var minSize = Math.Min(metrics.WidthPixels, metrics.HeightPixels);
                        var isWide  = minSize * metrics.Density >= TabletCrossover;
                        currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone;
                    }
                }
            }

            Device.SetIdiom(currentIdiom);

            if (SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                Device.SetFlowDirection(activity.Resources.Configuration.LayoutDirection.ToFlowDirection());
            }

            if (ExpressionSearch.Default == null)
            {
                ExpressionSearch.Default = new AndroidExpressionSearch();
            }

            IsInitialized = true;
            Profile.FrameEnd();
        }
示例#16
0
        //[STAThread]
        static async Task <int> Main(string[] args)
        {
            // Load Settings.
            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();

            Settings        = configuration.ReadSettings();
            Config.Settings = Settings;

            // Load Log4Net for net configuration.
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            // Enable UTF8 for Console window.
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            log.Info($"\n{Settings.ProductName}");
            log.Info("\nPress 'Q' to unregister file system, delete all files/folders and exit (simulate uninstall with full cleanup).");
            log.Info("\nPress 'q' to unregister file system and exit (simulate uninstall).");
            log.Info("\nPress any other key to exit without unregistering (simulate reboot).");
            log.Info("\n----------------------\n");

            // Typically you will register sync root during your application installation.
            // Here we register it during first program start for the sake of the development convenience.
            if (!await Registrar.IsRegisteredAsync(Settings.UserFileSystemRootPath))
            {
                log.Info($"\nRegistering {Settings.UserFileSystemRootPath} sync root.");
                Directory.CreateDirectory(Settings.UserFileSystemRootPath);
                Directory.CreateDirectory(Settings.ServerDataFolderPath);

                await Registrar.RegisterAsync(SyncRootId, Settings.UserFileSystemRootPath, Settings.ProductName,
                                              Path.Combine(Config.Settings.IconsFolderPath, "Drive.ico"));
            }
            else
            {
                log.Info($"\n{Settings.UserFileSystemRootPath} sync root already registered.");
            }

            // Log indexed state. Indexing must be enabled for the sync root to function.
            StorageFolder userFileSystemRootFolder = await StorageFolder.GetFolderFromPathAsync(Settings.UserFileSystemRootPath);

            log.Info($"\nIndexed state: {(await userFileSystemRootFolder.GetIndexedStateAsync())}\n");

            ConfigureWebDAVClient();

            ConsoleKeyInfo exitKey = new ConsoleKeyInfo();

            // Event to be fired when any key will be pressed in the console or when the tray application exits.
            ManualResetEvent exitEvent = new ManualResetEvent(false);

            try
            {
                virtualDrive = new VirtualDrive(Settings.UserFileSystemLicense, Settings.UserFileSystemRootPath, log, Settings.SyncIntervalMs);
                RemoteStorageMonitorInstance = new RemoteStorageMonitor(Settings.WebDAVServerUrl, log);

                // Start tray application.
                Thread tryIconThread = WindowsTrayInterface.CreateTrayInterface(Settings.ProductName, virtualDrive.SyncService, exitEvent);

                // Start processing OS file system calls.
                //engine.ChangesProcessingEnabled = false;
                await virtualDrive.StartAsync();

                // Start monitoring changes in remote file system.
                //await RemoteStorageMonitorInstance.StartAsync();

#if DEBUG
                // Opens Windows File Manager with user file system folder and remote storage folder.
                ShowTestEnvironment();
#endif
                // Keep this application running until user input.
                exitKey = WebDAVDrive.UI.ConsoleManager.WaitConsoleReadKey(exitEvent);

                //wait until the button "Exit" is pressed or any key in console is peressed  to stop application
                exitEvent.WaitOne();
            }
            finally
            {
                virtualDrive.Dispose();
                RemoteStorageMonitorInstance.Dispose();
            }

            if (exitKey.KeyChar == 'q')
            {
                // Unregister during programm uninstall.
                await Registrar.UnregisterAsync(SyncRootId);

                log.Info($"\n\nUnregistering {Settings.UserFileSystemRootPath} sync root.");
                log.Info("\nAll empty file and folder placeholders are deleted. Hydrated placeholders are converted to regular files / folders.\n");
            }
            else if (exitKey.KeyChar == 'Q')
            {
                log.Info($"\n\nUnregistering {Settings.UserFileSystemRootPath} sync root.");
                log.Info("\nAll files and folders placeholders are deleted.\n");

                // Unregister during programm uninstall and delete all files/folder.
                await Registrar.UnregisterAsync(SyncRootId);

                try
                {
                    Directory.Delete(Settings.UserFileSystemRootPath, true);
                }
                catch (Exception ex)
                {
                    log.Error($"\n{ex}");
                }

                try
                {
                    Directory.Delete(Config.Settings.ServerDataFolderPath, true);
                }
                catch (Exception ex)
                {
                    log.Error($"\n{ex}");
                }
            }
            else
            {
                log.Info("\n\nAll downloaded file / folder placeholders remain in file system. Restart the application to continue managing files.\n");
            }

            return(1);
        }
示例#17
0
 public void SetEndpointNameFormatter(IEndpointNameFormatter endpointNameFormatter)
 {
     Registrar.RegisterSingleInstance(endpointNameFormatter);
 }
 public void SetupForRegistrar()
 {
     _registrar = new Registrar <IFrameworkElement, IViewHandler>();
 }
示例#19
0
 public static void GMEUnRegister(Type t)
 {
     Registrar.UnregisterInterpreter();
 }
示例#20
0
        static void SetupInit(FormsApplication application)
        {
            Context = application;

            if (!IsInitialized)
            {
                Internals.Log.Listeners.Add(new XamarinLogListener());
                if (System.Threading.SynchronizationContext.Current == null)
                {
                    TizenSynchronizationContext.Initialize();
                }
                Elementary.Initialize();
                Elementary.ThemeOverlay();
            }

            // In .NETCore, AppDomain feature is not supported.
            // The list of assemblies returned by AppDomain.GetAssemblies() method should be registered manually.
            // The assembly of the executing application and referenced assemblies of it are added into the list here.
            // TODO: AppDomain is comming back in NETStandard2.0. This logic should be changed at that time.
            TizenPlatformServices.AppDomain.CurrentDomain.RegisterAssemblyRecursively(application.GetType().GetTypeInfo().Assembly);

            Device.PlatformServices = new TizenPlatformServices();;
            if (Device.info != null)
            {
                ((TizenDeviceInfo)Device.info).Dispose();
                Device.info = null;
            }

            Device.Info = new Forms.TizenDeviceInfo();
            Device.SetFlags(s_flags);

            if (!Forms.IsInitialized)
            {
                Registrar.RegisterAll(new Type[]
                {
                    typeof(ExportRendererAttribute),
                    typeof(ExportImageSourceHandlerAttribute),
                    typeof(ExportCellAttribute),
                    typeof(ExportHandlerAttribute)
                });
            }

            // TODO: We should consider various tizen profiles such as TV, Wearable and so on.
            string profile = ((TizenDeviceInfo)Device.Info).Profile;

            if (profile == "mobile")
            {
                Device.SetIdiom(TargetIdiom.Phone);
            }
            else if (profile == "tv")
            {
                Device.SetIdiom(TargetIdiom.TV);
            }
            else if (profile == "desktop")
            {
                Device.SetIdiom(TargetIdiom.Desktop);
            }
            else
            {
                Device.SetIdiom(TargetIdiom.Unsupported);
            }
            Color.SetAccent(GetAccentColor(profile));
            ExpressionSearch.Default = new TizenExpressionSearch();
            IsInitialized            = true;
        }
示例#21
0
 public static void GMEUnRegister(Type t)
 {
     Registrar.UnregisterComponentsInGMERegistry();
 }
示例#22
0
 protected override void Bindings(Container container)
 {
     Registrar.Register(container);
 }
示例#23
0
 public void SetupForRegistrar()
 {
     _registrar = new Registrar <IView, IViewHandler>();
 }
示例#24
0
        private void bbtnRegister_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            StackProxy.initialize();
            CallManager.StackProxy = StackProxy;

            Config.CFNRFlag            = false;
            Config.CFUFlag             = false;
            Config.DefaultAccountIndex = 0;
            Config.AAFlag  = Settings.AutoAnswer;
            Config.DNDFlag = Settings.DoNotDisturb;

            if (Config.Accounts.Count > 0)
            {
                Registrar.unregisterAccounts();
            }
            Config.Accounts.Clear();

            AccountConfig acc = new AccountConfig();

            acc.AccountName   = Settings.UserName;
            acc.DisplayName   = Settings.UserName;
            acc.DomainName    = Settings.Domain;
            acc.HostName      = Settings.Host;
            acc.Password      = Settings.Password;
            acc.TransportMode = ETransportMode.TM_UDP;
            acc.UserName      = Settings.UserName;
            acc.Id            = Settings.UserName;
            acc.ProxyAddress  = "";
            Config.Accounts.Add(acc);

            //ConfigStruct.listenPort = Settings.Port;
            //ConfigStruct.noUDP = false;
            //ConfigStruct.noTCP = true;
            //ConfigStruct.stunServer = "";
            //ConfigStruct.publishEnabled = false;
            //ConfigStruct.expires = 3600;
            //ConfigStruct.VADEnabled = true;
            //ConfigStruct.ECTail = 200;
            //ConfigStruct.nameServer = Settings.Host;
            //ConfigStruct.pollingEventsEnabled = false;


            CallManager.Config = Config;
            StackProxy.Config  = Config;
            Registrar.Config   = Config;
            pjsipPresenceAndMessaging.Instance.Config = Config;

            CallManager.CallStateRefresh -= CallManager_CallStateRefresh;
            CallManager.CallStateRefresh += CallManager_CallStateRefresh;
            //CallManager.IncomingCallNotification += CallManager_IncomingCallNotification;

            Registrar.AccountStateChanged -= Instance_AccountStateChanged;
            Registrar.AccountStateChanged += Instance_AccountStateChanged;

            if (CallManager.Initialize() == 0)
            {
                Registrar.registerAccounts();
            }
            else
            {
                lMessages.Caption = "Popraw ustawienia.";
                lStatus.Caption   = "Nie połączono";
                timerMessages.Start();
            }

            int noOfCodecs = StackProxy.getNoOfCodecs();

            for (int i = 0; i < noOfCodecs; i++)
            {
                string codecname = StackProxy.getCodec(i);
                StackProxy.setCodecPriority(codecname, 128);
            }

            StackProxy.DtmfDigitReceived -= Instance_DtmfDigitReceived;
            StackProxy.DtmfDigitReceived += Instance_DtmfDigitReceived;
        }
示例#25
0
        private void UpdateGPS()
        {
            byte newInterval = UserSettings.GetSetting(UserSettings.ByteSettingName.UpdateIntervalHUD);

            if (newInterval != m_updateIntervalGPS)
            {
                Log.DebugLog("Update interval changed from " + m_updateIntervalGPS + " to " + newInterval, Logger.severity.DEBUG);

                UpdateManager.Unregister(m_updateIntervalGPS, UpdateGPS);
                UpdateManager.Register(newInterval, UpdateGPS);
                m_updateIntervalGPS = newInterval;
            }

            if (m_storage == null)
            {
                Log.TraceLog("no storage getter");
                return;
            }

            RelayStorage store = m_storage.Invoke();

            if (store == null)
            {
                Log.TraceLog("no storage");
                return;
            }

            if (store.LastSeenCount == 0)
            {
                Log.TraceLog("No LastSeen");
                return;
            }

            Vector3D myPosition = m_controlled.GetPosition();

            foreach (var pair in Data)
            {
                pair.Value.MaxOnHUD = UserSettings.GetSetting(pair.Key);
                pair.Value.Prepare();
            }

            Log.TraceLog("primary node: " + store.PrimaryNode.DebugName);

            m_haveTerminalAccess.Clear();
            foreach (RelayNode node in Registrar.Scripts <RelayNode>())
            {
                MyCubeGrid grid = (node.Entity as MyCubeBlock)?.CubeGrid;
                Log.TraceLog("grid: " + grid.nameWithId() + ", node storage: " + node.GetStorage()?.PrimaryNode.DebugName);
                if (grid != null && node.GetStorage()?.PrimaryNode == store.PrimaryNode && m_haveTerminalAccess.Add(grid))
                {
                    foreach (var aGrid in Attached.AttachedGrid.AttachedGrids(grid, Attached.AttachedGrid.AttachmentKind.Terminal, true))
                    {
                        m_haveTerminalAccess.Add(aGrid);
                    }
                }
            }

            store.ForEachLastSeen((LastSeen seen) => {
                Log.TraceLog("seen: " + seen.Entity.nameWithId());

                if (!seen.isRecent())
                {
                    Log.TraceLog("not recent: " + seen.Entity.nameWithId());
                    return;
                }

                if (seen.isRecent_Broadcast())
                {
                    Log.TraceLog("already visible: " + seen.Entity.getBestName());
                    return;
                }

                if (seen.Entity is IMyCubeGrid && m_haveTerminalAccess.Contains((IMyCubeGrid)seen.Entity))
                {
                    Log.TraceLog("terminal linked: " + seen.Entity.nameWithId());
                    return;
                }

                UserSettings.ByteSettingName setting;
                if (!CanDisplay(seen, out setting))
                {
                    Log.TraceLog("cannot display: " + seen.Entity.nameWithId());
                    return;
                }

                GpsData relateData;
                if (!Data.TryGetValue(setting, out relateData))
                {
                    Log.DebugLog("failed to get setting data, setting: " + setting, Logger.severity.WARNING);
                    return;
                }

                if (relateData.MaxOnHUD == 0)
                {
                    Log.TraceLog("type not permitted: " + seen.Entity.nameWithId());
                    return;
                }

                Log.TraceLog("approved: " + seen.Entity.nameWithId());
                float distance = Vector3.DistanceSquared(myPosition, seen.GetPosition());
                relateData.distanceSeen.Add(new DistanceSeen(distance, seen));
            });

            m_haveTerminalAccess.Clear();

            foreach (var pair in Data)
            {
                UpdateGPS(pair.Key, pair.Value);
            }
        }
示例#26
0
        public void CreateTemporaryApp(bool hasPlist = false, string appName = "testApp", string code = null, IList <string> extraArgs = null, string extraCode = null, string usings = null)
        {
            string testDir;

            if (RootAssembly == null)
            {
                testDir = CreateTemporaryDirectory();
            }
            else
            {
                // We're rebuilding an existing executable, so just reuse that
                testDir = Path.GetDirectoryName(RootAssembly);
            }
            var app = AppPath ?? Path.Combine(testDir, appName + ".app");

            Directory.CreateDirectory(app);
            if (IsDotNet)
            {
                // This code to create a .NET project from the options in this class is very rudimentary; most options are not honored.
                // To be fixed when support for more options is needed.
                var mtouchExtraArgs = new List <string> ();
                if (Registrar != RegistrarOption.Unspecified)
                {
                    mtouchExtraArgs.Add($"--registrar:" + Registrar.ToString().ToLower());
                }

                string linkMode = string.Empty;
                if (Linker != LinkerOption.Unspecified)
                {
                    switch (Linker)
                    {
                    case LinkerOption.DontLink:
                        linkMode = "None";
                        break;

                    case LinkerOption.LinkAll:
                        linkMode = "Full";
                        break;

                    case LinkerOption.LinkSdk:
                        linkMode = "SdkOnly";
                        break;

                    case LinkerOption.LinkPlatform:
                    default:
                        throw new NotImplementedException(Linker.ToString());
                    }
                    linkMode = "<MtouchLink>" + linkMode + "</MtouchLink>";
                }

                var csproj = $@"<Project Sdk=""Microsoft.NET.Sdk"">
	<PropertyGroup>
		<TargetFramework>{Profile.AsPlatform ().ToFramework ()}</TargetFramework>
		<OutputType>Exe</OutputType>
		<MtouchExtraArgs>{string.Join (" ", mtouchExtraArgs)}</MtouchExtraArgs>
		<ApplicationId>{appName}</ApplicationId>
		{linkMode}
	</PropertyGroup>
</Project>";
                ProjectFile = Path.Combine(testDir, appName + ".csproj");
                File.WriteAllText(ProjectFile, csproj);
                File.WriteAllText(Path.Combine(testDir, appName + ".cs"), CreateCode(code, usings, extraCode));
                if (hasPlist)
                {
                    File.WriteAllText(Path.Combine(testDir, "Info.plist"), CreatePlist(Profile, appName));
                }
                Configuration.CopyDotNetSupportingFiles(testDir);
            }
            else
            {
                AppPath      = app;
                RootAssembly = CompileTestAppExecutable(testDir, code, extraArgs, Profile, appName, extraCode, usings);

                if (hasPlist)
                {
                    File.WriteAllText(Path.Combine(app, "Info.plist"), CreatePlist(Profile, appName));
                }
            }
        }
 public CharacterStateTracker(IMyCharacter character)
 {
     Registrar.Add((IMyEntity)character, this);
     character.OnMovementStateChanged += character_OnMovementStateChanged;
 }
示例#28
0
 static IntPtr GetNullableType(IntPtr type)
 {
     return(ObjectWrapper.Convert(Registrar.GetNullableType((Type)ObjectWrapper.Convert(type))));
 }
示例#29
0
		public void GetHandlerType()
		{
			var registrar = new Registrar<MockRenderer>();
			registrar.Register (typeof (View), typeof (MockRenderer));

			Assert.AreEqual (typeof (MockRenderer), registrar.GetHandlerType (typeof (View)));
		}
示例#30
0
 public void SetupForRegistrar()
 {
     _registrar = new Registrar <IFrameworkElement, IViewHandler>();
     _registrar.Register <IButton, ButtonHandler>();
 }
示例#31
0
 public static void GMERegister(Type t)
 {
     Registrar.RegisterInterpreter();
 }
示例#32
0
        public ManualMessage(IMyCubeBlock block)
        {
            m_block = block;

            Registrar.Add(block, this);
        }
示例#33
0
        public void Resolving_a_object_with_singleton_lifetime_should_resolve_same_reference_twice()
        {
            var registrar = new Registrar().Satisfy<ClassWithNoArguments>().With<ClassWithNoArguments>().For(Lifetime.Singleton);

            var firstResolveObject = new Resolver(registrar.Registrations).Resolve<ClassWithNoArguments>();
            var secondResolveObject = new Resolver(registrar.Registrations).Resolve<ClassWithNoArguments>();

            Assert.That(ReferenceEquals(firstResolveObject, secondResolveObject), Is.True, "Singleton lifetime should resolve to the same object reference!");
        }
示例#34
0
        public void Resolve_an_object_with_arguments_of_same_type_but_different_names_should_set_them_in_the_right_order()
        {
            string arg1 = "someArgument";
            decimal arg2 = 1234m;
            string arg3 = "anotherArgument";

            var registrar = new Registrar().Satisfy<ClassWithThreeArguments>().With<ClassWithThreeArguments>(new { argument3 = arg3, argument1 = arg1, argument2 = arg2 });

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithThreeArguments>();

            Assert.That(ReferenceEquals(resolvedObject.Argument1, arg1), Is.True, "expected argument 1 to be set");
            Assert.That(resolvedObject.Argument2, Is.EqualTo(arg2), "expected argument 2 to be set");
            Assert.That(ReferenceEquals(resolvedObject.Argument3, arg3), Is.True, "expected argument 3 to be set");
        }
示例#35
0
 public UnitTest2()
 {
     _registro = new Registrar();
 }
示例#36
0
        public void Resolve_an_object_with_arguments_should_have_the_arguments_set()
        {
            string argument1 = "someArgument";
            decimal argument2 = 1234m;

            var registrar = new Registrar().Satisfy<ClassWithThreeArguments>().With<ClassWithThreeArguments>(new { Argument1 = argument1, Argument2 = argument2, Argument3 = ""});

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithThreeArguments>();

            Assert.That(ReferenceEquals(resolvedObject.Argument1, argument1), Is.True, "expected argument 1 to be set");
            Assert.That(resolvedObject.Argument2, Is.EqualTo(argument2), "expected argument 2 to be set");
        }
示例#37
0
        public static void Main(string[] args)
        {
            char             ch, ch2;
            bool             successLogin = false;
            GradStudent      st;
            UndergradStudent stu;
            var               admins        = new List <User>();
            List <Course>     coursesList   = new List <Course>();
            List <Enrollment> courseEnrolls = new List <Enrollment>();



            List <User> profList = new List <User>();
            List <User> gslist   = new List <User>();
            List <User> ugslist  = new List <User>();



            LoadUserData('G', gslist, "GsList.txt");
            LoadUserData('U', ugslist, "UGsList.txt");
            LoadUserData('P', profList, "profData.txt");
            LoadCourseData(coursesList, "coursesData.txt");
            LoadUserData('A', admins, "adminData.txt");

            List <User> students = new List <User>();

            students.AddRange(gslist);
            students.AddRange(ugslist);


            do
            {
                ch = LoginMenu();

                switch (ch)
                {
                case '1':

                    Console.WriteLine("\n \t Enter your Id:");
                    string tId = Console.ReadLine();
                    Console.Write("\t Enter your Password: "******"\n Error: user Id or password are not correct!");
                    }
                    else
                    {
                        do
                        {
                            //1- Add Grad student" , "2- Add undergrad student", "3- List All grad students",
                            //"4- List All undergrad students", "5- Add new course", "6- list students in course");
                            ch2 = admin.Menu();
                            switch (ch2)
                            {
                            //TODO (1): Add new Grad Student <<DONE>>
                            case '1':
                                Console.WriteLine("Please Enter an ID");
                                string Id = Console.ReadLine();
                                Console.WriteLine("Please Enter a Password");
                                string pswd = Console.ReadLine();
                                Console.WriteLine("Please Enter a Name");
                                string name = Console.ReadLine();
                                Console.WriteLine("Please Enter a Student ID");
                                string sID = Console.ReadLine();
                                Console.WriteLine("Please Enter a Date of Birth");
                                string doB = Console.ReadLine();
                                Console.WriteLine("Please Enter a Undergrad Department");
                                string uDept = Console.ReadLine();
                                Console.WriteLine("Please Enter a GPA");
                                string GPA = Console.ReadLine();
                                Console.WriteLine("Please Enter a Previous Degree");
                                string pDeg = Console.ReadLine();
                                Console.WriteLine("Please Enter a Previous University");
                                string pUni = Console.ReadLine();
                                Console.WriteLine("Please Enter a Graduate Department");
                                string GradDept = Console.ReadLine();
                                Console.WriteLine("Please Enter a Undergrad GPA");
                                string   uGPA          = Console.ReadLine();
                                string[] grad          = new string[] { Id, pswd, name, sID, doB, uDept, GPA, pDeg, pUni, GradDept, uGPA };
                                var      checkIfExists = findUser(gslist, Id);
                                if (checkIfExists != null)
                                {
                                    Console.WriteLine("They are already in the list");
                                    break;
                                }
                                else
                                {
                                    gslist.Add(st = new GradStudent(grad));
                                    Console.WriteLine("student added");
                                    break;
                                }

                            //TODO (2): Add new undergrad Student,
                            case '2':
                                Console.WriteLine("Please Enter an ID");
                                Id = Console.ReadLine();
                                Console.WriteLine("Please Enter a Password");
                                pswd = Console.ReadLine();
                                Console.WriteLine("Please Enter a Name");
                                name = Console.ReadLine();
                                Console.WriteLine("Please Enter a Student ID");
                                sID = Console.ReadLine();
                                Console.WriteLine("Please Enter a Date of Birth");
                                doB = Console.ReadLine();
                                Console.WriteLine("Please Enter a Undergrad Department");
                                uDept = Console.ReadLine();
                                Console.WriteLine("Please Enter a GPA");
                                GPA = Console.ReadLine();
                                Console.WriteLine("Please Enter a Highschool");
                                string highSchool = Console.ReadLine();
                                Console.WriteLine("Please Enter a Classification");
                                string   classification = Console.ReadLine();
                                string[] ugrad          = new string[] { Id, pswd, name, sID, doB, uDept, GPA, highSchool, classification };
                                var      checkIfExistsU = findUser(ugslist, Id);
                                if (checkIfExistsU != null)
                                {
                                    Console.WriteLine("They are already in the list");
                                    break;
                                }
                                else
                                {
                                    ugslist.Add(stu = new UndergradStudent(ugrad));
                                    Console.WriteLine("student added");
                                    break;
                                }

                            case '3':
                                foreach (GradStudent std in gslist)
                                {
                                    Console.WriteLine();
                                    std.DisplayStdInfo();
                                }
                                break;

                            case '4':
                                foreach (UndergradStudent std in ugslist)
                                {
                                    Console.WriteLine();
                                    std.DisplayStdInfo();
                                }
                                break;

                            case '5':         //TODO (3): Add new  course by asking Admin for course info., verify inputs 1st
                                              //        : ++ Save new list to File if admin agrees

                                // Test: Currently adding one specific course
                                coursesList.Add(new Course("Adv. Prog", 3312, 3));
                                //coursesList[0].professor = (Professor )profList[0];
                                break;

                            case '6':         //TODO (4): Assign course to prof by getting ProfId, courseId,
                                              //        : verify inputs, and prof doesnot have >3 courses
                                              //        : ++ Save new list to File, and make the code initialize prof-course-assignment list from a file

                                // Test: Currently Assign all courses to 1st prof in the list
                                foreach (var c in coursesList)
                                {
                                    c.professor = (Professor)profList[0];
                                    c.professor.addCourseToTeach(c);
                                }
                                break;

                            case '7':
                                foreach (var std in courseEnrolls)
                                {
                                    std.displEnrolledStudInfo();
                                }
                                break;
                            } //end switch ch2
                        } while (ch2 != '0');
                    }         // else



                    break;

                case '2':      //  Works for both grad & undergrad using student combined list
                case '3':
                    Console.WriteLine("\n \t Enter your Id:");
                    tId = Console.ReadLine();
                    Console.Write("\t Enter your Password: "******"\n Error: user Id or password are not correct!");
                    }
                    else
                    {
                        do
                        {
                            //"1- List My courses", "2- Enroll in a course","3- submit course Assesment"
                            ch2 = student.Menu();
                            switch (ch2)
                            {
                            case '1':
                                student.DisplayEnrollments();

                                break;

                            case '2':
                                Console.WriteLine("Enter Course Id: ");
                                int cId = int.Parse(Console.ReadLine());

                                Course selectedCourse = findCourse(coursesList, cId);
                                // TODO (5): check if stud already enrolled in the course before adding
                                if (selectedCourse != null)
                                {
                                    Enrollment tEn = new Enrollment(selectedCourse, student);
                                    courseEnrolls.Add(tEn);
                                    student.addEnrollment(tEn);
                                    selectedCourse.addEnrollment(tEn);
                                }
                                break;


                            case '3':
                                student.DisplayEnrollments();
                                Console.WriteLine("Select Course Id To submit Assessment for: ");

                                cId = int.Parse(Console.ReadLine());

                                //selectedCourse = findCourse(coursesList,  cId);
                                //
                                Enrollment e = student.getEnrolmentByCourseId(cId);
                                if (e != null)
                                {
                                    e.getCourse().displayCourseAssessments();
                                    Console.WriteLine("Select Assessment Id To submit: ");
                                    string assessId = Console.ReadLine().Trim();
                                    e.submitAssesment(assessId, "12/12/2018");
                                }
                                break;

                                //case '4':
                                // TODO (6): Drop course, get cId, verify cId in student enrollments, then remove enrol.
                            } // switch ch2
                        } while (ch2 != '0');
                    }         //else
                    break;

                case '4':     //prof

                    Console.WriteLine("\n \t Enter your Id:");
                    tId = Console.ReadLine();
                    Console.Write("\t Enter your Password: "******"\n Error: user Id or password are not correct!");
                    }
                    else
                    {
                        do
                        {
                            // 1- List my courses, 2- Add Assesment to course,3- Update student's Assesment points");
                            // 4- list students in a course
                            ch2 = prof.Menu();
                            switch (ch2)
                            {
                            case '1':
                                prof.displayCourses();
                                break;

                            case '2':
                                prof.displayCourses();
                                Console.WriteLine("Enter Course Id: ");
                                int cId = int.Parse(Console.ReadLine());

                                Course selectedCourse = findCourse(coursesList, cId);
                                // TODO (7): get assessment type: assignment, exam, proj,...
                                //         : then add assessment info
                                if (selectedCourse != null)
                                {
                                    Console.WriteLine("Enter Assessment info: ");
                                    Console.WriteLine("Id = ");
                                    string assesId = Console.ReadLine();
                                    Console.WriteLine("Weight = ");
                                    float aPercent = float.Parse(Console.ReadLine());
                                    Console.WriteLine("Descr = ");
                                    string asDescr = Console.ReadLine();
                                    Console.WriteLine("Points = ");
                                    float aPoints = float.Parse(Console.ReadLine());
                                    Console.WriteLine("Due on = ");
                                    string aDueDate = Console.ReadLine();
                                    Console.WriteLine("Late Pen = ");
                                    float latePen = float.Parse(Console.ReadLine());

                                    selectedCourse.AddCourseAssesment(new Assignment(assesId, aPercent, asDescr, aPoints, aDueDate, latePen));
                                }


                                //coursesList[0].AddCourseAssesmsnt(new Assignment("HW1",0.25f,"written assignment",200,"10/22/18",0.1f));
                                //coursesList[0].AddCourseAssesmsnt(new Exam("MT",0.50f, 200,"10/22/18",2));
                                //coursesList[0].AddCourseAssesmsnt(new Assignment("HW2",0.25f,"written assignment",300,"10/22/18",0.1f));

                                break;

                            case '3':
                                prof.displayCourses();
                                Console.WriteLine("Enter Course Id: ");
                                cId = int.Parse(Console.ReadLine());

                                selectedCourse = findCourse(coursesList, cId);

                                if (selectedCourse != null)
                                {
                                    selectedCourse.displayCourseStudents();
                                    Console.WriteLine("Select student name  ");
                                    //Console.WriteLine(" sName : ");
                                    string sName = Console.ReadLine().Trim();

                                    Student s = selectedCourse.getStudentByName(sName);

                                    Enrollment e = s.getEnrolmentByCourseId(cId);
                                    if (e != null)
                                    {
                                        e.getCourse().displayCourseAssessments();
                                        Console.WriteLine("Select Assessment Id To update: ");
                                        string         assessId       = Console.ReadLine().Trim();
                                        StudAssessment studAssessment = e.getStudAssessmentById(assessId);
                                        Console.WriteLine("Enter assessment Points :");
                                        float newPoints = float.Parse(Console.ReadLine());
                                        studAssessment.updateAssessmentPoints(newPoints);
                                    }
                                }
                                break;

                            case '4':
                                prof.displayCourses();
                                Console.WriteLine("Enter Course Id: ");
                                cId = int.Parse(Console.ReadLine());

                                selectedCourse = findCourse(coursesList, cId);

                                if (selectedCourse != null)
                                {
                                    selectedCourse.displayCourseStudents();
                                }
                                break;
                            } // switch ch2
                        } while (ch2 != '0');
                    }         //else
                    break;
                }// switch ch
            } while (ch != '0');
        }
示例#38
0
        public void Resolving_an_existing_object_should_get_the_same_object_back_that_we_registered()
        {
            var registeredObject = new ClassWithNoArguments();

            var registrar = new Registrar().Satisfy<IClass>().With(registeredObject);

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<IClass>();

            Assert.That(ReferenceEquals(registeredObject, resolvedObject), Is.True, "the 2 object references are not the same");
        }
示例#39
0
        static async Task Main(string[] args)
        {
            // Load Settings.
            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();

            Settings = configuration.ReadSettings();

            // Load Log4Net for net configuration.
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "log4net.config")));

            // Enable UTF8 for Console Window
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            log.Info($"\n{System.Diagnostics.Process.GetCurrentProcess().ProcessName} {Settings.AppID}");
            log.Info("\nPress 'Q' to unregister file system, delete all files/folders and exit (simulate uninstall with full cleanup).");
            log.Info("\nPress 'q' to unregister file system and exit (simulate uninstall).");
            log.Info("\nPress any other key to exit without unregistering (simulate reboot).");
            log.Info("\n----------------------\n");

            // Typically you will register sync root during your application installation.
            // Here we register it during first program start for the sake of the development convenience.
            if (!await Registrar.IsRegisteredAsync(Settings.UserFileSystemRootPath))
            {
                log.Info($"\nRegistering {Settings.UserFileSystemRootPath} sync root.");
                Directory.CreateDirectory(Settings.UserFileSystemRootPath);
                Directory.CreateDirectory(Settings.ServerDataFolderPath);

                await Registrar.RegisterAsync(SyncRootId, Settings.UserFileSystemRootPath, Settings.ProductName,
                                              Path.Combine(Settings.IconsFolderPath, "Drive.ico"));
            }
            else
            {
                log.Info($"\n{Settings.UserFileSystemRootPath} sync root already registered.");
            }

            // Log indexed state.
            StorageFolder userFileSystemRootFolder = await StorageFolder.GetFolderFromPathAsync(Settings.UserFileSystemRootPath);

            log.Info($"\nIndexed state: {(await userFileSystemRootFolder.GetIndexedStateAsync())}\n");

            ConsoleKeyInfo exitKey;

            try
            {
                Engine = new VirtualEngine(
                    Settings.UserFileSystemLicense,
                    Settings.UserFileSystemRootPath,
                    Settings.ServerDataFolderPath,
                    Settings.IconsFolderPath,
                    log);
                Engine.AutoLock = Settings.AutoLock;

                // Start processing OS file system calls.
                await Engine.StartAsync();

#if DEBUG
                // Opens Windows File Manager with user file system folder and remote storage folder.
                ShowTestEnvironment();
#endif
                // Keep this application running until user input.
                exitKey = Console.ReadKey();
            }
            finally
            {
                Engine.Dispose();
            }

            if (exitKey.KeyChar == 'q')
            {
                // Unregister during programm uninstall.
                await Registrar.UnregisterAsync(SyncRootId);

                log.Info($"\n\nUnregistering {Settings.UserFileSystemRootPath} sync root.");
                log.Info("\nAll empty file and folder placeholders are deleted. Hydrated placeholders are converted to regular files / folders.\n");
            }
            else if (exitKey.KeyChar == 'Q')
            {
                log.Info($"\n\nUnregistering {Settings.UserFileSystemRootPath} sync root.");
                log.Info("\nAll files and folders placeholders are deleted.\n");

                // Unregister during programm uninstall and delete all files/folder.
                await Registrar.UnregisterAsync(SyncRootId);

                try
                {
                    Directory.Delete(Settings.UserFileSystemRootPath, true);
                }
                catch (Exception ex)
                {
                    log.Error($"\n{ex}");
                }

                try
                {
                    Directory.Delete(Settings.ServerDataFolderPath, true);
                }
                catch (Exception ex)
                {
                    log.Error($"\n{ex}");
                }
            }
            else
            {
                log.Info("\n\nAll downloaded file / folder placeholders remain in file system. Restart the application to continue managing files.\n");
            }
        }
示例#40
0
        public void Resolving_an_object_that_needs_be_be_constructed_should_return_an_instance_of_that_type()
        {
            var registrar = new Registrar().Satisfy<IClass>().With<ClassWithNoArguments>();

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<IClass>();

            Assert.That(resolvedObject, Is.InstanceOf<ClassWithNoArguments>(), "expected resolved object to be of type ClassWithNoArguments");
        }
示例#41
0
文件: Scanner.cs 项目: mwjackson/ioc
 public Scanner(Registrar registrar)
 {
     Registrar = registrar;
 }
示例#42
0
        public void Resolving_an_object_with_arguments_missing_should_throw_argumentexception()
        {
            string arg3 = "anotherArgument";

            var registrar = new Registrar().Satisfy<ClassWithThreeArguments>().With<ClassWithThreeArguments>(new { argument3 = arg3});

            Assert.That(() => new Resolver(registrar.Registrations).Resolve<ClassWithThreeArguments>(),
                Throws.ArgumentException.With.Message.EqualTo("Missing parameters: argument1 argument2"));
        }
示例#43
0
 /// <summary> Sends the event to all channel subscribers, waiting at most waitTime </summary>
 public int Broadcast(int waitTime, string eventName, params string[] arguments)
 {
     return(InternalSend(waitTime, Registrar.GetRegisteredInstances(ChannelName), eventName, arguments));
 }
示例#44
0
        public void Resolving_an_object_with_argument_of_type_that_has_been_registered_should_resolve_that_type_also()
        {
            var dependency = new ClassWithNoArguments();
            var registrar = new Registrar().Satisfy<ClassWithSingleDependency>().With<ClassWithSingleDependency>()
                .Satisfy<ClassWithNoArguments>().With(dependency);

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithSingleDependency>();

            Assert.That(resolvedObject, Is.InstanceOf<ClassWithSingleDependency>(), "expected resolved object to be of type ClassWithSingleDependency");
            Assert.That(resolvedObject.Argument1, Is.EqualTo(dependency), "expected dependency to have been resolved also");
        }
        public AccomodationService()
        {
            Registrar registrar = Registrar.getInstance();

            registrar.OnRegistration += PrepareRoom;
        }
示例#46
0
        public void Resolving_an_object_with_int_parameter_not_supplied_should_resolve_it_from_app_settings()
        {
            var registrar = new Registrar().Satisfy<ClassWithAppSettingIntArgument>().With<ClassWithAppSettingIntArgument>();

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithAppSettingIntArgument>();

            Assert.That(resolvedObject.TimeOutInSeconds, Is.EqualTo(int.Parse(ConfigurationManager.AppSettings["timeOutInSeconds"])));
        }
示例#47
0
文件: RelayNode.cs 项目: zrisher/ARMS
        /// <summary>
        /// Updates direct connections between this node and other nodes.
        /// When debug is set, checks connection to primary storage node.
        /// </summary>
        public void Update100()
        {
            s_sendPositionTo.Clear();

            bool checkPrimary = false;

            Registrar.ForEach((RelayNode node) => {
                if (node == this)
                {
                    return;
                }

                CommunicationType connToNode = TestConnection(node);

                if (connToNode == CommunicationType.TwoWay)
                {
                    if (m_directConnect.Add(node))
                    {
                        Log.TraceLog("Now connected to " + node.DebugName, Logger.severity.DEBUG);

                        if (this.Storage == null)
                        {
                            if (node.Storage != null)
                            {
                                Log.TraceLog("Using storage from other node: " + node.DebugName
                                             + ", primary: " + node.Storage.PrimaryNode.DebugName, Logger.severity.DEBUG);
                                this.Storage = node.Storage;
                            }
                        }
                        else if (node.Storage != null && this.Storage != node.Storage)
                        {
                            // should prefer blocks since they are less likely to be removed from world while offline
                            if (this.Block != null && node.Block == null)
                            {
                                Log.TraceLog("Nodes have different storages, copying to this node's storage because this node is a block", Logger.severity.DEBUG);
                                node.Storage.CopyTo(this.Storage);
                                node.Storage = this.Storage;
                            }
                            else if (this.Block == null && node.Block != null)
                            {
                                Log.TraceLog("Nodes have different storages, copying to other node's storage beacause other node is a block", Logger.severity.DEBUG);
                                this.Storage.CopyTo(node.Storage);
                                this.Storage = node.Storage;
                            }
                            else if (this.Storage.Size < node.Storage.Size)
                            {
                                Log.TraceLog("Nodes have different storages, copying to other node's storage", Logger.severity.DEBUG);
                                this.Storage.CopyTo(node.Storage);
                                this.Storage = node.Storage;
                            }
                            else
                            {
                                Log.TraceLog("Nodes have different storages, copying to this node's storage", Logger.severity.DEBUG);
                                node.Storage.CopyTo(this.Storage);
                                node.Storage = this.Storage;
                            }
                        }
                    }
                }
                else
                {
                    if (m_directConnect.Remove(node))
                    {
                        Log.TraceLog("No longer connected to " + node.DebugName, Logger.severity.DEBUG);
                        checkPrimary = true;
                    }
                }

                if (Storage != null)
                {
                    if (connToNode == CommunicationType.OneWay)
                    {
                        if (m_oneWayConnect.Add(node))
                        {
                            Log.TraceLog("New one-way connection to " + node.DebugName, Logger.severity.DEBUG);
                            Storage.AddPushTo(node);
                        }
                    }
                    else
                    {
                        if (m_oneWayConnect.Remove(node))
                        {
                            Log.TraceLog("Lost one-way connection to " + node.DebugName, Logger.severity.DEBUG);
                            Storage.RemovePushTo(node);
                        }
                    }
                }
            });

            if (Storage == null)
            {
                Log.DebugLog("No storage, creating a new one", Logger.severity.INFO);
                Storage = new RelayStorage(this);
            }
            else if (checkPrimary && !IsConnectedTo(Storage.PrimaryNode))
            {
                Log.DebugLog("Lost connection to primary, cloning storage", Logger.severity.INFO);
                Storage = Storage.Clone(this);
            }

            // connections don't update immediately, so don't worry about a single message (per block)
            Log.TraceLog("Not connected to primary node", Logger.severity.INFO, condition: !IsConnectedTo(Storage.PrimaryNode));

            IMyEntity topEntity = m_entity.GetTopMostParent();

            Log.TraceLog("Sending self to " + s_sendPositionTo.Count + " neutral/hostile storages", Logger.severity.TRACE);
            RelayStorage.Receive(s_sendPositionTo, new LastSeen(topEntity, LastSeen.DetectedBy.Broadcasting));

            if (Storage.VeryRecentRadarInfo(topEntity.EntityId))
            {
                return;
            }

            if (Block == null)
            {
                Storage.Receive(new LastSeen(topEntity, LastSeen.DetectedBy.Broadcasting, new LastSeen.RadarInfo(topEntity)));
            }
            else
            {
                foreach (IMyCubeGrid grid in AttachedGrid.AttachedGrids(Block.CubeGrid, AttachedGrid.AttachmentKind.Terminal, true))
                {
                    Storage.Receive(new LastSeen(grid, LastSeen.DetectedBy.Broadcasting, new LastSeen.RadarInfo(grid)));
                }
            }
        }
示例#48
0
        public void Resolving_an_object_with_names_in_different_case_to_ctor_should_still_set_them_correctly()
        {
            string arg1 = "someArgument";

            var registrar = new Registrar().Satisfy<ClassWithOneArgument>().With<ClassWithOneArgument>(new { ARGUMENT1 = arg1 });

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithOneArgument>();

            Assert.That(ReferenceEquals(resolvedObject.Argument1, arg1), Is.True, "expected argument 1 to be set");
        }
示例#49
0
 public void Setup()
 {
     _registrar = new Registrar();
     _scanner = new Scanner(_registrar);
 }
示例#50
0
        public void Resolving_an_object_with_string_parameter_not_supplied_should_resolve_it_from_app_settings()
        {
            var registrar = new Registrar().Satisfy<ClassWithAppSettingStringArgument>().With<ClassWithAppSettingStringArgument>();

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithAppSettingStringArgument>();

            Assert.That(resolvedObject.WebServiceUrl, Is.EqualTo(ConfigurationManager.AppSettings["webServiceUrl"]));
        }
 protected override void When()
 {
     backingStore = new BerkeleyBackingStore(new DefaultBerkeleyBackingStoreEnvironment(TempDir));
     var registrar = new Registrar<BerkeleyBackingStore>(backingStore);
     registrar.PerformRegistration(
         context =>
         {
             context.Graph<GraphAffectedByNewIndex>();
             context.Index(new ExistingIndex());
             context.Index(new NewIndex());
         });
     registrar.ApplyRegistration();
     registry = registrar.Registry;
     sessionFactory = new SessionFactory(registry);
 }
示例#52
0
 public void AddRequestClient <T>(Uri destinationAddress, RequestTimeout timeout)
     where T : class
 {
     Registrar.RegisterRequestClient <T>(destinationAddress, timeout);
 }
示例#53
0
		public void TestReplaceRenderer ()
		{
			var registrar = new Registrar<MockRenderer> ();

			registrar.Register (typeof (View), typeof (MockRenderer));
			registrar.Register (typeof (Button), typeof (ButtonMockRenderer));
			registrar.Register (typeof (Button), typeof (ShinyButtonMockRenderer));

			var buttonRenderer = registrar.GetHandler (typeof (Button));

			Assert.That (buttonRenderer, Is.InstanceOf<ShinyButtonMockRenderer>());
		}
示例#54
0
        public void Resolving_an_object_with_string_parameter_that_exists_in_connstrings_and_appsettings_should_report_error()
        {
            var registrar = new Registrar().Satisfy<ClassWithDuplicatedSettingArgument>().With<ClassWithDuplicatedSettingArgument>();

            Assert.That(() => new Resolver(registrar.Registrations).Resolve<ClassWithDuplicatedSettingArgument>(),
                Throws.ArgumentException.With.Message.EqualTo("Duplicated setting name! duplicatedsetting exists as both a connection string and application setting."));
        }
示例#55
0
 public void AddRequestClient <T>(RequestTimeout timeout)
     where T : class
 {
     Registrar.RegisterRequestClient <T>(timeout);
 }
示例#56
0
        public void Resolving_a_factory_function_should_get_back_the_same_object_we_registered()
        {
            var registeredObject = new ClassWithNoArguments();
            Func<IClass> factoryFunction = () => registeredObject;

            var registrar = new Registrar().Satisfy<IClass>().With(factoryFunction);

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<IClass>();

            Assert.That(ReferenceEquals(registeredObject, resolvedObject), Is.True, "the 2 object references are not the same");
        }
示例#57
0
        public void Resolving_an_object_with_string_parameter_not_supplied_should_resolve_it_from_connection_strings()
        {
            var registrar = new Registrar().Satisfy<ClassWithConnectionStringArgument>().With<ClassWithConnectionStringArgument>();

            var resolvedObject = new Resolver(registrar.Registrations).Resolve<ClassWithConnectionStringArgument>();

            Assert.That(resolvedObject.ConnString, Is.EqualTo(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString));
        }
示例#58
0
 protected void Page_Load(object sender, EventArgs e)
 {
     logica = new Registrar();
 }