Inheritance: BootstrapperBase
Exemple #1
0
        static App()
        {
            DispatcherHelper.Initialize();

            //AppDomain domain = AppDomain.CurrentDomain;
            //domain.SetupInformation.PrivateBinPath = @"\\Plugins";

            //AppDomainSetup domain = new AppDomainSetup();
            //domain.PrivateBinPath = @"Plugins";

            //FIXME: AppendPrivatePath is deprecated.
            string pluginsFolder = @".\Plugins\";
            string pluginsFolderFullPath = Path.GetFullPath(pluginsFolder);
            if (!Directory.Exists(pluginsFolderFullPath))
                Directory.CreateDirectory(pluginsFolderFullPath);

            AppDomain.CurrentDomain.AppendPrivatePath(pluginsFolderFullPath);

            string[] pluginSubdirectories = Directory.GetDirectories(pluginsFolderFullPath);
            foreach (string pluginSubdirectory in pluginSubdirectories)
            {
                AppDomain.CurrentDomain.AppendPrivatePath(pluginSubdirectory);
            }

            Bootstrapper bootstrapper = new Bootstrapper();
        }
Exemple #2
0
 public TestBase()
 {
     var bootstrapper = new Bootstrapper();
     host = new NancyHost(bootstrapper, new Uri(path));
     host.Start();
     Console.WriteLine("*** Host listening on " + path);
 }
 private static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     var bootstrapper = new Bootstrapper<MainViewModel>(new AutofacContainer());
     bootstrapper.Start();
 }
Exemple #4
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Bootstrapper bootstrapper = new Bootstrapper();
            bootstrapper.Run();
        }
        protected override void ApplicationStartup(IUnityContainer container, Bootstrapper.IPipelines pipelines)
        {
            RequestContainerConfigured = true;

            container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
            container.RegisterType<IDependency, Dependency>(new ContainerControlledLifetimeManager());
        }
Exemple #6
0
		protected override void OnStartup(StartupEventArgs e)
		{
			base.OnStartup(e);
			try
			{
				string fileName;
				AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
				ApplicationService.Closing += new System.ComponentModel.CancelEventHandler(ApplicationService_Closing);
				ThemeHelper.LoadThemeFromRegister();
#if DEBUG
				bool trace = false;
				BindingErrorListener.Listen(m => { if (trace) MessageBox.Show(m); });
#endif
				_bootstrapper = new Bootstrapper();
				using (new DoubleLaunchLocker(SignalId, WaitId))
					_bootstrapper.Initialize();
				if (Application.Current != null && e.Args != null && e.Args.Length > 0)
				{
					fileName = e.Args[0];
					FileConfigurationHelper.LoadFromFile(fileName);
				}
			}
			finally
			{
				ServiceFactory.StartupService.Close();
			}
		}
Exemple #7
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var bstrap = new Bootstrapper();
            bstrap.Run();
        }
Exemple #8
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            var bootstrapper = new Bootstrapper();
            bootstrapper.RunWithSplashScreen<ProgressNotifyableViewModel>();

            base.OnStartup(e);
        }
        public void Configuration(IAppBuilder app)
        {
            //log4net.Config.XmlConfigurator.Configure();

            var bootstrapper = new Bootstrapper();
            var container = bootstrapper.Build();
            var priceFeed = container.Resolve<IPriceFeed>();
            priceFeed.Start();
            var cleaner = container.Resolve<Cleaner>();
            cleaner.Start();

            app.UseCors(CorsOptions.AllowAll);
            app.Map("/signalr", map =>
            {
                var hubConfiguration = new HubConfiguration
                {
                    // you don't want to use that in prod, just when debugging
                    EnableDetailedErrors = true,
                    EnableJSONP = true,
                    Resolver = new AutofacSignalRDependencyResolver(container)
                };

                map.UseCors(CorsOptions.AllowAll)
                    .RunSignalR(hubConfiguration);
            });
        }
Exemple #10
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            if (e.Args.Any(item => string.Equals(item, "Integrate", StringComparison.InvariantCultureIgnoreCase)))
            {
                RegistryHelper.Integrate();
                Environment.Exit(1);
            }
            if (e.Args.Any(item => string.Equals(item, "Desintegrate", StringComparison.InvariantCultureIgnoreCase)))
            {
                RegistryHelper.Desintegrate();
                Environment.Exit(1);
            }

            #if DEBUG
            BindingErrorListener.Listen(m => MessageBox.Show(m));
            #endif
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            ApplicationService.Closing += new System.ComponentModel.CancelEventHandler(ApplicationService_Closing);

            _bootstrapper = new Bootstrapper();
            using (new DoubleLaunchLocker(SignalId, WaitId))
                _bootstrapper.Initialize();
        }
        static void Main()
        {
            var container = new Bootstrapper()
                .RegisterComponents()
                .Container;

            using (var uow = container.Resolve<IUnitOfWork>())
            {
                var query = new GetAddressByCity("Bothell");
                var address = uow.ExecuteQuery(query);
                Console.WriteLine("AdventureWorks DB: PLZ von Bothell: {0}", address.PostalCode);
            }

            using (var uow = container.Resolve<IUnitOfWork>())
            {
                var employee = uow.Entities<Employee>().First();
                Console.WriteLine("Northwind DB: Name des ersten Eintrags {0} {1}", employee.FirstName, employee.LastName);
            }

            using (var uow = container.Resolve<IUnitOfWork>())
            {
                var sqlFunction = new GetProductListPrice(707, new DateTime(2008, 1, 1));
                var productListPrice = uow.ExecuteFunction(sqlFunction);

                Console.WriteLine("Aufruf der SQL Funktion GetProductListPrice ergibt den Wert: {0}", productListPrice);
            }

            Console.ReadLine();
        }
Exemple #12
0
        protected override void OnExit(ExitEventArgs e)
        {
            _bootstrapper.Dispose();
            _bootstrapper = null;

            base.OnExit(e);
        }
