Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public void All_mappings_should_be_configured_correctly()
        {
            var startup = new Startup();
            startup.ConfigureAutomapper();

            Mapper.AssertConfigurationIsValid();
        }
Exemplo n.º 2
0
	    public OwinHttpServer(InMemoryRavenConfiguration config, DocumentDatabase db = null, bool useHttpServer = true, Action<RavenDBOptions> configure = null)
		{
	        startup = new Startup(config, db);
	        if (configure != null)
	            configure(startup.Options);
		    owinEmbeddedHost = OwinEmbeddedHost.Create(app => startup.Configuration(app));

	        if (!useHttpServer)
	        {
	            return;
	        }
            server = WebApp.Start("http://+:" + config.Port, app =>  //TODO DH: configuration.ServerUrl doesn't bind properly
			{
				var listener = (HttpListener) app.Properties["System.Net.HttpListener"];
			    if (listener != null)
			    {
			        new WindowsAuthConfigureHttpListener().Configure(listener, config);
			    }
			    startup.Configuration(app);
				app.Use(async (context, _) =>
				{
					context.Response.StatusCode = 404;
					context.Response.ReasonPhrase = "Not Found";
					await context.Response.Body.WriteAsync(NotFoundBody, 0, NotFoundBody.Length);
				});
			});
		}
Exemplo n.º 3
0
        static void Main()
        {
            //Initialize startup object
            var startup = new Startup();

            string baseAddress = null;
            //baseAddress = "http://localhost:9000/"; //Uncomment this line to also listen on localhost:9000

            //Start WebAPI OWIN host 
            using (WebApp.Start(url: baseAddress, startup: startup.Configuration))
            {
                //Start RestBus Subscriber/host

                var amqpUrl = ConfigurationManager.AppSettings["ServerUri"]; //AMQP URI for RabbitMQ server
                var serviceName = "speedtest"; //Uniquely identifies this service

                var msgMapper = new BasicMessageMapper(amqpUrl, serviceName);
                var subscriber = new RestBusSubscriber(msgMapper);
                using (var host = new RestBusHost(subscriber, startup.Config))
                {
                    host.Start();
                    Console.WriteLine("Server started ... Ctrl-C to quit.");
                    Console.ReadLine();
                }
            }
        }
 public ValuesControllerIntegrationTests()
 {
     var environment = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();
     var startup = new Startup(new HostingEnvironment());
     _app = startup.Configure;
     _services = startup.ConfigureServices;
 }
        public ActionResult Index([Diagnostics.NotNull] string route)
        {
            var actionResult = this.AuthenticateUser();
            if (actionResult != null)
            {
                return actionResult;
            }

            var output = new StringWriter();
            Console.SetOut(output);

            var projectDirectory = WebUtil.GetQueryString("pd");
            var toolsDirectory = WebUtil.GetQueryString("td");
            var binDirectory = FileUtil.MapPath("/bin");

            var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).WithExtensionsDirectory(binDirectory).Start();
            if (app == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, output.ToString());
            }

            var instance = ((CompositionContainer)app.CompositionService).GetExportedValue<IWebApi>(route);
            if (instance == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Route not found: " + route);
            }

            var result = instance.Execute(app);

            return result ?? Content(output.ToString(), "text/plain");
        }
Exemplo n.º 6
0
        public void Start(string projectDirectory, [CanBeNull] Action mock = null)
        {
            var toolsDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;

            var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).Start();
            if (app == null)
            {
                throw new ConfigurationException("Oh no, nothing works!");
            }

            Configuration = app.Configuration;
            CompositionService = app.CompositionService;

            mock?.Invoke();

            Trace = CompositionService.Resolve<ITraceService>();
            FileSystem = CompositionService.Resolve<IFileSystemService>();
            ParseService = CompositionService.Resolve<IParseService>();
            ProjectService = CompositionService.Resolve<IProjectService>();
            ConfigurationService = CompositionService.Resolve<IConfigurationService>();
            SnapshotService = CompositionService.Resolve<ISnapshotService>();
            CheckerService = CompositionService.Resolve<ICheckerService>();
            QueryService = CompositionService.Resolve<IQueryService>();
            LanguageService = CompositionService.Resolve<ILanguageService>();
            RuleService = CompositionService.Resolve<IRuleService>();
            XPathService = CompositionService.Resolve<IXPathService>();
        }
Exemplo n.º 7
0
 /// <summary>
 /// 默认构造函数
 /// </summary>
 public Adapter()
 {
     var builder = new AppBuilder();
     var startup = new Startup();
     startup.Configuration(builder);
     _owinApp = builder.Build();
 }
Exemplo n.º 8
0
        public void Start(string projectDirectory, [CanBeNull] Action mock = null)
        {
            var toolsDirectory = Path.Combine(projectDirectory, "sitecore.tools");

            var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).WithWebsiteAssemblyResolver().Start();
            if (app == null)
            {
                Debug.Write(projectDirectory);
                throw new ConfigurationException(string.Format("Project path not found: {0}", projectDirectory));
            }

            Configuration = app.Configuration;
            CompositionService = app.CompositionService;

            mock?.Invoke();

            Trace = CompositionService.Resolve<ITraceService>();
            FileSystem = CompositionService.Resolve<IFileSystemService>();
            ParseService = CompositionService.Resolve<IParseService>();
            ProjectService = CompositionService.Resolve<IProjectService>();
            ConfigurationService = CompositionService.Resolve<IConfigurationService>();
            SnapshotService = CompositionService.Resolve<ISnapshotService>();
            CheckerService = CompositionService.Resolve<ICheckerService>();
            QueryService = CompositionService.Resolve<IQueryService>();
        }
        public void TestSumValues()
        {
            var sse = SSEProvider.DeserializeData(sseAsString);

            var s = new Startup();
       //     var r = s.PreviousAndCurrentToDelta(sse, sse);
        }
Exemplo n.º 10
0
	public Test(){
		var environment = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
 		var hostingEnvironment = new HostingEnvironment(environment);
        var startup = new Startup(hostingEnvironment);
		var testServer = TestServer.Create(x => startup.Configure(x, hostingEnvironment), startup.ConfigureServices);
		client = testServer.CreateClient();
	}
Exemplo n.º 11
0
        public IList<IDisposable> Start()
        {
            List<IDisposable> servers = new List<IDisposable>();

            //Initialize startup object
            var startup = new Startup();

            string baseAddress = null;
            //baseAddress = "http://localhost:9000/"; //Uncomment this line to also listen via HTTP on localhost:9000

            //Start WebAPI OWIN host 
            servers.Add(WebApp.Start(url: baseAddress, startup: startup.Configuration));

            //Start RestBus Subscriber/host

            var amqpUrl = ConfigurationManager.AppSettings["rabbitmqserver"]; //AMQP URI for RabbitMQ server
            var serviceName = "test"; //Uniquely identifies this service

            var msgMapper = new BasicMessageMapper(amqpUrl, serviceName);
            var subscriber = new RestBusSubscriber(msgMapper);
            var host = new RestBusHost(subscriber, startup.Config);

            host.Start();
            Console.WriteLine("Server started ... Ctrl-C to quit.");

            servers.Add(host);
            return servers;

        }
 public TypescriptCodeProvider()
 {
     var unity = new UnityContainer();
     var startup = new Startup(unity);
     startup.Initialize();
     _codeGenerator = unity.Resolve<ICodeGenerator>();
 }
        private static void ConfigureContainer(ContainerBuilder containerBuilder, Assembly assembly)
        {
            var modules = new Startup().GetModules();

            foreach (var module in modules)
                containerBuilder.RegisterModule(module);

            AutofacExtension.ConfigureContainer(containerBuilder, new WebOption { UseApi = true, UseMvc = true }, assembly);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            var baseUri = ConfigurationManager.AppSettings["BaseUri"];

            Console.WriteLine("Starting web Server...");
            var startup = new Startup();
            WebApp.Start(baseUri, appBuilder => startup.Configuration(appBuilder));
            Console.WriteLine("Server running at {0} - press Enter to quit. ", baseUri);
            Console.ReadLine();
        }
        public void Configuration(IAppBuilder app)
        {
            //AppDomain.CurrentDomain.AssemblyResolve += DynamicAssemblyResolver.WebAssemblyResolveHandler;

            var startup = new Startup();
            startup.Configuration(app);

            AreaRegistration.RegisterAllAreas();
            BundleConfig.Register(BundleTable.Bundles);
        }
Exemplo n.º 16
0
        public BaseTest()
        {
            var environment = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();

            var startup = new Startup(environment);
            _applicationBuilder = startup.Configure;
            _serviceColletion = startup.ConfigureServices;

            _testServer = TestServer.Create(_applicationBuilder, _serviceColletion);
            _httpClient = _testServer.CreateClient();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the runtime startup task regardless of its order in the startup tasks.
        /// </summary>
        /// <param name="roleStartup">The role startup tasks</param>
        /// <returns>The runtime startup task</returns>
        public static Task GetRuntimeStartupTask(Startup roleStartup)
        {
            if (roleStartup.Task != null)
            {
                return roleStartup.Task.FirstOrDefault<Task>(t =>
                t.commandLine.Equals(Resources.WebRoleStartupTaskCommandLine)
             || t.commandLine.Equals(Resources.WorkerRoleStartupTaskCommandLine));
            }

            return null;
        }
Exemplo n.º 18
0
 protected async Task<HttpResponseMessage> SubmitGet(DbConnection effortConnection, string requestPath)
 {
     using (var server = TestServer.Create(app =>
     {
         var startup = new Startup(() => new TestDbContext(effortConnection, false));
         startup.Configuration(app);
     }))
     {
         var uri = new Uri(BaseUri, requestPath);
         var response = await server.CreateRequest(uri.ToString()).AddHeader("Accept", JsonApiContentType).GetAsync();
         return response;
     }
 }
 public static void InitializeTests(TestContext context)
 {
     server = TestServer.Create(AppBuilder =>
     {
         var httpConfig = new HttpConfiguration();
         WebApiConfig.Register(httpConfig);
         var webApiStartup = new Startup();
         webApiStartup.Configuration(AppBuilder);
         AppBuilder.UseWebApi(httpConfig);
     });
     client = server.HttpClient;
     Seed();
 }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;

            // register DI
            var startup = new Startup();
            startup.Configure();

            // instantiate tasks
            _photoDownloaderTask = new PhotoDownloaderTask();
            _photoDownloaderTask.Start();
        }
Exemplo n.º 21
0
 // Use this for initialization
 void Start()
 {
     if (instance != null) {
         GameObject.DestroyImmediate(gameObject);
         return;
     }
     instance = this;
     //Set the scripts object to not be destroyed
     DontDestroyOnLoad (gameObject);
     // Load Coordinated Effects
     //CoordinatedEffectSystem.RegisterCoordinatedEffect("CoordMeleeStrikeEffect", new CoordMeleeStrikeEffect());
     //CoordinatedEffectSystem.RegisterCoordinatedEffect("Backflip", new BackflipEffect());
 }
 public static void AssemblyInit(TestContext context)
 {
     // Start OWIN testing HTTP server with Web API support
     TestWebServer = TestServer.Create(appBuilder =>
     {
         var config = new HttpConfiguration();
         WebApiConfig.Register(config);
         var webAppStartup = new Startup();
         webAppStartup.Configuration(appBuilder);
         appBuilder.UseWebApi(config);
     });
     HttpClient = TestWebServer.HttpClient;
 }
Exemplo n.º 23
0
        public static void LoadProjects()
        {
            _isLoaded = true;

            ProjectContexts.Clear();

            var dataFolder = FileUtil.MapPath(Settings.DataFolder);
            var pathfinderFolder = Path.Combine(dataFolder, "Pathfinder");

            var fileName = Path.Combine(pathfinderFolder, "projects." + Environment.MachineName + ".xml");
            if (!FileUtil.FileExists(fileName))
            {
                return;
            }

            var xml = FileUtil.ReadFromFile(fileName);
            var root = xml.ToXElement();
            if (root == null)
            {
                return;
            }

            foreach (var element in root.Elements())
            {
                var toolsDirectory = element.GetAttributeValue("toolsdirectory");
                if (!Directory.Exists(toolsDirectory))
                {
                    continue;
                }

                var projectDirectory = element.GetAttributeValue("projectdirectory");
                if (!Directory.Exists(projectDirectory))
                {
                    continue;
                }

                var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).Start();
                if (app == null)
                {
                    throw new ConfigurationException("Failed to load configuration");
                }

                var projectService = app.CompositionService.Resolve<IProjectService>();
                var projectOptions = projectService.GetProjectOptions();
                var projectTree = projectService.GetProjectTree(projectOptions).With(toolsDirectory, projectDirectory);

                var projectContext = new ProjectContext(app.Configuration, app.CompositionService, projectTree);

                ProjectContexts.Add(projectContext);
            }
        }
        public static void AssemblyInit(TestContext context)
        {
            httpTestServer = TestServer.Create(appBuilder =>
            {
                var config = new HttpConfiguration();
                WebApiConfig.Register(config);
                var startup = new Startup();

                startup.Configuration(appBuilder);
                appBuilder.UseWebApi(config);
            });
            httpClient = httpTestServer.HttpClient;
            SeedDatabase();
        }
Exemplo n.º 25
0
        public void Configuration(IAppBuilder app)
        {
            // TODO: Files...
            var options = new FileServerOptions
            {
                RequestPath = new PathString("/app"),
                FileSystem = new PhysicalFileSystem("app")
            };

            app.UseFileServer(options);

            var startup = new Startup();
            startup.Configuration(app);
        }
Exemplo n.º 26
0
        // [Test]
        public void ProjectTests()
        {
            var projectDirectory = PathHelper.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty, GoodWebsite);
            var toolsDirectory = Path.Combine(projectDirectory, "sitecore.tools");

            var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).Start();
            if (app == null)
            {
                throw new ConfigurationException("Oh no, nothing works!");
            }

            var emitter = app.CompositionService.Resolve<EmitterService>();
            emitter.Start();
        }
Exemplo n.º 27
0
	    public OwinHttpServer(InMemoryRavenConfiguration config, DocumentDatabase db = null, bool useHttpServer = true, Action<RavenDBOptions> configure = null)
		{
	        startup = new Startup(config, db);
	        if (configure != null)
	            configure(startup.Options);
		    owinEmbeddedHost = OwinEmbeddedHost.Create(app => startup.Configuration(app));

	        if (!useHttpServer)
	        {
	            return;
	        }

	        EnableHttpServer(config);
		}
Exemplo n.º 28
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public Adapter()
        {
            // 创建默认的AppBuilder
            var builder = new AppBuilder();

            // 实例化 Startup类
            // 这个类中必须有“Configuration”方法
            var startup = new Startup();

            // 调用Configuration方法,把自己的处理函数注册到处理流程中
            startup.Configuration(builder);

            // 生成OWIN“入口”函数
            _owinApp = builder.Build();
        }