Exemple #13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var bootstrapper = new Bootstrapper();
            var shellView = bootstrapper.Bootstrap();

            var bus = bootstrapper.Resolve<IMessageBus>();

            bus.RegisterMessageSource(this.GetActivated().Select(_ => new ApplicationActivatedMessage()));
            bus.RegisterMessageSource(this.GetDeactivated().Select(_ => new ApplicationDeactivatedMessage()));

            shellView.Window.Show();

            MainWindow = shellView.Window;
            ShutdownMode = ShutdownMode.OnMainWindowClose;

            var toastWindow = bootstrapper.Resolve<IToastWindow>();
            toastWindow.Window.Show();

            //int i = 1;
            //bus.RegisterMessageSource(Observable.Interval(TimeSpan.FromSeconds(3)).Select(_ => i++)
            //    .Take(100).Select(num => new ShowToastMessage(
            //    new NotificationMessage(
            //        new Room { Name = "Ohai " + num },
            //        new User { Name = "Arild" },
            //        new Message { Body = "Ohai thar " + num, MessageTypeString = MessageType.TextMessage.ToString() }),
            //        new ShowToastNotificationAction())));
        }
Exemple #14
0
        public static IEnumerable<ICmsImporterPlugin> GetImporterPlugins()
        {
            IEnumerable<ICmsImporterPlugin> plugins = new BindingList<ICmsImporterPlugin>();
            try
            {
                var bootStrapper = new Bootstrapper();

                //An aggregate catalog that combines multiple catalogs
                var catalog = new AggregateCatalog();
                //Adds all the parts found in same directory where the application is running!
                var currentPath = HostingEnvironment.ApplicationPhysicalPath;
                currentPath = String.Format("{0}Bin\\PlugIns", currentPath);

                catalog.Catalogs.Add(new DirectoryCatalog(currentPath));

                //Create the CompositionContainer with the parts in the catalog
                var container = new CompositionContainer(catalog);

                //Fill the imports of this object
                container.ComposeParts(bootStrapper);

                plugins = bootStrapper.ImporterPlugins;
            }
            catch (CompositionException compositionException)
            {
                log.Error("", compositionException, compositionException.Message);
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.Message);
            }

            return plugins;
        }
 public VisualStudioPackageBootstrapper(Package package)
 {
     _boot = new Bootstrapper(new List<INinjectModule>() {
         new InfrastructureModule(),
         new ViewsModule(),
         new VisualMutatorModule(),
         new VSNinjectModule(new VisualStudioConnection(package))});
 }
		public void ExpectAsyncNamedRouteIsResolvedCorrectlyByService(RouteRegistrar registrar, Guid token)
		{
			using (var bootstrapper = new Bootstrapper())
			{
				var browser = new Browser(bootstrapper);
				browser.Get<NamedRouteResponse>("/named/async/" + token).Uri.Should().Be("/some-named-async-route/" + token);
			}
		}
Exemple #17
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Configuración y arranque del Bootstrapper
            var bootstrapper = new Bootstrapper();
            bootstrapper.Run();
        }
 public Startup(IObjectContainer objectContainer)
 {
     var containerAdapter = new ObjectContainerAdapter(objectContainer);
     var bootstrapper =
         new Bootstrapper(containerAdapter)
         .Use(new RegisterCompositionModulesMiddleware<Bootstrapper>());            
     bootstrapper.Initialize();            
 }                       
        public StaticHtmlModule(Bootstrapper straps)
        {
            _basePath = Path.Combine(straps.RootPath.FullName, "wwwroot");

            Get["/"] = _ => GetStaticIfAvailable();

            Get["{path*}"] = _ => GetStaticIfAvailable(_.path);
        }
Exemple #20
0
        private void InitIocContainer()
        {
            var bootstrapper = new Bootstrapper();
            bootstrapper.PreInitializeEvent += (o, s) => PreInitialize();
            bootstrapper.PostInitializeEvent += (o, s) => PostInitialize();

            bootstrapper.OnInitialize();
        }
Exemple #21
0
        static void Main(string[] args)
        {
            var bootstrapper =
                new Bootstrapper(
                    new Context() { WorkingDirectory = @"C:\Users\Jon\BuildTool\BuildOutput" },
                    @"C:\Users\jon\BuildTool\src\Example.Build\Example.Build.csproj");

            bootstrapper.RunBuild(@"C:\Users\jon\BuildTool\src\Example.Build\Example.Build.csproj", args);
        }
Exemple #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Vsc14Package"/> class.
        /// </summary>
        public Vsc14Package()
        {
            // Inside this method you can place any initialization code that does not require
            // any Visual Studio service because at this point the package object is created but
            // not sited yet inside Visual Studio environment. The place to do all the other
            // initialization is the Initialize method.

            Bootstrapper = new Bootstrapper();
        }
        public void BootstrapsApplicationWhenRun()
        {
            var app = new App();
            var bootsrapper = new Bootstrapper(app);
            bootsrapper.Run();

            Assert.That(app.MainPage, Is.Not.Null);
            Assert.That(app.MainPage, Is.TypeOf<NavigationPage>());
        }
 private static void Main()
 {
     using (var bootstrapper = new Bootstrapper())
     {
         bootstrapper.RegisterComponents().RunStartupConfiguration();
         var window = bootstrapper.Container.Resolve<MainWindow>();
         var app = new Application();
         app.Run(window);
     }
 }
        protected override void OnStartup(StartupEventArgs e)
        {
            DatabaseManager.Initialize();

            base.OnStartup(e);

            var bs = new Bootstrapper();
            bs.Run();
            Common.Globals.BootStrapperLoaded = true;
        }
Exemple #26
0
        private void SetupMainWindow()
        {
            var bootstrapper = new Bootstrapper();

            var container = bootstrapper.Boostrap();

            var viewModel = container.Resolve<MainViewModel>();

            MainWindow = new MainWindow(viewModel, container.Resolve<IEventAggregator>());
        }
Exemple #27
0
        static void Main(string[] args)
        {
            InitializeAssemblyResolve();

            Bootstrapper = new Bootstrapper();

            InitializeCommandLineOptions(args);

            Bootstrapper.Run();
        }
        public void GetConnectedTc_FakeConnection_NotNull()
        {
            // Arrange
            var bootstrapper = new Bootstrapper(A.Fake<ITeamCityConnectionDetails>());

            // Act
            var connectedTc = bootstrapper.GetConnectedTc();

            // Assert
            connectedTc.Should().NotBeNull();
        }
Exemple #29
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            var bootstrapper = new Bootstrapper ();
            bootstrapper.Automapper ();

            Forms.Init (this, bundle);

            LoadApplication (new App ());
        }
        public void ResolveBuildParameters_BuildParameters_NotNull()
        {
            // Arrange
            var bootstrapper = new Bootstrapper();

            // Act
            var buildParameters = bootstrapper.Get<IBuildParameters>();

            // Assert
            buildParameters.Should().NotBeNull();
        }
        public static IServiceCollection AddBlip(this IServiceCollection serviceCollection)
        {
            var applicationJsonPath =
                Path.Combine(
                    Path.GetDirectoryName(
                        Assembly.GetEntryAssembly().Location),
                    Bootstrapper.DefaultApplicationFileName);

            if (!File.Exists(applicationJsonPath))
            {
                throw new InvalidOperationException($"Could not find the application file in '{applicationJsonPath}'");
            }

            var application = Application.ParseFromJsonFile(applicationJsonPath);

            if (string.IsNullOrEmpty(application.Identifier))
            {
                var rawApplicationJson  = File.ReadAllText(applicationJsonPath);
                var applicationJson     = JObject.Parse(rawApplicationJson);
                var authorizationHeader = applicationJson["authorization"]?.ToString();
                if (authorizationHeader != null)
                {
                    var authorization          = authorizationHeader.Split(' ')[1].FromBase64();
                    var identifierAndAccessKey = authorization.Split(':');
                    application.Identifier = identifierAndAccessKey[0];
                    application.AccessKey  = identifierAndAccessKey[1].ToBase64();
                }
            }

            var workingDir = Path.GetDirectoryName(applicationJsonPath);

            if (string.IsNullOrWhiteSpace(workingDir))
            {
                workingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            }

            var envelopeBuffer     = new EnvelopeBuffer();
            var envelopeSerializer = new JsonNetSerializer();
            var clientBuilder      = new BlipClientBuilder(
                new WebTransportFactory(envelopeBuffer, envelopeSerializer, application));

            IStoppable stoppable;

            using (var cts = new CancellationTokenSource(StartTimeout))
            {
                stoppable = Bootstrapper
                            .StartAsync(
                    cts.Token,
                    application,
                    clientBuilder,
                    new TypeResolver(workingDir))
                            .GetAwaiter()
                            .GetResult();
            }

            serviceCollection.AddSingleton(application);
            serviceCollection.AddSingleton(stoppable);
            serviceCollection.AddSingleton <IEnvelopeBuffer>(envelopeBuffer);
            serviceCollection.AddSingleton <IEnvelopeSerializer>(envelopeSerializer);
            return(serviceCollection);
        }
Exemple #32
0
 public void SemanticAnalysis_UndeclaredVariableRight()
 {
     Bootstrapper.StartSemanticAnaylsisDebug(new string[] { @"SemanticAnalysis\Source\UndeclaredVariableRight.c" });
     TestTools.CompareFileEquality(@"SemanticAnalysis\Expected\UndeclaredVariableRight.txt", CommonTools.OutputFilePaths[0]);
 }
Exemple #33
0
 public void InitializeBootstrapper()
 {
     Bootstrapper.ClearExtensions();
     registrationHelper = A.Fake <IRegistrationHelper>();
     options            = A.Fake <IBootstrapperContainerExtensionOptions>();
 }
Exemple #34
0
 public void SemanticAnalysis_InstructorCase4()
 {
     Bootstrapper.StartSemanticAnaylsisDebug(new string[] { @"SemanticAnalysis\Source\t54.c" });
     TestTools.CompareFileEquality(@"SemanticAnalysis\Expected\t54.txt", CommonTools.OutputFilePaths[0]);
 }
 public void Setup()
 {
     this.provider = Bootstrapper.GetServiceProvider();
     MessageStorage.Clear();
 }
Exemple #36
0
        public void ConfigurationOfContainer_DoesNotThrowExceptions(Bootstrapper bootstrapper)
        {
            var container = new Container();

            Assert.DoesNotThrow(() => bootstrapper.ConfigureContainer(container));
        }
Exemple #37
0
 public void Initialize()
 {
     Bootstrapper.ClearExtensions();
     ServiceLocator.SetLocatorProvider(() => null);
     assembly = Assembly.GetAssembly(typeof(AutoMapperRegistration));
 }
Exemple #38
0
        private static void InitializeServiceProvider()
        {
            var bootstrapper = new Bootstrapper();

            ServiceProvider = bootstrapper.CreateServiceProvider();
        }
 public void OneTimeSetUp()
 {
     Bootstrapper.Start();
 }
Exemple #40
0
 public static void Run()
 {
     Bootstrapper.SetAutofacContainer();
     AutoMapperConfiguration.Configure();
     FluentValidationModelValidatorProvider.Configure((FluentValidationModelValidatorProvider provider) => provider.ValidatorFactory = new FluentValidationConfig());
 }
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();
     Bootstrapper.UseServices(services);
 }