Exemplo n.º 29
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            var viewModel = new StartupViewModel();
            var view = new Startup();

            viewModel.OkCommand = new RelayCommand(() =>
            {
                int clientId;
                if (!int.TryParse(viewModel.ClientId, out clientId))
                {
                    MessageBox.Show("Client id must be a number");
                    return;
                }

                int serverCommandPort;
                if (!int.TryParse(viewModel.CommandPort, out serverCommandPort))
                {
                    MessageBox.Show("Command port must be a number");
                    return;
                }

                int serverPublishPort;
                if (!int.TryParse(viewModel.PublishPort, out serverPublishPort))
                {
                    MessageBox.Show("Publish port must be a number");
                    return;
                }

                var config = new Configuration
                {
                    ClientId = clientId,
                    ServerAddress = viewModel.ServerAddress,
                    ServerCommandPort = serverCommandPort,
                    ServerPublishPort = serverPublishPort
                };
                StartApplication(config);
                view.Close();
            });

            viewModel.CancelCommand = new RelayCommand(() =>
            {
                view.Close();
                App_OnExit(this, null);
            });

            view.DataContext = viewModel;
            view.ShowDialog();
        }
        public void TestInit()
        {
            // Start OWIN testing HTTP server with Web API support
            this.httpTestServer = TestServer.Create(appBuilder =>
            {
                var config = new HttpConfiguration();
                WebApiConfig.Register(config);

                var startup = new Startup();
                startup.ConfigureAuth(appBuilder);

                appBuilder.UseWebApi(config);
            });
            
            this.httpClient = this.httpTestServer.HttpClient;
        }
Exemplo n.º 31
0
        public SettingsModel(AppBar appbar)
        {
            DockEdgeItems = new DockEdge[2] {
                DockEdge.Left, DockEdge.Right
            };
            DockEdge = Properties.Settings.Default.DockEdge;

            Monitor[] _monitors = Monitor.GetMonitors();

            ScreenItems = _monitors.Select((s, i) => new ScreenItem()
            {
                Index = i, Text = string.Format("#{0}", i + 1)
            }).ToArray();

            if (Properties.Settings.Default.ScreenIndex < _monitors.Length)
            {
                ScreenIndex = Properties.Settings.Default.ScreenIndex;
            }
            else
            {
                ScreenIndex = _monitors.Where(s => s.IsPrimary).Select((s, i) => i).Single();
            }

            XOffset = Properties.Settings.Default.XOffset;

            YOffset = Properties.Settings.Default.YOffset;

            PollingInterval = Properties.Settings.Default.PollingInterval;

            UseAppBar = Properties.Settings.Default.UseAppBar;

            AlwaysTop = Properties.Settings.Default.AlwaysTop;

            HighDPISupport = Properties.Settings.Default.HighDPISupport;

            ClickThrough = Properties.Settings.Default.ClickThrough;

            ShowTrayIcon = Properties.Settings.Default.ShowTrayIcon;

            CheckForUpdates = Properties.Settings.Default.CheckForUpdates;

            RunAtStartup = Startup.StartupTaskExists();

            SidebarWidth = Properties.Settings.Default.SidebarWidth;

            BGColor = Properties.Settings.Default.BGColor;

            BGOpacity = Properties.Settings.Default.BGOpacity;

            FontSettingItems = new FontSetting[5]
            {
                FontSetting.x10,
                FontSetting.x12,
                FontSetting.x14,
                FontSetting.x16,
                FontSetting.x18
            };
            FontSetting = Properties.Settings.Default.FontSetting;

            FontColor = Properties.Settings.Default.FontColor;

            AlertFontColor = Properties.Settings.Default.AlertFontColor;

            DateSettingItems = new DateSetting[4]
            {
                DateSetting.Disabled,
                DateSetting.Short,
                DateSetting.Normal,
                DateSetting.Long
            };
            DateSetting = Properties.Settings.Default.DateSetting;

            CollapseMenuBar = Properties.Settings.Default.CollapseMenuBar;

            ShowClock = Properties.Settings.Default.ShowClock;

            Clock24HR = Properties.Settings.Default.Clock24HR;

            if (appbar.Ready)
            {
                foreach (MonitorConfig _record in Properties.Settings.Default.MonitorConfig)
                {
                    _record.Hardware = (
                        from hw in appbar.Model.MonitorManager.GetHardware(_record.Type)
                        join config in _record.Hardware on hw.ID equals config.ID into c
                        from config in c.DefaultIfEmpty(hw)
                        select config
                        ).ToArray();
                }
            }

            MonitorConfig = Properties.Settings.Default.MonitorConfig;

            if (Properties.Settings.Default.Hotkeys != null)
            {
                ToggleKey = Properties.Settings.Default.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Toggle);

                ShowKey = Properties.Settings.Default.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Show);

                HideKey = Properties.Settings.Default.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Hide);

                ReloadKey = Properties.Settings.Default.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Reload);

                CloseKey = Properties.Settings.Default.Hotkeys.FirstOrDefault(k => k.Action == Hotkey.KeyAction.Close);
            }

            IsChanged = false;
        }