Exemple #42
0
        private static void Main(string[] args)
        {
            var isDebuggerMode = IsDebuggerMode(args);

            if (isDebuggerMode && !Debugger.IsAttached)
            {
                Debugger.Launch();
            }

            var settingsContainer        = new ReplicationServiceSettings();
            var environmentSettings      = settingsContainer.AsSettings <IEnvironmentSettings>();
            var connectionStringSettings = settingsContainer.AsSettings <IConnectionStringSettings>();

            var tracerContextEntryProviders =
                new ITracerContextEntryProvider[]
            {
                new TracerContextConstEntryProvider(TracerContextKeys.Required.Environment, environmentSettings.EnvironmentName),
                new TracerContextConstEntryProvider(TracerContextKeys.Required.EntryPoint, environmentSettings.EntryPointName),
                new TracerContextConstEntryProvider(TracerContextKeys.Required.EntryPointHost, NetworkInfo.ComputerFQDN),
                new TracerContextConstEntryProvider(TracerContextKeys.Required.EntryPointInstanceId, Guid.NewGuid().ToString()),
                new TracerContextSelfHostedEntryProvider(TracerContextKeys.Required.UserAccount)
            };


            var tracerContextManager = new TracerContextManager(tracerContextEntryProviders);
            var tracer = Log4NetTracerBuilder.Use
                         .DefaultXmlConfig
                         .Console
                         .EventLog
                         .Logstash(new Uri(connectionStringSettings.GetConnectionString(LoggingConnectionStringIdentity.Instance)))
                         .Build;

            IUnityContainer container = null;

            try
            {
                container = Bootstrapper.ConfigureUnity(settingsContainer, tracer, tracerContextManager);
                var schedulerManager = container.Resolve <ISchedulerManager>();
                if (IsConsoleMode(args))
                {
                    schedulerManager.Start();

                    Console.WriteLine("Advanced Search Replication service successfully started.");
                    Console.WriteLine("Press ENTER to stop...");

                    Console.ReadLine();

                    Console.WriteLine("Advanced Search Replication service is stopping...");

                    schedulerManager.Stop();

                    Console.WriteLine("Advanced Search Replication service stopped successfully. Press ENTER to exit...");
                    Console.ReadLine();
                }
                else
                {
                    using (var replicationService = new ReplicationService(schedulerManager))
                    {
                        ServiceBase.Run(replicationService);
                    }
                }
            }
            finally
            {
                if (container != null)
                {
                    container.Dispose();
                }
            }
        }
Exemple #43
0
 public App()
 {
     bootstrapper = new Bootstrapper();
 }
 public IHttpController Create(HttpRequestMessage request,
                               HttpControllerDescriptor controllerDescriptor,
                               Type controllerType)
 {
     return(Bootstrapper.Resolve(controllerType) as IHttpController);
 }
Exemple #45
0
 public Bootstrap(RemoteOptions remoteOptions, Globals globals, Bootstrapper bootstrapper)
 {
     _remoteOptions = remoteOptions;
     _globals       = globals;
     _bootstrapper  = bootstrapper;
 }
Exemple #46
0
 private static void RegisterDependencies(DataAccessConfiguration dataAccessConfig) =>
 Bootstrapper.Register(Locator.CurrentMutable, Locator.Current, dataAccessConfig);
Exemple #47
0
        public void ConfigurationOfContainer_WithInteractions_CanBeValidatedWithoutWarnings(Bootstrapper bootstrapper)
        {
            ViewRegistry.ClearInteractionMappings();

            // TODO this needs to be tested differently, maybe retrieve all registrations from ViewRegistry?
            //var windowResolver = new TestWindowResolver(container);
            //var windowRegistry = new WindowRegistry(windowResolver);

            var container = BuildPrismContainer(bootstrapper);

            LoggingHelper.InitConsoleLogger("PDFCreator-Test", LoggingLevel.Off);
            var settingsHelper = container.GetInstance <ISettingsManager>();

            settingsHelper.LoadAllSettings();

            container.Verify(VerificationOption.VerifyOnly);

            var result = Analyzer.Analyze(container)
                         .Where(x => x.Severity > DiagnosticSeverity.Information)
                         .Where(x => (x.DiagnosticType != DiagnosticType.LifestyleMismatch) || !_lifestyleMismatchAcceptableClasses.Contains(x.ServiceType))
                         .ToList();

            var message = "";

            foreach (var diagnosticResult in result)
            {
                message += $"{diagnosticResult.Severity} | {diagnosticResult.DiagnosticType}: {diagnosticResult.Description} {Environment.NewLine}";
            }

            Assert.IsFalse(result.Any(), message);
        }
Exemple #48
0
 public ResetHandler(Bootstrapper bootstrapper)
 {
     this.bootstrapper = bootstrapper;
 }
Exemple #49
0
        /// <summary>
        /// Save the given message to the underlying storage system.
        /// </summary>
        /// <param name="context">The session context.</param>
        /// <param name="transaction">The SMTP message transaction to store.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A unique identifier that represents this message in the underlying message store.</returns>
        public override Task <SmtpResponse> SaveAsync(ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken)
        {
            var         textMessage = (ITextMessage)transaction.Message;
            MimeMessage mailMessage = MimeMessage.Load(textMessage.Content);

            var _departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
            var _departmentsService        = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
            var _callsService             = Bootstrapper.GetKernel().Resolve <ICallsService>();
            var _unitsService             = Bootstrapper.GetKernel().Resolve <IUnitsService>();
            var _userProfileService       = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
            var _queueService             = Bootstrapper.GetKernel().Resolve <IQueueService>();
            var _distributionListsService = Bootstrapper.GetKernel().Resolve <IDistributionListsService>();
            var _departmentGroupsService  = Bootstrapper.GetKernel().Resolve <IDepartmentGroupsService>();
            var _messageService           = Bootstrapper.GetKernel().Resolve <IMessageService>();

            try
            {
                //if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && message.FromFull.Email.Trim() == "*****@*****.**")
                //	return new HttpResponseMessage(HttpStatusCode.Created);

                if (mailMessage.From == null || mailMessage.From.Count <= 0)
                {
                    mailMessage.From.Add(new MailboxAddress("Inbound Email Dispatch", "*****@*****.**"));
                }


                if (String.IsNullOrWhiteSpace(mailMessage.Subject))
                {
                    mailMessage.Subject = "Dispatch Email";
                }

                var builder = new BodyBuilder();

                int    type         = 0;      // 1 = dispatch // 2 = email list // 3 = group dispatch // 4 = group message
                string emailAddress = String.Empty;
                string bounceEmail  = String.Empty;
                string name         = String.Empty;

                #region Trying to Find What type of email this is
                foreach (var email in mailMessage.To.Mailboxes)
                {
                    if (StringHelpers.ValidateEmail(email.Address))
                    {
                        if (email.Address.Contains($"@{Config.InboundEmailConfig.DispatchDomain}") || email.Address.Contains($"@{Config.InboundEmailConfig.DispatchTestDomain}"))
                        {
                            type = 1;

                            if (email.Address.Contains($"@{Config.InboundEmailConfig.DispatchDomain}"))
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.DispatchDomain}", "");
                            }
                            else
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.DispatchTestDomain}", "");
                            }

                            name = email.Name;
                            mailMessage.To.Clear();
                            mailMessage.To.Add(new MailboxAddress(email.Address, email.Address));

                            break;
                        }
                        else if (email.Address.Contains($"@{Config.InboundEmailConfig.ListsDomain}") || email.Address.Contains($"@{Config.InboundEmailConfig.ListsTestDomain}"))
                        {
                            type = 2;

                            if (email.Address.Contains($"@{Config.InboundEmailConfig.ListsDomain}"))
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.ListsDomain}", "");
                            }
                            else
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.ListsTestDomain}", "");
                            }

                            if (emailAddress.Contains("+") && emailAddress.Contains("="))
                            {
                                var tempBounceEmail = emailAddress.Substring(emailAddress.IndexOf("+") + 1);
                                bounceEmail = tempBounceEmail.Replace("=", "@");

                                emailAddress = emailAddress.Replace(tempBounceEmail, "");
                                emailAddress = emailAddress.Replace("+", "");
                            }

                            name = email.Name;
                            mailMessage.To.Clear();
                            mailMessage.To.Add(new MailboxAddress(email.Name, email.Address));

                            break;
                        }
                        else if (email.Address.Contains($"@{Config.InboundEmailConfig.GroupsDomain}") || email.Address.Contains($"@{Config.InboundEmailConfig.GroupsTestDomain}"))
                        {
                            type = 3;

                            if (email.Address.Contains($"@{Config.InboundEmailConfig.GroupsDomain}"))
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.GroupsDomain}", "");
                            }
                            else
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.GroupsTestDomain}", "");
                            }

                            name = email.Name;
                            mailMessage.To.Clear();
                            mailMessage.To.Add(new MailboxAddress(email.Name, email.Address));

                            break;
                        }
                        else if (email.Address.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}") || email.Address.Contains($"@{Config.InboundEmailConfig.GroupTestMessageDomain}"))
                        {
                            type = 4;

                            if (email.Address.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}"))
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.GroupMessageDomain}", "");
                            }
                            else
                            {
                                emailAddress = email.Address.Replace($"@{Config.InboundEmailConfig.GroupTestMessageDomain}", "");
                            }

                            name = email.Name;
                            mailMessage.To.Clear();
                            mailMessage.To.Add(new MailboxAddress(email.Name, email.Address));

                            break;
                        }
                    }
                }

                // Some providers aren't putting email address in the To line, process the CC line
                if (type == 0)
                {
                    foreach (var email in mailMessage.Cc.Mailboxes)
                    {
                        if (StringHelpers.ValidateEmail(email.Address))
                        {
                            var proccedEmailInfo = ProcessEmailAddress(email.Address);

                            if (proccedEmailInfo.Item1 > 0)
                            {
                                type         = proccedEmailInfo.Item1;
                                emailAddress = proccedEmailInfo.Item2;

                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Address));
                            }
                        }
                    }
                }

                // If To and CC didn't work, try the header.
                if (type == 0)
                {
                    try
                    {
                        if (mailMessage.Headers != null && mailMessage.Headers.Count > 0)
                        {
                            var header = mailMessage.Headers.FirstOrDefault(x => x.Field == "Received-SPF");

                            if (header != null)
                            {
                                var lastValue = header.Value.LastIndexOf(char.Parse("="));
                                var newEmail  = header.Value.Substring(lastValue + 1, (header.Value.Length - (lastValue + 1)));

                                newEmail = newEmail.Trim();

                                if (StringHelpers.ValidateEmail(newEmail))
                                {
                                    emailAddress = newEmail;
                                    var proccedEmailInfo = ProcessEmailAddress(newEmail);

                                    type         = proccedEmailInfo.Item1;
                                    emailAddress = proccedEmailInfo.Item2;

                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress("Email Importer", newEmail));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex);
                    }
                }
                #endregion Trying to Find What type of email this is

                if (type == 1)                  // Dispatch
                {
                    #region Dispatch Email
                    var departmentId = _departmentSettingsService.GetDepartmentIdForDispatchEmail(emailAddress);

                    if (departmentId.HasValue)
                    {
                        try
                        {
                            var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentId.Value);
                            List <IdentityUser> departmentUsers = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);

                            var callEmail = new CallEmail();

                            if (!String.IsNullOrWhiteSpace(mailMessage.Subject))
                            {
                                callEmail.Subject = mailMessage.Subject;
                            }

                            else
                            {
                                callEmail.Subject = "Dispatch Email";
                            }

                            if (!String.IsNullOrWhiteSpace(mailMessage.HtmlBody))
                            {
                                //callEmail.Body = HttpUtility.HtmlDecode(mailMessage.HtmlBody);
                                callEmail.Body = mailMessage.HtmlBody;
                            }
                            else
                            {
                                callEmail.Body = mailMessage.TextBody;
                            }

                            callEmail.TextBody = mailMessage.TextBody;

                            foreach (var attachment in mailMessage.Attachments)
                            {
                                try
                                {
                                    var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                                    //if (fileName.Contains(".mp3") || fileName.Contains(".amr"))
                                    //{
                                    //	byte[] filebytes;
                                    //	using (var memory = new MemoryStream())
                                    //	{
                                    //		if (attachment is MimePart)
                                    //			((MimePart)attachment).ContentBase.DecodeTo(memory);
                                    //		else
                                    //			((MessagePart)attachment).Message.WriteTo(memory);

                                    //		filebytes = memory.ToArray();
                                    //	}

                                    //	if (attachment is MessagePart)
                                    //	{
                                    //		var rfc822 = (MessagePart)attachment;
                                    //		rfc822.Message.WriteTo(stream);
                                    //	}
                                    //	else
                                    //	{
                                    //		var part = (MimePart)attachment;
                                    //		part.Content.DecodeTo(stream);
                                    //	}

                                    //	byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                    //	callEmail.DispatchAudioFileName = attachment.Name;
                                    //	callEmail.DispatchAudio = filebytes;
                                    //}
                                }
                                catch { }
                            }

                            if (emailSettings == null)
                            {
                                emailSettings              = new DepartmentCallEmail();
                                emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                emailSettings.DepartmentId = departmentId.Value;
                                emailSettings.Department   = _departmentsService.GetDepartmentById(departmentId.Value, false);
                            }
                            else if (emailSettings.Department == null)
                            {
                                emailSettings.Department = _departmentsService.GetDepartmentById(departmentId.Value);
                            }

                            var activeCalls     = _callsService.GetLatest10ActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                            var units           = _unitsService.GetUnitsForDepartment(emailSettings.Department.DepartmentId);
                            var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                            int defaultPriority = (int)CallPriority.High;

                            if (priorities != null && priorities.Any())
                            {
                                var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                if (defaultPrio != null)
                                {
                                    defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                }
                            }

                            var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                           emailSettings.Department.ManagingUserId,
                                                                           departmentUsers, emailSettings.Department, activeCalls, units, defaultPriority);

                            if (call != null)
                            {
                                call.DepartmentId = departmentId.Value;

                                var savedCall = _callsService.SaveCall(call);

                                var cqi = new CallQueueItem();
                                cqi.Call                 = savedCall;
                                cqi.Profiles             = _userProfileService.GetAllProfilesForDepartment(call.DepartmentId).Select(x => x.Value).ToList();
                                cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                _queueService.EnqueueCallBroadcast(cqi);

                                //return new HttpResponseMessage(HttpStatusCode.Created);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                        }
                    }
                    #endregion Dispatch
                }
                else if (type == 2)                 // Email List
                {
                    #region Distribution Email
                    var list = _distributionListsService.GetDistributionListByAddress(emailAddress);

                    if (list != null)
                    {
                        if (String.IsNullOrWhiteSpace(bounceEmail))
                        {
                            try
                            {
                                List <Model.File> files = new List <Model.File>();

                                //try
                                //{
                                //	if (message.Attachments != null && message.Attachments.Any())
                                //	{
                                //		foreach (var attachment in message.Attachments)
                                //		{
                                //			if (Convert.ToInt32(attachment.ContentLength) > 0)
                                //			{
                                //				Model.File file = new Model.File();

                                //				byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                //				file.Data = filebytes;
                                //				file.FileName = attachment.Name;
                                //				file.DepartmentId = list.DepartmentId;
                                //				file.ContentId = attachment.ContentID;
                                //				file.FileType = attachment.ContentType;
                                //				file.Timestamp = DateTime.UtcNow;

                                //				files.Add(_fileService.SaveFile(file));
                                //			}
                                //		}
                                //	}
                                //}
                                //catch { }

                                var dlqi = new DistributionListQueueItem();
                                dlqi.List  = list;
                                dlqi.Users = _departmentsService.GetAllUsersForDepartment(list.DepartmentId);

                                if (files != null && files.Any())
                                {
                                    dlqi.FileIds = new List <int>();
                                    dlqi.FileIds.AddRange(files.Select(x => x.FileId).ToList());
                                }

                                dlqi.Message             = new InboundMessage();
                                dlqi.Message.Attachments = new List <InboundMessageAttachment>();

                                //if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                                //{
                                //	dlqi.Message.FromEmail = message.FromFull.Email.Trim();
                                //	dlqi.Message.FromName = message.FromFull.Name.Trim();
                                //}

                                dlqi.Message.Subject   = mailMessage.Subject;
                                dlqi.Message.HtmlBody  = mailMessage.HtmlBody;
                                dlqi.Message.TextBody  = mailMessage.TextBody;
                                dlqi.Message.MessageID = mailMessage.MessageId;

                                _queueService.EnqueueDistributionListBroadcast(dlqi);
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                            }
                        }
                        else
                        {
                            //return new HttpResponseMessage(HttpStatusCode.Created);
                        }
                    }

                    //return new HttpResponseMessage(HttpStatusCode.Created);
                    #endregion Distribution Email
                }
                if (type == 3)                  // Group Dispatch
                {
                    #region Group Dispatch Email
                    var departmentGroup = _departmentGroupsService.GetGroupByDispatchEmailCode(emailAddress);

                    if (departmentGroup != null)
                    {
                        try
                        {
                            var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentGroup.DepartmentId);
                            //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                            var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                            var callEmail = new CallEmail();
                            callEmail.Subject = mailMessage.Subject;

                            if (!String.IsNullOrWhiteSpace(mailMessage.HtmlBody))
                            {
                                //callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                callEmail.Body = mailMessage.HtmlBody;
                            }
                            else
                            {
                                callEmail.Body = mailMessage.TextBody;
                            }

                            //foreach (var attachment in mailMessage.Attachments)
                            //{
                            //	try
                            //	{
                            //		if (Convert.ToInt32(attachment.ContentLength) > 0)
                            //		{
                            //			if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                            //			{
                            //				byte[] filebytes = Convert.FromBase64String(attachment.Content);

                            //				callEmail.DispatchAudioFileName = attachment.Name;
                            //				callEmail.DispatchAudio = filebytes;
                            //			}
                            //		}
                            //	}
                            //	catch { }
                            //}

                            if (emailSettings == null)
                            {
                                emailSettings              = new DepartmentCallEmail();
                                emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                emailSettings.DepartmentId = departmentGroup.DepartmentId;

                                if (departmentGroup.Department != null)
                                {
                                    emailSettings.Department = departmentGroup.Department;
                                }
                                else
                                {
                                    emailSettings.Department = _departmentsService.GetDepartmentById(departmentGroup.DepartmentId);
                                }
                            }

                            var activeCalls = _callsService.GetActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                            var units       = _unitsService.GetAllUnitsForGroup(departmentGroup.DepartmentGroupId);

                            var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                            int defaultPriority = (int)CallPriority.High;

                            if (priorities != null && priorities.Any())
                            {
                                var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                if (defaultPrio != null)
                                {
                                    defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                }
                            }

                            var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                           emailSettings.Department.ManagingUserId,
                                                                           departmentGroupUsers.Select(x => x.User).ToList(), emailSettings.Department, activeCalls, units, defaultPriority);

                            if (call != null)
                            {
                                call.DepartmentId = departmentGroup.DepartmentId;

                                var savedCall = _callsService.SaveCall(call);

                                var cqi = new CallQueueItem();
                                cqi.Call                 = savedCall;
                                cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(departmentGroupUsers.Select(x => x.UserId).ToList());
                                cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                _queueService.EnqueueCallBroadcast(cqi);

                                //return new HttpResponseMessage(HttpStatusCode.Created);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                        }
                    }
                    #endregion Group Dispatch Email
                }
                if (type == 4)                  // Group Message
                {
                    #region Group Message
                    var departmentGroup = _departmentGroupsService.GetGroupByMessageEmailCode(emailAddress);

                    if (departmentGroup != null)
                    {
                        try
                        {
                            //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                            var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                            var newMessage = new Message();
                            newMessage.SentOn          = DateTime.UtcNow;
                            newMessage.SendingUserId   = departmentGroup.Department.ManagingUserId;
                            newMessage.IsBroadcast     = true;
                            newMessage.Subject         = mailMessage.Subject;
                            newMessage.SystemGenerated = true;

                            if (!String.IsNullOrWhiteSpace(mailMessage.HtmlBody))
                            {
                                //newMessage.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                newMessage.Body = mailMessage.HtmlBody;
                            }
                            else
                            {
                                newMessage.Body = mailMessage.TextBody;
                            }

                            foreach (var member in departmentGroupUsers)
                            {
                                if (newMessage.GetRecipients().All(x => x != member.UserId))
                                {
                                    newMessage.AddRecipient(member.UserId);
                                }
                            }

                            var savedMessage = _messageService.SaveMessage(newMessage);
                            _messageService.SendMessage(savedMessage, "", departmentGroup.DepartmentId, false);

                            //return new HttpResponseMessage(HttpStatusCode.Created);
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
                        }
                    }

                    #endregion Group Message
                }

                //return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
            catch (Exception ex)
            {
                Framework.Logging.LogException(ex);
                //throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.ToString()) });
            }

            return(Task.FromResult(SmtpResponse.Ok));
        }