Exemplo n.º 32
0
        public void Save()
        {
            if (!string.Equals(Culture, Framework.Settings.Instance.Culture, StringComparison.Ordinal))
            {
                MessageBox.Show(Resources.LanguageChangedText, Resources.LanguageChangedTitle, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
            }

            Framework.Settings.Instance.DockEdge        = DockEdge;
            Framework.Settings.Instance.ScreenIndex     = ScreenIndex;
            Framework.Settings.Instance.Culture         = Culture;
            Framework.Settings.Instance.UIScale         = UIScale;
            Framework.Settings.Instance.XOffset         = XOffset;
            Framework.Settings.Instance.YOffset         = YOffset;
            Framework.Settings.Instance.PollingInterval = PollingInterval;
            Framework.Settings.Instance.UseAppBar       = UseAppBar;
            Framework.Settings.Instance.AlwaysTop       = AlwaysTop;
            Framework.Settings.Instance.ShowAltTab      = ShowAltTab;
            Framework.Settings.Instance.ClickThrough    = ClickThrough;
            Framework.Settings.Instance.ShowTrayIcon    = ShowTrayIcon;
            Framework.Settings.Instance.AutoUpdate      = AutoUpdate;
            Framework.Settings.Instance.RunAtStartup    = RunAtStartup;
            Framework.Settings.Instance.StartHidden     = StartHidden;
            Framework.Settings.Instance.SidebarWidth    = SidebarWidth;
            Framework.Settings.Instance.AutoBGColor     = AutoBGColor;
            Framework.Settings.Instance.BGColor         = BGColor;
            Framework.Settings.Instance.BGOpacity       = BGOpacity;
            Framework.Settings.Instance.TextAlign       = TextAlign;
            Framework.Settings.Instance.FontSetting     = FontSetting;
            Framework.Settings.Instance.FontColor       = FontColor;
            Framework.Settings.Instance.AlertFontColor  = AlertFontColor;
            Framework.Settings.Instance.AlertBlink      = AlertBlink;
            Framework.Settings.Instance.DateSetting     = DateSetting;
            Framework.Settings.Instance.CollapseMenuBar = CollapseMenuBar;
            Framework.Settings.Instance.ShowClock       = ShowClock;
            Framework.Settings.Instance.Clock24HR       = Clock24HR;

            MonitorConfig[] _config = MonitorConfig.Select(c => c.Clone()).ToArray();

            for (int i = 0; i < _config.Length; i++)
            {
                HardwareConfig[] _hardware = _config[i].HardwareOC.ToArray();

                for (int v = 0; v < _hardware.Length; v++)
                {
                    _hardware[v].Order = Convert.ToByte(_hardware.Length - v);
                }

                _config[i].Hardware   = _hardware;
                _config[i].HardwareOC = null;

                _config[i].Order = Convert.ToByte(_config.Length - i);
            }

            Framework.Settings.Instance.MonitorConfig = _config;

            List <Hotkey> _hotkeys = new List <Hotkey>();

            if (ToggleKey != null)
            {
                _hotkeys.Add(ToggleKey);
            }

            if (ShowKey != null)
            {
                _hotkeys.Add(ShowKey);
            }

            if (HideKey != null)
            {
                _hotkeys.Add(HideKey);
            }

            if (ReloadKey != null)
            {
                _hotkeys.Add(ReloadKey);
            }

            if (CloseKey != null)
            {
                _hotkeys.Add(CloseKey);
            }

            if (CycleEdgeKey != null)
            {
                _hotkeys.Add(CycleEdgeKey);
            }

            if (CycleScreenKey != null)
            {
                _hotkeys.Add(CycleScreenKey);
            }

            Framework.Settings.Instance.Hotkeys = _hotkeys.ToArray();

            Framework.Settings.Instance.Save();

            App.RefreshIcon();

            if (RunAtStartup)
            {
                Startup.EnableStartupTask();
            }
            else
            {
                Startup.DisableStartupTask();
            }

            IsChanged = false;
        }
Exemplo n.º 33
0
        /// <summary>
        /// Starts Ignite with given configuration.
        /// </summary>
        /// <returns>Started Ignite.</returns>
        public static unsafe IIgnite Start(IgniteConfiguration cfg)
        {
            IgniteArgumentCheck.NotNull(cfg, "cfg");

            lock (SyncRoot)
            {
                // 0. Init logger
                var log = cfg.Logger ?? new JavaLogger();

                log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version);

                // 1. Check GC settings.
                CheckServerGc(cfg, log);

                // 2. Create context.
                IgniteUtils.LoadDlls(cfg.JvmDllPath, log);

                var cbs = new UnmanagedCallbacks(log);

                IgniteManager.CreateJvmContext(cfg, cbs, log);
                log.Debug("JVM started.");

                var gridName = cfg.IgniteInstanceName;

                if (cfg.AutoGenerateIgniteInstanceName)
                {
                    gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid();
                }

                // 3. Create startup object which will guide us through the rest of the process.
                _startup = new Startup(cfg, cbs);

                IUnmanagedTarget interopProc = null;

                try
                {
                    // 4. Initiate Ignite start.
                    UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null);


                    // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
                    var node = _startup.Ignite;
                    interopProc = node.InteropProcessor;

                    var javaLogger = log as JavaLogger;
                    if (javaLogger != null)
                    {
                        javaLogger.SetProcessor(interopProc);
                    }

                    // 6. On-start callback (notify lifecycle components).
                    node.OnStart();

                    Nodes[new NodeKey(_startup.Name)] = node;

                    return(node);
                }
                catch (Exception)
                {
                    // 1. Perform keys cleanup.
                    string name = _startup.Name;

                    if (name != null)
                    {
                        NodeKey key = new NodeKey(name);

                        if (Nodes.ContainsKey(key))
                        {
                            Nodes.Remove(key);
                        }
                    }

                    // 2. Stop Ignite node if it was started.
                    if (interopProc != null)
                    {
                        UU.IgnitionStop(interopProc.Context, gridName, true);
                    }

                    // 3. Throw error further (use startup error if exists because it is more precise).
                    if (_startup.Error != null)
                    {
                        // Wrap in a new exception to preserve original stack trace.
                        throw new IgniteException("Failed to start Ignite.NET, check inner exception for details",
                                                  _startup.Error);
                    }

                    throw;
                }
                finally
                {
                    _startup = null;

                    if (interopProc != null)
                    {
                        UU.ProcessorReleaseStart(interopProc);
                    }
                }
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Creates an Epicor Session
        /// This is a bit of a heavy hitter, it creates a copy of the current system configuration and copies it to a temporary location
        /// then sets an alternate cache folder in order for us to have our own unique undisturbed cache
        /// Then it creates an epicor session and instanciates all the apropriate static libraries to allow
        /// epicor to operate as if it was running a full client, there's quite a bit in here that you probably won't understand without
        /// digging through the Epicor.exe and other libraries. Just go with it
        ///
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private static Session GetEpiSession(CommandLineParams o)
        {
            string  password = o.Password;
            Session ses      = null;

            //Create a copy of the config file so that we can set a temporary cache folder for our instance
            var newConfig = Path.GetTempFileName().Replace(".tmp", ".sysconfig");

            File.Copy(o.ConfigFile, newConfig, true);
            o.NewConfig = newConfig;

            //Create a temp directory to store our epicor cache
            DirectoryInfo di = Directory.CreateDirectory(Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()));

            o.Temp = di.FullName;
            Log.Debug($"Created Temp Epicor Directory at: {o.Temp}");
            var    x            = XElement.Load(newConfig);
            string currentCache = x.Descendants("appSettings").Elements().Where(r => r.Name == "AlternateCacheFolder").FirstOrDefault().FirstAttribute.Value;

            //Set our new Temp Cache location in our new config
            x.Descendants("appSettings").Elements().Where(r => r.Name == "AlternateCacheFolder").FirstOrDefault().FirstAttribute.Value = di.FullName;
            x.Save(newConfig);

            try
            {
                password = NeedtoEncrypt(o);
                ses      = new Session(o.Username, password, Session.LicenseType.Default, newConfig);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed to Login");
                ShowProgressBar(false);

                LoginForm frm = new LoginForm(o.EpicorClientFolder);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    ShowProgressBar();
                    o.Username   = Settings.Default.Username;
                    o.Password   = Settings.Default.Password;
                    o.ConfigFile = Settings.Default.Environment;
                    o.Encrypted  = "true";
                    password     = NeedtoEncrypt(o);

                    try
                    {
                        ses = new Session(o.Username, password, Session.LicenseType.Default, newConfig);
                    }
                    catch (Exception)
                    {
                        Log.Error(ex, $"Failed to Login Again");
                        MessageBox.Show("Failed to Authenticate", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        ses = null;
                    }
                    ShowProgressBar(true);
                }
            }

            if (ses != null)
            {
                SecRightsHandler.CacheBOSecSettings(ses);


                //Cause Brandon likes  hot keys... like a douche here's a BUNCHA un-necesary code... sigh!
                if (string.IsNullOrEmpty(currentCache))
                {
                    currentCache = $"{Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData))}";
                }
                string deepPath = "";
                var    s        = Directory.GetDirectories(Path.Combine(o.Temp, "Epicor"))[0];
                deepPath = Path.Combine("Epicor", Path.GetFileName(s));
                s        = Directory.GetDirectories(s)[0];
                deepPath = Path.Combine(deepPath, Path.GetFileName(s));
                s        = Directory.GetDirectories(s)[0];
                deepPath = Path.Combine(deepPath, Path.GetFileName(s));
                deepPath = Path.Combine(deepPath, "Customization");
                if (File.Exists(Path.Combine(currentCache, deepPath)))
                {
                    foreach (string gk in Directory.GetFiles(Path.Combine(currentCache, deepPath), "AllForms*.xml"))
                    {
                        string newPat = Path.Combine(Path.Combine(o.Temp, deepPath), Path.GetFileName(gk));
                        if (!Directory.Exists(Path.GetDirectoryName(newPat)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(newPat));
                        }
                        File.Copy(gk, newPat);
                    }
                }


                dynamic curMRUList = typeof(SecRightsHandler).GetField("_currMRUList", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);

                Startup.SetupPlugins(ses);

                if (!string.IsNullOrEmpty(o.DLLLocation))
                {
                    String fineName = Path.GetFileName(o.DLLLocation);
                    string newPath  = Path.GetDirectoryName((string)curMRUList.GetType().GetProperty("SavePath", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).GetValue(curMRUList)).Replace("BOSecMRUList", "CustomDLLs");
                    o.DLLLocation = Path.Combine(newPath, fineName);
                }

                epi.Ice.Lib.Configuration c = new epi.Ice.Lib.Configuration(newConfig);

                c.AlternateCacheFolder = di.FullName;
                Assembly assy  = Assembly.LoadFile(Path.Combine(o.EpicorClientFolder, "Epicor.exe"));
                TypeInfo ty    = assy.DefinedTypes.Where(r => r.Name == "ConfigureForAutoDeployment").FirstOrDefault();
                dynamic  thing = Activator.CreateInstance(ty);

                object[] args = { c };
                try
                {
                    thing.GetType().GetMethod("SetUpAssemblyRetrieversAndPossiblyGetNewConfiguration", BindingFlags.Instance | BindingFlags.Public).Invoke(thing, args);
                    WellKnownAssemblyRetrievers.AutoDeployAssemblyRetriever  = (IAssemblyRetriever)thing.GetType().GetProperty("AutoDeployAssemblyRetriever", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(thing);
                    WellKnownAssemblyRetrievers.SessionlessAssemblyRetriever = (IAssemblyRetriever)thing.GetType().GetProperty("SessionlessAssemblyRetriever", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(thing);
                }
                catch (Exception ee)
                {
                    Log.Error(ee.ToString());
                }
                Startup.PreStart(ses, true);
                launcher = new EpicorLauncher();
            }
            return(ses);
        }
Exemplo n.º 35
0
        public void AllSavesTest()
        {
            _output.WriteLine("Starting Sistema test ...");
            ISistema sistema = Startup.BuildSistema();

            //Insert Cotizacion
            {
                _output.WriteLine("Testing insert ..");
                Persona persona = new Persona()
                {
                    Nombre  = "Felipe",
                    Email   = "*****@*****.**",
                    Materno = "Varas",
                    Paterno = "jara",
                    Rut     = "194517319"
                };
                Servicio servicio = new Servicio()
                {
                    Estado = EstadoServicio.PREPRODUCCION,
                    Nombre = "video",
                    Precio = 230000
                };
                Cotizacion cotizacion = new Cotizacion()
                {
                    estado  = EstadoCotizacion.BORRADOR,
                    Fecha   = DateTime.Now,
                    Persona = persona,
                };
                Persona personaNull = new Persona()
                {
                    Nombre  = "",
                    Email   = " ",
                    Materno = " ",
                    Paterno = "",
                    Rut     = ""
                };

                Cotizacion cotizacionNull = new Cotizacion()
                {
                    estado  = EstadoCotizacion.RECHAZADO,
                    Fecha   = DateTime.Now,
                    Persona = null,
                };

                //Agregar servicio
                {
                    cotizacion.Add(servicio);
                    Assert.NotEmpty(cotizacion.Servicios);
                }
                _output.WriteLine("Done");
                _output.WriteLine("Probando guardar persona");
                //Guardar persona (exitosa)
                {
                    sistema.Save(persona);
                }
                //Guardar persona (no exitosa)
                {
                    Assert.Throws <Core.ModelException>(() => sistema.Save(personaNull));
                }
                _output.WriteLine("Done..");
                _output.WriteLine("Probando guardar cotizacion");
                //Guardar cotizacion (exitosa)
                {
                    sistema.Save(cotizacion);
                }
                //Guardar cotizacion (no exitosa)
                {
                    Assert.Throws <Core.ModelException>(() => sistema.Save(cotizacionNull));
                }
                _output.WriteLine("Done..");
                _output.WriteLine("Probando guardar Usuario");
                //Guardar Usuario (exitosa)
                {
                    sistema.Save(persona, "felipev123");
                }
                //Guardar Usuario (no exitosa)
                {
                    Assert.Throws <Core.ModelException>(() => sistema.Save(personaNull, null));
                    Assert.Throws <ArgumentNullException>(() => sistema.Save(persona, null));
                    Assert.Throws <Core.ModelException>(() => sistema.Save(personaNull, "felipev123"));
                }
                _output.WriteLine("Done..");
            }
        }
Exemplo n.º 36
0
 protected virtual void OnStartup(StartupEventArgs e)
 {
     Startup?.Invoke(this, e);
 }
Exemplo n.º 37
0
        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            var startup = new Startup();

            ProgramCommon.Main(args, startup);
        }
Exemplo n.º 38
0
 static void Main(string[] args)
 {
     Startup.Execute <EntitySpider>(args);
     Console.Read();
 }
Exemplo n.º 39
0
 public KSPAddonImproved(Startup mask, bool once = false)
 {
     runOnce = once;
     scenes  = mask;
 }
Exemplo n.º 40
0
    // Update is called once per frame
    void FixedUpdate()
    {
        Vector2 playerInput = new Vector2(Input.GetAxis("P2-Horizontal"), Input.GetAxis("P2-Vertical"));
        Vector2 rotInput    = new Vector2(Input.GetAxis("P2-Horizontal2"), Input.GetAxis("P2-Vertical2"));

        playerRB.velocity = playerInput * movementSpeed;

        if (rotInput.y == 0)
        {
            if (rotInput.x == 0)
            {
                // do nothing
            }
            else if (rotInput.x > 0)
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, 270);
            }
            else
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, 90);
            }
        }
        else if (rotInput.x == 0)
        {
            if (rotInput.y > 0)
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, 0);
            }
            else
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, 180);
            }
        }
        else if (rotInput.y > 0)
        {
            if (rotInput.x > 0) // Q1
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, (180 / Mathf.PI) * Mathf.Atan(rotInput.y / rotInput.x) - 90);
            }
            else // Q2
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, (180 / Mathf.PI) * Mathf.Atan(-rotInput.x / rotInput.y));
            }
        }
        else
        {
            if (rotInput.x < 0) // Q3
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, (180 / Mathf.PI) * Mathf.Atan(-rotInput.y / -rotInput.x) + 90);
            }
            else // Q4
            {
                childSprite.transform.eulerAngles = new Vector3(0, 0, 270 - (180 / Mathf.PI) * Mathf.Atan(rotInput.y / -rotInput.x));
            }
        }

        if (Input.GetAxis("P2-Trigger") < -.2)
        {
            if (!onpress)
            {
                List <Element> collectedElements = GameplayLogic.playerCollectedElements[1];

                if (collectedElements.Count > 2)
                {
                    playerSource.clip = Startup.GetRandomShootNoise();
                    playerSource.Play();

                    Debug.Log(collectedElements[0]);
                    Debug.Log(collectedElements[1]);
                    Debug.Log(collectedElements[2]);


                    if (collectedElements[0] == collectedElements[1] && collectedElements[1] == collectedElements[2] && collectedElements[0] == collectedElements[2])
                    {    // all three elements are the same.
                        Projectile projectile1 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                        projectile1.SetProperties(2, 45 * (gunTarget.position - transform.position), collectedElements[1], .30f);
                    }
                    else if (collectedElements[0] == collectedElements[1] || collectedElements[1] == collectedElements[2] || collectedElements[0] == collectedElements[2])
                    {     // two of the elements are the same.
                        if (collectedElements[0] != Element.Fire && collectedElements[1] != Element.Fire && collectedElements[2] != Element.Fire)
                        { // ice and lightning
                            Projectile projectile1 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            Projectile projectile2 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            projectile1.SetProperties(2, 30 * (gunRight.position - transform.position), Element.Ice, .20f);
                            projectile2.SetProperties(2, 30 * (gunLeft.position - transform.position), Element.Lightning, .20f);
                        }
                        else if (collectedElements[0] != Element.Ice && collectedElements[1] != Element.Ice && collectedElements[2] != Element.Ice)
                        { // fire and lightning
                            Projectile projectile1 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            Projectile projectile2 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            projectile1.SetProperties(2, 30 * (gunRight.position - transform.position), Element.Fire, .20f);
                            projectile2.SetProperties(2, 30 * (gunLeft.position - transform.position), Element.Lightning, .20f);
                        }
                        else if (collectedElements[0] != Element.Lightning && collectedElements[1] != Element.Lightning && collectedElements[2] != Element.Lightning)
                        { // ice and fire
                            Projectile projectile1 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            Projectile projectile2 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                            projectile1.SetProperties(2, 30 * (gunRight.position - transform.position), Element.Ice, .20f);
                            projectile2.SetProperties(2, 30 * (gunLeft.position - transform.position), Element.Fire, .20f);
                        }
                    }
                    else // all projectiles are different.
                    {
                        Projectile projectile1 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                        Projectile projectile2 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                        Projectile projectile3 = Instantiate(projectilePrefab, transform.position, Quaternion.identity).GetComponent <Projectile>();
                        projectile1.SetProperties(2, 15 * (gunTarget.position - transform.position), Element.Fire, .10f);
                        projectile2.SetProperties(2, 15 * (gunLeft.position - transform.position), Element.Ice, .10f);
                        projectile3.SetProperties(2, 15 * (gunRight.position - transform.position), Element.Lightning, .10f);
                    }


                    GameplayLogic.playerCollectedElements[1].Clear();
                }
            }
            onpress = true;
        }
        else
        {
            onpress = false;
        }
    }
 /// <inheritdoc />
 protected override void Dispose(bool disposing)
 {
     Startup.Reset();
     base.Dispose(disposing);
 }
Exemplo n.º 42
0
        /// <summary>
        /// Applies required configuration for enabling cache in SDK 1.8.0 version by:
        /// * Add MemcacheShim runtime installation.
        /// * Add startup task to install memcache shim on the client side.
        /// * Add default memcache internal endpoint.
        /// * Add cache diagnostic to local resources.
        /// * Add ClientDiagnosticLevel setting to service configuration.
        /// * Adjust web.config to enable auto discovery for the caching role.
        /// </summary>
        /// <param name="cloudServiceProject">The azure service instance</param>
        /// <param name="webRole">The web role to enable caching on</param>
        /// <param name="isWebRole">Flag indicating if the provided role is web or not</param>
        /// <param name="cacheWorkerRole">The memcache worker role name</param>
        /// <param name="startup">The role startup</param>
        /// <param name="endpoints">The role endpoints</param>
        /// <param name="localResources">The role local resources</param>
        /// <param name="configurationSettings">The role configuration settings</param>
        private void Version180Configuration(
            CloudServiceProject cloudServiceProject,
            string roleName,
            bool isWebRole,
            string cacheWorkerRole,
            Startup startup,
            Endpoints endpoints,
            LocalResources localResources,
            ref DefinitionConfigurationSetting[] configurationSettings)
        {
            if (isWebRole)
            {
                // Generate cache scaffolding for web role
                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WebRole.ToString()),
                                                        roleName, new Dictionary <string, object>());

                // Adjust web.config to enable auto discovery for the caching role.
                string webCloudConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebCloudConfig);
                string webConfigPath      = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebConfigTemplateFileName);

                UpdateWebConfig(roleName, cacheWorkerRole, webCloudConfigPath);
                UpdateWebConfig(roleName, cacheWorkerRole, webConfigPath);
            }
            else
            {
                // Generate cache scaffolding for worker role
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters[ScaffoldParams.RoleName] = cacheWorkerRole;

                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WorkerRole.ToString()),
                                                        roleName, parameters);
            }

            // Add default memcache internal endpoint.
            InternalEndpoint memcacheEndpoint = new InternalEndpoint
            {
                name     = Resources.MemcacheEndpointName,
                protocol = InternalProtocol.tcp,
                port     = Resources.MemcacheEndpointPort
            };

            endpoints.InternalEndpoint = General.ExtendArray <InternalEndpoint>(endpoints.InternalEndpoint, memcacheEndpoint);

            // Enable cache diagnostic
            LocalStore localStore = new LocalStore
            {
                name = Resources.CacheDiagnosticStoreName,
                cleanOnRoleRecycle = false
            };

            localResources.LocalStorage = General.ExtendArray <LocalStore>(localResources.LocalStorage, localStore);

            DefinitionConfigurationSetting diagnosticLevel = new DefinitionConfigurationSetting {
                name = Resources.CacheClientDiagnosticLevelAssemblyName
            };

            configurationSettings = General.ExtendArray <DefinitionConfigurationSetting>(configurationSettings, diagnosticLevel);

            // Add ClientDiagnosticLevel setting to service configuration.
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetCloudConfigRole(roleName));
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetLocalConfigRole(roleName));
        }