Exemple #50
0
 public void SemanticAnalysis_AwkwardTypeDeclaration()
 {
     Bootstrapper.StartSemanticAnaylsisDebug(new string[] { @"SemanticAnalysis\Source\AwkwardTypeDeclaration.c" });
     TestTools.CompareFileEquality(@"SemanticAnalysis\Expected\AwkwardTypeDeclaration.txt", CommonTools.OutputFilePaths[0]);
 }
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     Bootstrapper.Start();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CsvCompilerModule"/> class.
 /// </summary>
 public CsvCompilerModule(Bootstrapper bootstrapper) : base(bootstrapper)
 {
     csvCompiler = new CsvCompiler();
 }
        private void InitializeServiceControl(ScenarioContext context, string[] instanceNames)
        {
            if (instanceNames.Length == 0)
            {
                instanceNames = new[] { Settings.DEFAULT_SERVICE_NAME };
            }

            // how to deal with the statics here?
            LogManager.Use <NLogFactory>();
            NLog.LogManager.Configuration = SetupLogging(Settings.DEFAULT_SERVICE_NAME);

            var startPort = 33333;

            foreach (var instanceName in instanceNames)
            {
                startPort = FindAvailablePort(startPort);
                var settings = new Settings(instanceName)
                {
                    Port   = startPort++,
                    DbPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()),
                    ForwardErrorMessages         = false,
                    ForwardAuditMessages         = false,
                    TransportType                = transportToUse.TypeName,
                    TransportConnectionString    = transportToUse.ConnectionString,
                    ProcessRetryBatchesFrequency = TimeSpan.FromSeconds(2),
                    MaximumConcurrencyLevel      = 2,
                    HttpDefaultConnectionLimit   = int.MaxValue
                };

                if (instanceName == Settings.DEFAULT_SERVICE_NAME)
                {
                    SetSettings(settings);
                }

                SetInstanceSettings(instanceName, settings);
                SettingsPerInstance[instanceName] = settings;

                var configuration = new BusConfiguration();
                configuration.TypesToScan(GetTypesScopedByTestClass(transportToUse).Concat(new[]
                {
                    typeof(MessageMapperInterceptor),
                    typeof(RegisterWrappers),
                    typeof(SessionCopInBehavior),
                    typeof(SessionCopInBehaviorForMainPipe),
                    typeof(TraceIncomingBehavior),
                    typeof(TraceOutgoingBehavior)
                }));
                configuration.EnableInstallers();

                configuration.GetSettings().SetDefault("ScaleOut.UseSingleBrokerQueue", true);
                configuration.GetSettings().Set("SC.ScenarioContext", context);

                // This is a hack to ensure ServiceControl picks the correct type for the messages that come from plugins otherwise we pick the type from the plugins assembly and that is not the type we want, we need to pick the type from ServiceControl assembly.
                // This is needed because we no longer use the AppDomain separation.
                configuration.EnableFeature <MessageMapperInterceptor>();
                configuration.RegisterComponents(r => { configuration.GetSettings().Set("SC.ConfigureComponent", r); });

                configuration.RegisterComponents(r =>
                {
                    r.RegisterSingleton(context.GetType(), context);
                    r.RegisterSingleton(typeof(ScenarioContext), context);
                });

                configuration.Pipeline.Register <SessionCopInBehavior.Registration>();
                configuration.Pipeline.Register <SessionCopInBehaviorForMainPipe.Registration>();
                configuration.Pipeline.Register <TraceIncomingBehavior.Registration>();
                configuration.Pipeline.Register <TraceOutgoingBehavior.Registration>();

                if (instanceName == Settings.DEFAULT_SERVICE_NAME)
                {
                    CustomConfiguration(configuration);
                }

                CustomInstanceConfiguration(instanceName, configuration);

                Bootstrapper bootstrapper;
                using (new DiagnosticTimer($"Initializing Bootstrapper for {instanceName}"))
                {
                    var loggingSettings = new LoggingSettings(settings.ServiceName);
                    bootstrapper = new Bootstrapper(() => { }, settings, configuration, loggingSettings);
                    bootstrappers[instanceName]    = bootstrapper;
                    bootstrapper.HttpClientFactory = HttpClientFactory;
                }
                using (new DiagnosticTimer($"Initializing AppBuilder for {instanceName}"))
                {
                    var app = new AppBuilder();
                    bootstrapper.Startup.Configuration(app);
                    var appFunc = app.Build();

                    var handler = new OwinHttpMessageHandler(appFunc)
                    {
                        UseCookies        = false,
                        AllowAutoRedirect = false
                    };
                    Handlers[instanceName]       = handler;
                    portToHandler[settings.Port] = handler; // port should be unique enough
                    var httpClient = new HttpClient(handler);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClients[instanceName] = httpClient;
                }

                using (new DiagnosticTimer($"Creating and starting Bus for {instanceName}"))
                {
                    busses[instanceName] = bootstrapper.Start(true);
                }
            }

            // how to deal with the statics here?
            ArchivingManager.ArchiveOperations = new Dictionary <string, InMemoryArchive>();
            RetryingManager.RetryOperations    = new Dictionary <string, InMemoryRetry>();
        }
        public void Start()
        {
            var bootstrap = new Bootstrapper();

            bootstrap.Initialize();
        }