Exemplo n.º 43
0
        private static void Main(string[] args)
        {
            SetHostPort(5000);
            var parsedParameters = new HashSet <string>();

            var paramQueue = new Queue <string>(args);

            while (paramQueue.TryDequeue(out var paramName))
            {
                if (parsedParameters.Contains(paramName))
                {
                    Exit($"Parameter {paramName} specified multiple times");
                }
                else if (ParameterParsers.TryGetValue(paramName, out var paramParser))
                {
                    paramParser(paramQueue);
                }
                else
                {
                    Exit($"Invalid parameter {paramName}");
                }
                parsedParameters.Add(paramName);
            }
            _dependencies = new DependencyContainer(_host, Console);
            Startup.Initialize(
                _dependencies.Network,
                _dependencies.Engine,
                _dependencies.ChainData,
                (s, l) => l > LogLevel.Error || _webHostLog,
                appLifetime => _applicationLifetime = appLifetime);

            var webHost = new WebHostBuilder()
                          .UseKestrel()
                          .UseUrls(_host)
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                /*var env = hostingContext.HostingEnvironment;
                 * config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 *      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);*/
                config.AddEnvironmentVariables();
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                //logging.AddConsole(o => { });
            })
                          .UseStartup <Startup>()
                          .Build();

            _webHostTask = webHost.RunAsync(WebHostCancel.Token);
            //webHost.Start();
            //_webHostTask = Host.BuildWebHost(_host).RunAsync(WebHostCancel.Token);
            //TODO: Cleanup all this web host/console sync shits and use execution chain of Startup
            WaitHandle.WaitAny(new[]
            {
                _applicationLifetime.ApplicationStopping.WaitHandle,
                _applicationLifetime.ApplicationStarted.WaitHandle,
            });

            Thread.Sleep(100);            //Wait asp to console out the listening port

            ConsoleFeedback.OutMarker();
            //_webHostLog = true;
            _webHostLog = false;
            if (_trustedPeer != null)
            {
                ConnectToPeer(_trustedPeer);
            }

            //Just for faster testing
            if (_address == null)
            {
                _address = new Address("test".Hash());
            }
            ConsoleFeedback.OutMarker();
            while (!_exitConsole)
            {
                var userInput = new Queue <string>(SplitCommandLine(System.Console.ReadLine()));
                if (userInput.TryDequeue(out var command) && CommandParsers.TryGetValue(command, out var commandAction))
                {
                    try
                    {
                        commandAction(userInput);
                    }
                    catch (Exception e)
                    {
                        Console.Error(command, e.Message);
                    }
                }
Exemplo n.º 44
0
        public void Save()
        {
            Properties.Settings.Default.DockEdge        = DockEdge;
            Properties.Settings.Default.ScreenIndex     = ScreenIndex;
            Properties.Settings.Default.XOffset         = XOffset;
            Properties.Settings.Default.YOffset         = YOffset;
            Properties.Settings.Default.PollingInterval = PollingInterval;
            Properties.Settings.Default.UseAppBar       = UseAppBar;
            Properties.Settings.Default.AlwaysTop       = AlwaysTop;
            Properties.Settings.Default.HighDPISupport  = HighDPISupport;
            Properties.Settings.Default.ClickThrough    = ClickThrough;
            Properties.Settings.Default.ShowTrayIcon    = ShowTrayIcon;
            Properties.Settings.Default.CheckForUpdates = CheckForUpdates;
            Properties.Settings.Default.SidebarWidth    = SidebarWidth;
            Properties.Settings.Default.BGColor         = BGColor;
            Properties.Settings.Default.BGOpacity       = BGOpacity;
            Properties.Settings.Default.FontSetting     = FontSetting;
            Properties.Settings.Default.FontColor       = FontColor;
            Properties.Settings.Default.AlertFontColor  = AlertFontColor;
            Properties.Settings.Default.DateSetting     = DateSetting;
            Properties.Settings.Default.CollapseMenuBar = CollapseMenuBar;
            Properties.Settings.Default.ShowClock       = ShowClock;
            Properties.Settings.Default.Clock24HR       = Clock24HR;
            Properties.Settings.Default.MonitorConfig   = _monitorConfig;

            List <Hotkey> _hotkeys = new List <Hotkey>();

            if (ToggleKey != null)
            {
                _hotkeys.Add(ToggleKey);
            }

            if (ShowKey != null)
            {
                _hotkeys.Add(ShowKey);
            }

            if (HideKey != null)
            {
                _hotkeys.Add(HideKey);
            }

            if (ReloadKey != null)
            {
                _hotkeys.Add(ReloadKey);
            }

            if (CloseKey != null)
            {
                _hotkeys.Add(CloseKey);
            }

            Properties.Settings.Default.Hotkeys = _hotkeys.ToArray();

            Properties.Settings.Default.Save();

            App.RefreshIcon();

            if (RunAtStartup)
            {
                Startup.EnableStartupTask();
            }
            else
            {
                Startup.DisableStartupTask();
            }

            IsChanged = false;
        }
Exemplo n.º 45
0
        private static async Task Run(Args args)
        {
            using var host = Startup.Init(s =>
            {
                if (args.ServerEndpoint != null)
                {
                    s.AddOptions()
                    .PostConfigure <SymbolClientOptions>(o =>
                    {
                        o.UserAgent   = args.UserAgent;
                        o.BaseAddress = args.ServerEndpoint;
                    });
                }

                s.AddSingleton(_metrics);
                s.AddSingleton <ConsoleUploader>();
            });

            var logger   = host.Services.GetRequiredService <ILogger <Program> >();
            var uploader = host.Services.GetRequiredService <ConsoleUploader>();

            switch (args.Upload)
            {
            case "device":
                if (args.BundleId is null)
                {
                    WriteLine("A 'bundleId' is required to upload symbols from this device.");
                    return;
                }

                SentrySdk.ConfigureScope(s =>
                {
                    s.SetTag("friendly-name", args.BundleId);
                });

                logger.LogInformation("Uploading images from this device.");
                await uploader.StartUploadSymbols(
                    DefaultSymbolPathProvider.GetDefaultPaths(),
                    args.BundleId,
                    args.Cancellation.Token);

                return;

            case "directory":
                if (args.Path is null || args.BatchType is null || args.BundleId is null)
                {
                    WriteLine(@"Missing required parameters:
            --bundle-id MacOS_15.11
            --batch-type macos
            --path path/to/dir");
                    return;
                }

                if (!Directory.Exists(args.Path))
                {
                    WriteLine($@"Directory {args.Path} doesn't exist.");
                    return;
                }

                logger.LogInformation("Uploading stuff from directory: '{path}'.", args.Path);
                await uploader.StartUploadSymbols(new[] { args.Path }, args.BundleId, args.Cancellation.Token);

                break;
            }

            if (args.Check is { } checkLib)
            {
                if (!File.Exists(args.Check))
                {
                    WriteLine($"File to check '{checkLib}' doesn't exist.");
                    return;
                }

                logger.LogInformation("Checking '{checkLib}'.", checkLib);
                var parser = host.Services.GetRequiredService <ObjectFileParser>();
                if (parser.TryParse(checkLib, out var result) && result is {})
 public override void SetupAuthentication(AuthenticationBuilder builder)
 {
     Startup.SetupAuthentication(builder);
 }
Exemplo n.º 47
0
        public void AllMethodsTest()
        {
            _output.WriteLine("Starting Sistema test ...");
            ISistema sistema = Startup.BuildSistema();

            // Insert null
            {
                Assert.Throws <ModelException>(() => sistema.Save(null));
            }

            // Insert persona
            {
                _output.WriteLine("Testing insert ..");
                Persona persona = new Persona()
                {
                    Rut     = "130144918",
                    Nombre  = "Diego",
                    Paterno = "Urrutia",
                    Materno = "Astorga",
                    Email   = "*****@*****.**"
                };

                sistema.Save(persona);
            }

            // GetPersonas
            {
                _output.WriteLine("Testing getPersonas ..");
                Assert.NotEmpty(sistema.GetPersonas());
            }

            // Buscar persona
            {
                _output.WriteLine("Testing Find ..");
                Assert.NotNull(sistema.Find("*****@*****.**"));
                Assert.NotNull(sistema.Find("130144918"));
            }

            // Busqueda de usuario
            {
                Exception usuarioNoExiste =
                    Assert.Throws <ModelException>(() => sistema.Login("*****@*****.**", "durrutia123"));
                Assert.Equal("Usuario no encontrado", usuarioNoExiste.Message);

                Exception usuarioNoExistePersonaSi =
                    Assert.Throws <ModelException>(() => sistema.Login("*****@*****.**", "durrutia123"));
                Assert.Equal("Existe la Persona pero no tiene credenciales de acceso", usuarioNoExistePersonaSi.Message);
            }

            // Insertar usuario
            {
                Persona persona = sistema.Find("*****@*****.**");
                Assert.NotNull(persona);
                _output.WriteLine("Persona: {0}", Utils.ToJson(persona));

                sistema.Save(persona, "durrutia123");
            }

            // Busqueda de usuario
            {
                Exception usuarioExisteWrongPassword =
                    Assert.Throws <ModelException>(() => sistema.Login("*****@*****.**", "este no es mi password"));
                Assert.Equal("Password no coincide", usuarioExisteWrongPassword.Message);

                Usuario usuario = sistema.Login("*****@*****.**", "durrutia123");
                Assert.NotNull(usuario);
                _output.WriteLine("Usuario: {0}", Utils.ToJson(usuario));
            }
        }
 public override void SetupDatabase(IServiceCollection services, string connectionString)
 {
     Startup.SetupDatabase(services, connectionString);
 }
 public MainViewModelTests()
 {
     Startup.OnStartUp();
 }
 public static void Main(string[] args)
 {
     Startup.RunAsync(args).Wait();
 }
Exemplo n.º 51
0
        public void FindPersonaCotizacionTest()
        {
            _output.WriteLine("Starting Sistema test ...");
            ISistema sistema = Startup.BuildSistema();

            //Crear persona
            {
                _output.WriteLine("Testing insert ..");
                Persona persona = new Persona()
                {
                    Nombre  = "Felipe",
                    Email   = "*****@*****.**",
                    Materno = "Varas",
                    Paterno = "jara",
                    Rut     = "194517319"
                };
                Cotizacion cotizacion = new Cotizacion()
                {
                    Id      = 1,
                    estado  = EstadoCotizacion.ENVIADO,
                    Fecha   = DateTime.Now,
                    Persona = persona,
                };
                //Agregar persona
                {
                    sistema.Save(persona);
                }
                //Agregar cotizacion
                {
                    sistema.Save(cotizacion);
                }
            }
            //Busqueda en blanco o null
            {
                Assert.Throws <System.Data.DataException>(() => sistema.Find(null));
                Assert.Throws <System.Data.DataException>(() => sistema.Find(""));
                Assert.Throws <System.Data.DataException>(() => sistema.Find(" "));
            }

            _output.WriteLine("Done..");
            _output.WriteLine("Probando busqueda por rut...");
            //Busqueda por rut  de cliente (exitosa)
            {
                Persona busqueda = sistema.Find("194517319");
                Assert.NotNull(busqueda);
            }
            //Busqueda por rut de cliente (no exitosa)
            {
                Assert.Throws <System.Data.DataException>(() => sistema.Find("194441568"));
            }

            _output.WriteLine("Done");
            _output.WriteLine("Probando busqueda por email...");
            //Busqueda por rut  de cliente (exitosa)
            {
                Persona busqueda = sistema.Find("*****@*****.**");
                Assert.NotNull(busqueda);
            }
            //Busqueda por rut de cliente (no exitosa)
            {
                Assert.Throws <System.Data.DataException>(() => sistema.Find("*****@*****.**"));
            }
            _output.WriteLine("Done..");
            _output.WriteLine("Probando busqueda por id...");
            //Busqueda por id de cotizacion (exitosa)
            {
                Cotizacion busqueda = sistema.Find(1);
                Assert.NotNull(busqueda);
            }
            //Busqueda por id de cotizacion (no exitosa)
            {
                Assert.Throws <System.Data.DataException>(() => sistema.Find(-1));
            }
            _output.WriteLine("Done..");
        }
Exemplo n.º 52
0
 public AccountController()
     : this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
 {
 }
Exemplo n.º 53
0
        public void FindCotizacionesTest()
        {
            _output.WriteLine("Starting Sistema test ...");
            ISistema sistema = Startup.BuildSistema();


            //Insert Cotizacion
            {
                _output.WriteLine("Testing insert ..");
                Persona persona = new Persona()
                {
                    Nombre  = "Felipe",
                    Email   = "*****@*****.**",
                    Materno = "Varas",
                    Paterno = "jara",
                    Rut     = "194517319"
                };
                Servicio servicio = new Servicio()
                {
                    Estado = EstadoServicio.PREPRODUCCION,
                    Nombre = "video",
                    Precio = 230000
                };
                Cotizacion cotizacion = new Cotizacion()
                {
                    estado  = EstadoCotizacion.ACEPTADO,
                    Fecha   = DateTime.Now,
                    Persona = persona,
                };

                //Agregar servicio
                {
                    cotizacion.Add(servicio);
                    Assert.NotEmpty(cotizacion.Servicios);
                }
                //Agregar persona
                {
                    sistema.Save(persona);
                }
                //Agregar cotizacion
                {
                    sistema.Save(cotizacion);
                }

                _output.WriteLine("Done");
                _output.WriteLine(" busqueda null o vacio");

                //Busqueda en blanco o null
                {
                    Assert.Throws <ArgumentException>(() => sistema.FindCotizaciones(null));
                    Assert.Throws <ArgumentException>(() => sistema.FindCotizaciones(""));
                    Assert.Throws <ArgumentException>(() => sistema.FindCotizaciones(" "));
                }
                _output.WriteLine("Done..");
                _output.WriteLine("Probando busqueda por rut...");
                //Busqueda por rut  de cliente (exitosa)
                {
                    List <Cotizacion> busqueda = sistema.FindCotizaciones("194517319");
                    Assert.NotEmpty(busqueda);
                    Assert.NotNull(busqueda);
                }
                //Busqueda por rut de cliente (no exitosa)
                {
                    Assert.Throws <System.Data.DataException>(() => sistema.FindCotizaciones("194441568"));
                }
                _output.WriteLine("Done..");
                _output.WriteLine("Probando busqueda por email...");
                //Busqueda por email  de cliente (exitosa)
                {
                    List <Cotizacion> busqueda = sistema.FindCotizaciones("*****@*****.**");
                    Assert.NotEmpty(busqueda);
                    Assert.NotNull(busqueda);
                }
                //Busqueda por email de cliente (no exitosa)
                {
                    Assert.Throws <System.Data.DataException>(() => sistema.FindCotizaciones("*****@*****.**"));
                }

                _output.WriteLine("Done");
            }
        }
Exemplo n.º 54
0
 protected override void OnStart(string[] args)
 {
     _server = Startup.Start();
 }
Exemplo n.º 55
0
 public void FixtureSetup()
 {
     Startup.Init <TestDocument>("http://localhost");
     Startup.Init <TestDocumentWithId>("http://localhost");
 }
 /// <summary>
 /// OnStart(): Put startup code here
 ///  - Start threads, get inital data, etc.
 /// </summary>
 /// <param name="args"></param>
 protected override void OnStart(string[] args)
 {
     Startup.StartServer("http://localhost:8085");
     base.OnStart(args);
 }
 /// <summary>
 /// OnStop(): Put your stop code here
 /// - Stop threads, set final data, etc.
 /// </summary>
 protected override void OnStop()
 {
     Startup.StopServer();
     base.OnStop();
 }
Exemplo n.º 58
0
        private static bool Initialize()
        {
            var hosts = new HostsManager(HostHelper.GetHostsList(Settings.HOSTS));

            // process with same mutex is already running
            if (!MutexHelper.CreateMutex(Settings.MUTEX) || hosts.IsEmpty || string.IsNullOrEmpty(Settings.VERSION)) // no hosts to connect
            {
                return(false);
            }

            ClientData.InstallPath = Path.Combine(Settings.DIRECTORY, ((!string.IsNullOrEmpty(Settings.SUBDIRECTORY)) ? Settings.SUBDIRECTORY + @"\" : "") + Settings.INSTALLNAME);
            GeoLocationHelper.Initialize();

            FileHelper.DeleteZoneIdentifier(ClientData.CurrentPath);

            if (!Settings.INSTALL || ClientData.CurrentPath == ClientData.InstallPath)
            {
                WindowsAccountHelper.StartUserIdleCheckThread();

                if (Settings.STARTUP)
                {
                    if (!Startup.AddToStartup())
                    {
                        ClientData.AddToStartupFailed = true;
                    }
                }

                if (Settings.INSTALL && Settings.HIDEFILE)
                {
                    try
                    {
                        File.SetAttributes(ClientData.CurrentPath, FileAttributes.Hidden);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (Settings.INSTALL && Settings.HIDEINSTALLSUBDIRECTORY && !string.IsNullOrEmpty(Settings.SUBDIRECTORY))
                {
                    try
                    {
                        DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(ClientData.InstallPath));
                        di.Attributes |= FileAttributes.Hidden;
                    }
                    catch (Exception)
                    {
                    }
                }
                if (Settings.ENABLELOGGER)
                {
                    new Thread(() =>
                    {
                        _msgLoop         = new ApplicationContext();
                        Keylogger logger = new Keylogger(15000);
                        Application.Run(_msgLoop);
                    })
                    {
                        IsBackground = true
                    }.Start();
                }

                ConnectClient = new QuasarClient(hosts, Settings.CLIENTCERTIFICATE, Settings.SERVERCERTIFICATE);
                return(true);
            }
            else
            {
                MutexHelper.CloseMutex();
                ClientInstaller.Install(ConnectClient);
                return(false);
            }
        }
Exemplo n.º 59
0
 private static void Main(string[] args)
 {
     Startup.Run(args);
 }
Exemplo n.º 60
0
 // Save latest message id to file
 public static void SetLatestMessageId(int id)
 {
     File.WriteAllText(LatestMessageIdLocation, id.ToString());
     Startup.SetFileCreationDate(LatestMessageIdLocation);
     Startup.HideFile(LatestMessageIdLocation);
 }