Exemple #55
0
        public void Initialize(UnoHostProject project, IObserver <OpenGlVersion> glObserver)
        {
            IGL gl = new OpenTKGL();

#if DEBUG
            GL.Initialize(gl, true);
#else
            GL.Initialize(gl, false);
#endif
            ApplicationContext.Initialize(this);
            glObserver.OnNext(
                new OpenGlVersion(
                    gl.GetString(GLStringName.Version),
                    gl.GetString(GLStringName.Vendor),
                    gl.GetString(GLStringName.Renderer)));


            // Hook up size / dpi changed

            _form.DpiChanged += (s, a) =>
            {
                _unoWindow.ChangeSize(Size.ToPixelSize(), _form.Density);
                PerformRepaint();
            };

            Resize += (s, a) =>
            {
                _unoWindow.ChangeSize(Size.ToPixelSize(), _form.Density);
                PerformRepaint();
            };

            _form.Closed += (s, a) => Bootstrapper.OnAppTerminating(_unoWindow);


            // Hook up mouse events

            MouseDown += (s, a) =>
                         _log.TrySomethingBlocking(
                () =>
            {
                if (a.Button == System.Windows.Forms.MouseButtons.Right)
                {
                    return;
                }

                Bootstrapper.OnMouseDown(_unoWindow, a.X, a.Y, a.Button.ToUno());
            });

            MouseUp += (s, a) =>
                       _log.TrySomethingBlocking(() => Bootstrapper.OnMouseUp(_unoWindow, a.X, a.Y, a.Button.ToUno()));

            MouseMove += (s, a) =>
                         _log.TrySomethingBlocking(() => Bootstrapper.OnMouseMove(_unoWindow, a.X, a.Y));

            //control.MouseEnter += (s, a) =>
            //	log.TrySomethingBlocking(() => toApp.OnPointerEvent(new PointerEnterEventArgs(WinFormsInputState.Query())));

            MouseLeave += (s, a) =>
                          _log.TrySomethingBlocking(() => Bootstrapper.OnMouseOut(_unoWindow));

            MouseWheel += (s, a) =>
            {
                var numLinesPerScroll = SystemInformation.MouseWheelScrollLines;
                var deltaMode         = numLinesPerScroll > 0
                                        ? Uno.Platform.WheelDeltaMode.DeltaLine
                                        : Uno.Platform.WheelDeltaMode.DeltaPage;

                var delta = deltaMode == Uno.Platform.WheelDeltaMode.DeltaLine
                                        ? (a.Delta / 120.0f) * (float)numLinesPerScroll
                                        : a.Delta / 120.0f;

                _log.TrySomethingBlocking(() => Bootstrapper.OnMouseWheel(_unoWindow, 0, delta, (int)deltaMode));
            };


            // Hook up keyboard events

            KeyDown += (s, a) =>
                       _log.TrySomethingBlocking(() =>
                                                 a.Handled = a.KeyCode.ToKey().MatchWith(
                                                     key => Bootstrapper.OnKeyDown(_unoWindow, key),
                                                     () => false));

            KeyUp += (s, a) =>
                     _log.TrySomethingBlocking(() =>
                                               a.Handled = a.KeyCode.ToKey().MatchWith(
                                                   key => Bootstrapper.OnKeyUp(_unoWindow, key),
                                                   () => false));

            KeyPress += (s, a) =>
                        _log.TrySomethingBlocking(() =>
            {
                if (!char.IsControl(a.KeyChar))
                {
                    a.Handled = Bootstrapper.OnTextInput(_unoWindow, a.KeyChar.ToString());
                }
            });

            _unoWindow.ChangeSize(_form.Size.ToPixelSize(), _form.Density);
        }
 private static void InitializeContainer(Container container)
 {
     Bootstrapper.RegisterServices(container);
 }
 public static void Start()
 {
     Bootstrapper.Initialise();
 }
 protected void Application_Start(object sender, EventArgs e)
 {
     Bootstrapper.Run();
     RouteProvider.RegisterRoutes(RouteTable.Routes);
 }
Exemple #59
0
 public static void MapEventProxy <TEvent>(this IAppBuilder app)
 {
     Bootstrapper.Init <TEvent>();
     app.Map("/eventAggregation/events", subApp => subApp.Use <EventScriptMiddleware <TEvent> >());
 }
Exemple #60
0
 public void SemanticAnalysis_FunctionCall()
 {
     Bootstrapper.StartSemanticAnaylsisDebug(new string[] { @"SemanticAnalysis\Source\FunctionCall.c" });
     TestTools.CompareFileEquality(@"SemanticAnalysis\Expected\FunctionCall.txt", CommonTools.OutputFilePaths[0]);
 }