Exemplo n.º 1
0
        public void CopyCtor_CopiesItemsDictionary_FromTheGivenContext()
        {
            var context = new CreateContext(_connection.Object, _job, _state.Object);
            var contextCopy = new CreateContext(context);

            Assert.Same(context.Items, contextCopy.Items);
        }
Exemplo n.º 2
0
        public void CopyCtor_CopiesItemsDictionary_FromTheGivenContext()
        {
            var context = CreateContext();
            var contextCopy = new CreateContext(context);

            Assert.Same(context.Items, contextCopy.Items);
        }
Exemplo n.º 3
0
        public Stream BuildPackage(ExtensionDescriptor extensionDescriptor) {
            var context = new CreateContext();
            BeginPackage(context);
            try {
                EstablishPaths(context, _webSiteFolder, extensionDescriptor.Location, extensionDescriptor.Id, extensionDescriptor.ExtensionType);
                SetCoreProperties(context, extensionDescriptor);

                string projectFile = extensionDescriptor.Id + ".csproj";
                if (LoadProject(context, projectFile)) {
                    EmbedVirtualFile(context, projectFile, MediaTypeNames.Text.Xml);
                    EmbedProjectFiles(context, "Compile", "Content", "None", "EmbeddedResource");
                    EmbedReferenceFiles(context);
                } else if (DefaultExtensionTypes.IsTheme(extensionDescriptor.ExtensionType)) {
                    // this is a simple theme with no csproj
                    EmbedThemeFiles(context);
                }
            }
            finally {
                EndPackage(context);
            }

            if (context.Stream.CanSeek) {
                context.Stream.Seek(0, SeekOrigin.Begin);
            }

            return context.Stream;
        }
Exemplo n.º 4
0
        public void CopyCtor_CopiesJobId_FromTheGivenContext()
        {
            var context = new CreateContext(_connection.Object, _job, _state.Object);
            var contextCopy = new CreateContext(context);

            Assert.Same(context.JobId, contextCopy.JobId);
        }
Exemplo n.º 5
0
        internal ClientExceptionContext(CreateContext createContext, Exception exception)
            : base(createContext)
        {
            if (exception == null) throw new ArgumentNullException("exception");

            Exception = exception;
        }
Exemplo n.º 6
0
 internal CreatedContext(
     CreateContext context, 
     bool canceled, 
     Exception exception)
     : base(context)
 {
     Canceled = canceled;
     Exception = exception;
 }
        public ClientExceptionContextFacts()
        {
            var connection = new Mock<IStorageConnection>();
            var job = Job.FromExpression(() => TestMethod());
            var state = new Mock<IState>();
            var stateMachineFactory = new Mock<IStateMachineFactory>();

            _createContext = new CreateContext(
                connection.Object, stateMachineFactory.Object, job, state.Object);
        }
Exemplo n.º 8
0
        public void Ctor_CorrectlyInitializes_AllProperties()
        {
            var context = new CreateContext(_connection.Object, _job, _state.Object);

            Assert.Same(_connection.Object, context.Connection);
            Assert.Same(_job, context.Job);
            Assert.Same(_state.Object, context.InitialState);

            Assert.NotNull(context.Items);
            Assert.Null(context.JobId);
        }
Exemplo n.º 9
0
        private static void SetCoreProperties(CreateContext context, ExtensionDescriptor extensionDescriptor) {
            context.Builder.Id = BuildPackageId(extensionDescriptor.Id, extensionDescriptor.ExtensionType);
            context.Builder.Version = new Version(extensionDescriptor.Version);
            context.Builder.Title = extensionDescriptor.Name ?? extensionDescriptor.Id;
            context.Builder.Description = extensionDescriptor.Description;
            context.Builder.Authors.Add(extensionDescriptor.Author);

            if(Uri.IsWellFormedUriString(extensionDescriptor.WebSite, UriKind.Absolute)) {
                context.Builder.ProjectUrl = new Uri(extensionDescriptor.WebSite);
            }
        }
Exemplo n.º 10
0
        public void Ctor_CanceledProperty_IsFalseByDefault()
        {
            var connection = new Mock<IStorageConnection>();
            var job = Job.FromExpression(() => TestMethod());
            var state = new Mock<IState>();
            var stateMachineFactory = new Mock<IStateMachineFactory>();

            var createContext = new CreateContext(
                connection.Object, stateMachineFactory.Object, job, state.Object);
            var context = new CreatingContext(createContext);

            Assert.False(context.Canceled);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Get the instance.
        /// </summary>
        /// <param name="context">Context used to create instances.</param>
        /// <param name="instance">The instance.</param>
        /// <returns>
        /// Instance if found; otherwise null.
        /// </returns>
        public InstanceResult GetInstance(CreateContext context, out object instance)
        {
            var strategyContext = new ExternalInstanceStrategyContext
            {
                BuildPlan = this,
                CreateContext = context
            };

            var result =  _instanceStrategy.GetInstance(strategyContext, out instance);
            if (result == InstanceResult.Created && _callback != null)
                instance = _callback.InstanceCreated(context, this, instance);

            return result;
        }
        /// <summary>
        /// Get the instance.
        /// </summary>
        /// <param name="context">Context used to create instances.</param>
        /// <param name="instance">The instance.</param>
        /// <returns>
        /// If an existing or an new instance is returned.
        /// </returns>
        /// <remarks>
        /// Use one of the set methods to assigned the instance.
        /// </remarks>
        public InstanceResult GetInstance(CreateContext context, out object instance)
        {
            var array = (object[]) Array.CreateInstance(_serviceType, _buildPlans.Length);
            var index = 0;
            foreach (var buildPlan in _buildPlans)
            {
                object innerInstance;
                buildPlan.GetInstance(context, out innerInstance);

                array[index++] = innerInstance;
            }

            instance = array;
            return InstanceResult.Loaded;
        }
Exemplo n.º 13
0
        public void Ctor_CorrectlySetsAllProperties()
        {
            var connection = new Mock<IStorageConnection>();
            var job = Job.FromExpression(() => TestMethod());
            var state = new Mock<IState>();
            var exception = new Exception();
            var stateMachineFactory = new Mock<IStateMachineFactory>();

            var createContext = new CreateContext(
                connection.Object, stateMachineFactory.Object, job, state.Object);
            var context = new CreatedContext(createContext, true, exception);

            Assert.True(context.Canceled);
            Assert.Same(exception, context.Exception);
        }
        private async Task CreatingAContext()
        {
            _contextCommand = FightingFantasyContext.FightingFantasyContextCommand;

            var quickContextCommand = new QuickContext
            {
                Context = _contextCommand,
                CharacterTypes = _characterTypes,
                ItemTypes = _itemTypes
            };

            var response = await _mediator.Send(quickContextCommand);
            response.Should().NotBeNull();
            response.Result.Should().NotBeEmpty();
            _contextId = response.Result;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Get the instance.
        /// </summary>
        /// <param name="context">Context used to create instances.</param>
        /// <param name="instance">The instance.</param>
        /// <returns>
        /// If an existing or an new instance is returned.
        /// </returns>
        /// <remarks>
        /// Use one of the set methods to assigned the instance.
        /// </remarks>
        public InstanceResult GetInstance(CreateContext context, out object instance)
        {
            var array = (object[])Array.CreateInstance(_serviceType, _buildPlans.Length);
            var index = 0;

            foreach (var buildPlan in _buildPlans)
            {
                object innerInstance;
                buildPlan.GetInstance(context, out innerInstance);

                array[index++] = innerInstance;
            }

            instance = array;
            return(InstanceResult.Loaded);
        }
Exemplo n.º 16
0
        public void testgetbooking()
        {
            var context = CreateContext.getNewContext("TestingDB");
            var repo    = new BookingRepo(context);
            var VC      = new BookingController(repo);
            IEnumerable <Bookings> Result = VC.GetBookings();

            string[] names = { "Cancelled", "Upcoming" };
            int      count = 0;

            foreach (Bookings b in Result)
            {
                Assert.Equal(b.ClientName, names[count]);
                count++;
            }
        }
Exemplo n.º 17
0
        public void testgetclient()
        {
            var context = CreateContext.getNewContext("TestingDB");
            var repo    = new ClientRepo(context);
            var VC      = new VenueController(repo);
            IEnumerable <Clients> Result = VC.Get();

            string[] names = { "Alabama Coffee", "Brad's Bistro" };
            int      count = 0;

            foreach (Clients c in Result)
            {
                Assert.Equal(c.ClientName, names[count]);
                count++;
            }
        }
Exemplo n.º 18
0
        public void testgettag()
        {
            var context = CreateContext.getNewContext("TestingDB");
            var repo    = new TagRepo(context);
            var VC      = new TagsController(repo);
            IEnumerable <Tags> Result = VC.GetTags();

            string[] names = { "Loud", "Fun" };
            int      count = 0;

            foreach (Tags t in Result)
            {
                Assert.Equal(t.Tag, names[count]);
                count++;
            }
        }
Exemplo n.º 19
0
        public void testgetPerformer()
        {
            var context = CreateContext.getNewContext("TestingDB");
            var repo    = new PerformerRepo(context);
            var VC      = new PerformersController(repo);
            IEnumerable <Performers> Result = VC.GetPerformers();

            string[] names = { "Zeals Seals", "Young Ones" };
            int      count = 0;

            foreach (Performers p in Result)
            {
                Assert.Equal(p.GroupName, names[count]);
                count++;
            }
        }
Exemplo n.º 20
0
        private static void CreateWithFilters(
            CreateContext context,
            IEnumerable<IClientFilter> filters)
        {
            var preContext = new CreatingContext(context);
            Func<CreatedContext> continuation = () =>
            {
                context.CreateJob();
                return new CreatedContext(context, false, null);
            };

            var thunk = filters.Reverse().Aggregate(continuation,
                (next, filter) => () => InvokeClientFilter(filter, preContext, next));

            thunk();
        }
        protected override void OnOpenGlInit(GlInterface gl, int fb)
        {
            base.OnOpenGlInit(gl, fb);

            var tmp = new AvaloniaBindingContext(gl);

            OpenTK.Graphics.ES11.GL.LoadBindings(tmp);
            OpenTK.Graphics.ES20.GL.LoadBindings(tmp);
            OpenTK.Graphics.ES30.GL.LoadBindings(tmp);
            OpenTK.Graphics.OpenGL.GL.LoadBindings(tmp);
            OpenTK.Graphics.OpenGL4.GL.LoadBindings(tmp);

            CreateContext?.Invoke();

            Load?.Invoke();
            _stopwatch.Start();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Get the instance.
        /// </summary>
        /// <param name="context">Context used to create instances.</param>
        /// <param name="instance">The instance.</param>
        /// <returns>
        /// Instance if found; otherwise null.
        /// </returns>
        public InstanceResult GetInstance(CreateContext context, out object instance)
        {
            var strategyContext = new ExternalInstanceStrategyContext
            {
                BuildPlan     = this,
                CreateContext = context
            };

            var result = _instanceStrategy.GetInstance(strategyContext, out instance);

            if (result == InstanceResult.Created && _callback != null)
            {
                instance = _callback.InstanceCreated(context, this, instance);
            }

            return(result);
        }
Exemplo n.º 23
0
        /// <inheritdoc />
        public string Create(Job job, State state)
        {
            if (job == null) throw new ArgumentNullException("job");
            if (state == null) throw new ArgumentNullException("state");

            try
            {
                var context = new CreateContext(_connection, job, state);
                _process.Run(context);

                return context.JobId;
            }
            catch (Exception ex)
            {
                throw new CreateJobFailedException("Job creation process has bee failed. See inner exception for details", ex);
            }
        }
Exemplo n.º 24
0
        public AngleBackend(bool isCpuBackend = false)
        {
            IsCpuBackend = isCpuBackend;
            var ptrsize = Marshal.SizeOf(typeof(IntPtr));

            if (ptrsize == 8)
            {
                EGL = LoadLibrary("x64/libEGL.dll");
                GL  = LoadLibrary("x64/libGLESv2.dll");
            }
            else
            {
                EGL = LoadLibrary("x86/libEGL.dll");
                GL  = LoadLibrary("x86/libGLESv2.dll");
            }
            EglChooseConfig          = (ChooseConfig)EGL_GetProcAddress("eglChooseConfig", typeof(ChooseConfig));
            EglGetPlatformDisplayExt = (GetPlatformDisplayExt)EGL_GetProcAddress("eglGetPlatformDisplayEXT", typeof(GetPlatformDisplayExt));
            EglInitialize            = (Initialize)EGL_GetProcAddress("eglInitialize", typeof(Initialize));
            EglGetConfigs            = (GetConfigs)EGL_GetProcAddress("eglGetConfigs", typeof(GetConfigs));
            EglCreateContext         = (CreateContext)EGL_GetProcAddress("eglCreateContext", typeof(CreateContext));
            EglCreatePbufferSurface  = (CreatePbufferSurface)EGL_GetProcAddress("eglCreatePbufferSurface", typeof(CreatePbufferSurface));
            EglCreateWindowSurface   = (CreateWindowSurface)EGL_GetProcAddress("eglCreateWindowSurface", typeof(CreateWindowSurface));
            EglDestroyContext        = (DestroyContext)EGL_GetProcAddress("eglDestroyContext", typeof(DestroyContext));
            EglMakeCurrent           = (MakeCurrent)EGL_GetProcAddress("eglMakeCurrent", typeof(MakeCurrent));
            EglSwapBuffers           = (SwapBuffers)EGL_GetProcAddress("eglSwapBuffers", typeof(SwapBuffers));
            EglSurfaceAttrib         = (SurfaceAttrib)EGL_GetProcAddress("eglSurfaceAttrib", typeof(SurfaceAttrib));
            EglWaitClient            = (WaitClient)EGL_GetProcAddress("eglWaitClient", typeof(WaitClient));
            EglWaitGL                             = (WaitGL)EGL_GetProcAddress("eglWaitGL", typeof(WaitGL));
            EglDestroySurface                     = (DestroySurface)EGL_GetProcAddress("eglDestroySurface", typeof(DestroySurface));
            EglSwapInterval                       = (SwapInterval)EGL_GetProcAddress("eglSwapInterval", typeof(SwapInterval));
            EglTerminate                          = (Terminate)EGL_GetProcAddress("eglTerminate", typeof(Terminate));
            EglSurfaceAttrib                      = (SurfaceAttrib)EGL_GetProcAddress("eglSurfaceAttrib", typeof(SurfaceAttrib));
            EglWaitNative                         = (WaitNative)EGL_GetProcAddress("eglWaitNative", typeof(WaitNative));
            EglGetProcAddress                     = (EGLGetProcAddress)EGL_GetProcAddress("eglGetProcAddress", typeof(EGLGetProcAddress));
            GlGetIntegerv                         = (GetIntegerv)GL_GetProcAddress("glGetIntegerv", typeof(GetIntegerv));
            GlBindRenderbuffer                    = (BindRenderbuffer)GL_GetProcAddress("glBindRenderbuffer", typeof(BindRenderbuffer));
            GlFramebufferRenderbuffer             = (FramebufferRenderbuffer)GL_GetProcAddress("glFramebufferRenderbuffer", typeof(FramebufferRenderbuffer));
            GlBindFramebuffer                     = (BindFramebuffer)GL_GetProcAddress("glBindFramebuffer", typeof(BindFramebuffer));
            GlGenRenderbuffers                    = (GenRenderbuffers)GL_GetProcAddress("glGenRenderbuffers", typeof(GenRenderbuffers));
            GlGenFramebuffers                     = (GenFramebuffers)GL_GetProcAddress("glGenFramebuffers", typeof(GenFramebuffers));
            GlRenderbufferStorageMultisampleANGLE =
                (RenderbufferStorageMultisampleANGLE)GL_GetProcAddress("glRenderbufferStorageMultisampleANGLE", typeof(RenderbufferStorageMultisampleANGLE));
            GlBlitFramebufferANGLE =
                (BlitFramebufferANGLE)GL_GetProcAddress("glBlitFramebufferANGLE", typeof(BlitFramebufferANGLE));
        }
Exemplo n.º 25
0
        private static void EmbedThemeFiles(CreateContext context)
        {
            var basePath = context.SourcePath;

            foreach (var virtualPath in context.SourceFolder.ListFiles(context.SourcePath, true))
            {
                // ignore dlls, etc
                if (IgnoreFile(virtualPath))
                {
                    continue;
                }
                // full virtual path given but we need the relative path so it can be put into
                // the package that way (the package itself is the logical base path).
                // Get it by stripping the basePath off including the slash.
                var relativePath = virtualPath.Replace(basePath, "");
                EmbedVirtualFile(context, relativePath, MediaTypeNames.Application.Octet);
            }
        }
Exemplo n.º 26
0
        private static void EmbedProjectFiles(CreateContext context, params string[] itemGroupTypes)
        {
            IEnumerable <XElement> itemGroups = context.Project
                                                .Elements(Ns("Project"))
                                                .Elements(Ns("ItemGroup"));

            foreach (string itemGroupType in itemGroupTypes)
            {
                IEnumerable <string> includePaths = itemGroups
                                                    .Elements(Ns(itemGroupType))
                                                    .Attributes("Include")
                                                    .Select(x => x.Value);
                foreach (string includePath in includePaths)
                {
                    EmbedVirtualFile(context, includePath, MediaTypeNames.Application.Octet);
                }
            }
        }
        public void PipelineFactory_GivenCreateContextAndPostMethod_BuildsExpectedBatchingPipeline()
        {
            const int entityCount = 55;

            var entities = new TestEntity[entityCount];

            for (int i = 0; i < entityCount; i++)
            {
                entities[i] = new TestEntity();
            }

            var context = new CreateContext <TestEntity>(
                EndpointName.CurrentTotalsReports,
                entities);

            var outerPipeline = (RequestPipeline)this.pipelineFactory.GetPipeline(context);

            Type[] expectedOuterElementTypes =
            {
                typeof(AutoBatchingPipeline),
                typeof(MultiStatusHandler)
            };

            IPipelineElement[] actualOuterElements = outerPipeline.PipelineElements.ToArray();

            AssertElements(expectedOuterElementTypes, actualOuterElements);

            // Validate the nested pipeline elements
            var innerPipeline = (RequestPipeline)((AutoBatchingPipeline)actualOuterElements[0]).InnerPipeline;

            Type[] expectedInnerElementTypes =
            {
                typeof(CreateContextValidator),
                typeof(CreateRequestSerializer),
                typeof(RestClientPostHandler),
                typeof(ModificationResultsDeserializer),
                typeof(SupplementalDataDeserializer),
                typeof(MultiStatusHandler)
            };

            IPipelineElement[] actualInnerElements = innerPipeline.PipelineElements.ToArray();

            AssertElements(expectedInnerElementTypes, actualInnerElements);
        }
        public PreserveCultureAttributeFacts()
        {
            _connection = new Mock <IStorageConnection>();
            var job   = Job.FromExpression(() => Sample());
            var state = new Mock <IState>();

            var createContext = new CreateContext(
                _connection.Object, job, state.Object);

            _creatingContext = new CreatingContext(createContext);

            var workerContext = new WorkerContextMock();

            var performContext = new PerformContext(
                workerContext.Object, _connection.Object, JobId, job, DateTime.UtcNow, new Mock <IJobExecutionContext>().Object);

            _performingContext = new PerformingContext(performContext);
            _performedContext  = new PerformedContext(performContext, null, false, null);
        }
Exemplo n.º 29
0
        public virtual void Run(CreateContext context)
        {
            var filterInfo = GetFilters(context.Job.MethodData);

            try
            {
                CreateWithFilters(context, filterInfo.ClientFilters);
            }
            catch (Exception ex)
            {
                var exceptionContext = new ClientExceptionContext(context, ex);

                InvokeExceptionFilters(exceptionContext, filterInfo.ClientExceptionFilters);
                if (!exceptionContext.ExceptionHandled)
                {
                    throw;
                }
            }
        }
        public PreserveCultureAttributeFacts()
        {
            _connection = new Mock<IStorageConnection>();
            var job = Job.FromExpression(() => Sample());
            var state = new Mock<IState>();
            var stateMachineFactory = new Mock<IStateMachineFactory>();

            var createContext = new CreateContext(
                _connection.Object, stateMachineFactory.Object, job, state.Object);
            _creatingContext = new CreatingContext(createContext);
            _createdContext = new CreatedContext(createContext, false, null);

            var workerContext = new WorkerContextMock();

            var performContext = new PerformContext(
                workerContext.Object, _connection.Object, JobId, job, DateTime.UtcNow, new Mock<IJobCancellationToken>().Object);
            _performingContext = new PerformingContext(performContext);
            _performedContext = new PerformedContext(performContext, false, null);
        }
Exemplo n.º 31
0
        public async Task RestClientPostHandler_RestClientIsInvokedWithExpectedInputsAsync()
        {
            CreateContext <TestEntity> context = GetCreateContext();

            // rest client Create() method is called with 3 parameters:
            // the request id, the endpoint, and the serialized request string
            this.mockRestClient
            .Setup(p => p.CreateAsync(
                       It.Is <EndpointName>(t => t.Equals(EndpointName.Tests)),
                       It.Is <string>(s => s.Equals(Request)),
                       It.IsAny <LogContext>(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(Response));

            context.RestClient = this.mockRestClient.Object;

            await this.pipelineElement.ProcessAsync(context, NullLogger.Instance, default).ConfigureAwait(false);

            this.mockRestClient.VerifyAll();
        }
Exemplo n.º 32
0
        public async Task RestClientPostHandler_RestClientSetsResponseContentPropertyOfContextObjectAsync()
        {
            CreateContext <TestEntity> context = GetCreateContext();

            this.mockRestClient
            .Setup(p => p.CreateAsync(
                       It.IsAny <EndpointName>(),
                       It.IsAny <string>(),
                       It.IsAny <LogContext>(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(Response));

            context.RestClient = this.mockRestClient.Object;

            await this.pipelineElement.ProcessAsync(context, NullLogger.Instance, default).ConfigureAwait(false);

            Assert.AreEqual(Response, context.ResponseContent, "Expected response content to be set.");

            this.mockRestClient.VerifyAll();
        }
        public async Task <IHttpActionResult> PostContext([FromBody] CreateContext newMessage)
        {
            if (newMessage == null)
            {
                return(new ResponseMessageResult(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.OK
                }));
            }

            var response = await _mediator.Send(newMessage);

            if (response is FailedResponse <Guid> )
            {
                return(new ResponseMessageResult(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                }));
            }

            return(Created($"{Request.RequestUri.ToString().TrimEnd(new[] { '/' })}/{response.Result}", string.Empty));
        }
Exemplo n.º 34
0
        public static BackgroundJob TriggerRecurringJob(
            [NotNull] this IBackgroundJobFactory factory,
            [NotNull] JobStorage storage,
            [NotNull] IStorageConnection connection,
            [NotNull] IProfiler profiler,
            [NotNull] RecurringJobEntity recurringJob,
            DateTime now)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }
            if (profiler == null)
            {
                throw new ArgumentNullException(nameof(profiler));
            }
            if (recurringJob == null)
            {
                throw new ArgumentNullException(nameof(recurringJob));
            }

            var context = new CreateContext(storage, connection, recurringJob.Job, null, profiler);

            context.Parameters["RecurringJobId"] = recurringJob.RecurringJobId;
            context.Parameters["Time"]           = JobHelper.ToTimestamp(now);

            var backgroundJob = factory.Create(context);

            recurringJob.LastExecution = now;
            recurringJob.LastJobId     = backgroundJob?.Id;

            return(backgroundJob);
        }
Exemplo n.º 35
0
        public PreserveCultureAttributeFacts()
        {
            _connection = new Mock <IStorageConnection>();

            var storage       = new Mock <JobStorage>();
            var backgroundJob = new BackgroundJobMock {
                Id = JobId
            };
            var state = new Mock <IState>();

            var createContext = new CreateContext(
                storage.Object, _connection.Object, backgroundJob.Job, state.Object);

            _creatingContext = new CreatingContext(createContext);

            var performContext = new PerformContext(
                _connection.Object, backgroundJob.Object, new Mock <IJobCancellationToken>().Object);

            _performingContext = new PerformingContext(performContext);
            _performedContext  = new PerformedContext(performContext, null, false, null);
        }
Exemplo n.º 36
0
        public void Run(CreateContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            var filterInfo = GetFilters(context.Job);

            try
            {
                CreateWithFilters(context, filterInfo.ClientFilters);
            }
            catch (Exception ex)
            {
                var exceptionContext = new ClientExceptionContext(context, ex);

                InvokeExceptionFilters(exceptionContext, filterInfo.ClientExceptionFilters);
                if (!exceptionContext.ExceptionHandled)
                {
                    throw;
                }
            }
        }
Exemplo n.º 37
0
        public Core(string args, EventHandler eventHandler)
        {
            this.eventHandler = eventHandler;

            #if STATIC_BIND
            this.coreHandler = Native.space_domain_init_context(args);
            #else
            var libName  = "libffi_space.so";
            var dataPath = Application.dataPath + "/Plugins/" + libName;
            libraryHandle = LoadLibrary(dataPath);

            // load methods
            this.nativeContextClose = GetLibraryFunction <ContextClose>(libraryHandle, "space_domain_close_context");
            this.nativeContextPush  = GetLibraryFunction <ContextPush>(libraryHandle, "space_domain_set_data");
            this.nativeContextTake  = GetLibraryFunction <ContextTake>(libraryHandle, "space_domain_get_data");
            this.nativeContextTick  = GetLibraryFunction <ContextTick>(libraryHandle, "space_domain_run_tick");

            // start ffi context
            CreateContext createContext = GetLibraryFunction <CreateContext>(libraryHandle, "space_domain_init_context");
            contextHandle = createContext.Invoke(args);
            #endif
            Debug.Log("core initialize");
        }
Exemplo n.º 38
0
        /// <inheritdoc />
        public string Create(Job job, IState state)
        {
            if (job == null)
            {
                throw new ArgumentNullException("job");
            }
            if (state == null)
            {
                throw new ArgumentNullException("state");
            }

            try
            {
                var context = new CreateContext(_connection, _stateMachineFactory, job, state);
                _process.Run(context);

                return(context.JobId);
            }
            catch (Exception ex)
            {
                throw new CreateJobFailedException("Job creation process has bee failed. See inner exception for details", ex);
            }
        }
Exemplo n.º 39
0
 private static void EstablishPaths(CreateContext context, IWebSiteFolder webSiteFolder, string locationPath, string moduleName, string moduleType) {
     context.SourceFolder = webSiteFolder;
     if (DefaultExtensionTypes.IsTheme(moduleType)) {
         context.SourcePath = "~/Themes/" + moduleName + "/";
         context.TargetPath = "\\Content\\Themes\\" + moduleName + "\\";
     }
     else {
         context.SourcePath = "~/Modules/" + moduleName + "/";
         context.TargetPath = "\\Content\\Modules\\" + moduleName + "\\";
     }
 }
Exemplo n.º 40
0
 private static void BeginPackage(CreateContext context) {
     context.Stream = new MemoryStream();
     context.Builder = new NuGetPackageBuilder();
 }
Exemplo n.º 41
0
 private static void EmbedThemeFiles(CreateContext context) {
     var basePath = context.SourcePath;
     foreach (var virtualPath in context.SourceFolder.ListFiles(context.SourcePath, true)) {
         // ignore dlls, etc
         if (IgnoreFile(virtualPath)) {
             continue;
         }
         // full virtual path given but we need the relative path so it can be put into
         // the package that way (the package itself is the logical base path).
         // Get it by stripping the basePath off including the slash.
         var relativePath = virtualPath.Replace(basePath, "");
         EmbedVirtualFile(context, relativePath, MediaTypeNames.Application.Octet);
     }
 }
Exemplo n.º 42
0
        private void EmbedReferenceFiles(CreateContext context) {
            var entries = context.Project
                .Elements(Ns("Project"))
                .Elements(Ns("ItemGroup"))
                .Elements(Ns("Reference"))
                .Select(reference => new {
                    Include = reference.Attribute("Include"),
                    HintPath = reference.Element(Ns("HintPath"))
                })
                .Where(entry => entry.Include != null);

            foreach (var entry in entries) {
                var assemblyName = new AssemblyName(entry.Include.Value);

                // If it is not a core assembly
                if (_frameworkAssemblies.GetFrameworkAssemblies().FirstOrDefault(assembly => assembly.Name.Equals(assemblyName.Name)) == null) {
                    string virtualPath = _virtualPathProvider.GetReferenceVirtualPath(context.SourcePath, assemblyName.Name, entry.HintPath != null ? entry.HintPath.Value : null);

                    if (!string.IsNullOrEmpty(virtualPath)) {
                        EmbedVirtualFile(context, virtualPath, MediaTypeNames.Application.Octet);
                    }
                }
            }
        }
Exemplo n.º 43
0
 /// <summary>
 /// Creates the actual instance
 /// </summary>
 /// <param name="context">Context information used to be able to create the object.</param>
 /// <param name="arguments">Constructor arguments</param>
 /// <returns>Created instance.</returns>
 protected virtual object Create(CreateContext context, object[] arguments)
 {
     return  _factoryMethod(arguments);
     /*return _createCallback != null
                ? _createCallback.InstanceCreated(context, instance)
                : instance;*/
 }
        private void TryScheduleJob(
            JobStorage storage,
            IStorageConnection connection,
            string recurringJobId,
            IReadOnlyDictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var cronSchedule  = CrontabSchedule.Parse(cron, _cronStringFormat);

            try
            {
                var startDate = JobHelper.DeserializeNullableDateTime(recurringJob["StartDate"]);
                if (startDate.HasValue)
                {
                    startDate = DateTime.SpecifyKind(startDate.Value, DateTimeKind.Utc);
                }

                var endDate = JobHelper.DeserializeNullableDateTime(recurringJob["EndDate"]);
                if (endDate.HasValue)
                {
                    endDate = DateTime.SpecifyKind(endDate.Value, DateTimeKind.Utc);
                }

                var ignoreEndDateTimeComponent = _ignoreTimeComponentInStartEndDates;
                if (recurringJob.ContainsKey(HashKeys.UseEndDateTimeComponent))
                {
                    bool.TryParse(recurringJob[HashKeys.UseEndDateTimeComponent] ?? bool.FalseString,
                                  out var useEndDateTimeComponent);
                    ignoreEndDateTimeComponent = !useEndDateTimeComponent;
                }

                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                    ? TimeZoneConverter.TZConvert.GetTimeZoneInfo(recurringJob[HashKeys.TimeZoneId])
                    : TimeZoneInfo.Utc;

                var startDateForZone = startDate == null ? (DateTime?)null : TimeZoneInfo.ConvertTime(startDate.Value, TimeZoneInfo.Utc, timeZone);
                var endDateForZone   = endDate == null ? (DateTime?)null : TimeZoneInfo.ConvertTime(endDate.Value, TimeZoneInfo.Utc, timeZone);

                var nowInstant        = _instantFactory(cronSchedule, timeZone);
                var nowInstantForZone = TimeZoneInfo.ConvertTime(nowInstant.NowInstant, TimeZoneInfo.Utc, timeZone);

                // If the time component should be ignored, ignore it.
                if (_ignoreTimeComponentInStartEndDates && startDateForZone.HasValue)
                {
                    startDateForZone = startDateForZone.Value.Date;
                    // Now that we have the proper date, re-adjust the UTC versions so GetNextInstants works with the proper date range
                    startDate = TimeZoneInfo.ConvertTime(startDateForZone.Value, timeZone, TimeZoneInfo.Utc);
                }

                if (endDateForZone.HasValue && ignoreEndDateTimeComponent)
                {
                    endDateForZone = (endDateForZone.Value.Date == DateTime.MaxValue.Date)
                        ? DateTime.MaxValue
                        : endDateForZone.Value.Date.AddDays(1);
                    // Now that we have the proper date, re-adjust the UTC versions so GetNextInstants works with the proper date range
                    endDate = TimeZoneInfo.ConvertTime(endDateForZone.Value, timeZone, TimeZoneInfo.Utc);
                }

                var changedFields = new Dictionary <string, string>();

                var lastInstant = GetLastInstant(recurringJob, nowInstant, startDate, endDate);

                if (WithinDateRange(nowInstantForZone, startDateForZone, endDateForZone) && nowInstant.GetNextInstants(lastInstant, endDate).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"]))
                    {
                        state.Queue = recurringJob["Queue"];
                    }

                    var context = new CreateContext(storage, connection, job, state);
                    context.Parameters["RecurringJobId"] = recurringJobId;

                    var backgroundJob = _factory.Create(context);
                    var jobId         = backgroundJob?.Id;

                    if (String.IsNullOrEmpty(jobId))
                    {
                        Logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled.");
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                // Fixing old recurring jobs that doesn't have the CreatedAt field
                if (!recurringJob.ContainsKey("CreatedAt"))
                {
                    changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                }

                changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null);

                connection.SetRangeInHash(
                    $"{PluginConstants.JobType}:{recurringJobId}",
                    changedFields);
            }
#if NETFULL
            catch (TimeZoneNotFoundException ex)
            {
#else
            catch (Exception ex)
            {
                // https://github.com/dotnet/corefx/issues/7552
                if (!ex.GetType().Name.Equals("TimeZoneNotFoundException"))
                {
                    throw;
                }
#endif

                Logger.ErrorException(
                    $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.",
                    ex);
            }
        }
Exemplo n.º 45
0
 private static void EndPackage(CreateContext context) {
     context.Builder.Save(context.Stream);
 }
Exemplo n.º 46
0
 internal CreatingContext(CreateContext context)
     : base(context)
 {
 }
Exemplo n.º 47
0
 public InstanceStrategyContext(ConcreteBuildPlan bp, CreateContext createContext, Func<object> factory)
 {
     _bp = bp;
     _factory = factory;
     CreateContext = createContext;
 }
Exemplo n.º 48
0
 public BackgroundJob Create(CreateContext context)
 {
     Console.WriteLine($"Create: {context.Job.Type.FullName}.{context.Job.Method.Name} in {context.InitialState?.Name} state");
     return(_inner.Create(context));
 }
Exemplo n.º 49
0
 internal CreatingContext(CreateContext context)
     : base(context)
 {
 }
Exemplo n.º 50
0
 public BackgroundJob Create(CreateContext context)
 {
     return(_inner.Create(context));
 }
Exemplo n.º 51
0
 private static bool LoadProject(CreateContext context, string relativePath) {
     string virtualPath = context.SourcePath + relativePath;
     if (context.SourceFolder.FileExists(virtualPath)) {
         context.Project = XDocument.Parse(context.SourceFolder.ReadFile(context.SourcePath + relativePath));
         return true;
     }
     return false;
 }
Exemplo n.º 52
0
 /// <summary>
 /// Creates the actual instance
 /// </summary>
 /// <param name="context"></param>
 /// <param name="arguments">Constructor arguments</param>
 /// <returns>
 /// Created instance.
 /// </returns>
 /// <remarks>Uses the </remarks>
 protected override object Create(CreateContext context, object[] arguments)
 {
     var type = ConcreteType.MakeGenericType(context.RequestedService.GetGenericArguments());
     return Activator.CreateInstance(type, arguments);
 }
Exemplo n.º 53
0
 private static void EmbedVirtualFile(CreateContext context, string relativePath, string contentType) {
     var file = new VirtualPackageFile(
         context.SourceFolder,
         context.SourcePath + relativePath, 
         context.TargetPath + relativePath);
     context.Builder.Files.Add(file);
 }
Exemplo n.º 54
0
 private static void EndPackage(CreateContext context)
 {
     context.Builder.Save(context.Stream);
 }
Exemplo n.º 55
0
 /// <summary>
 /// Get the instance.
 /// </summary>
 /// <param name="context">Context used to create instances.</param>
 /// <param name="instance">The instance.</param>
 /// <returns>
 /// If an existing or an new instance is returned.
 /// </returns>
 /// <remarks>
 /// Use one of the set methods to assigned the instance.
 /// </remarks>
 public InstanceResult GetInstance(CreateContext context, out object instance)
 {
     instance = Array.CreateInstance(_service, 0);
     return(InstanceResult.Loaded);
 }
Exemplo n.º 56
0
 private static void BeginPackage(CreateContext context)
 {
     context.Stream  = new MemoryStream();
     context.Builder = new NuGetPackageBuilder();
 }
Exemplo n.º 57
0
        private static void EmbedProjectFiles(CreateContext context, params string[] itemGroupTypes) {
            IEnumerable<XElement> itemGroups = context.Project
                .Elements(Ns("Project"))
                .Elements(Ns("ItemGroup"));

            foreach (string itemGroupType in itemGroupTypes) {
                IEnumerable<string> includePaths = itemGroups
                    .Elements(Ns(itemGroupType))
                    .Attributes("Include")
                    .Select(x => x.Value);
                foreach (string includePath in includePaths) {
                    EmbedVirtualFile(context, includePath, MediaTypeNames.Application.Octet);
                }
            }
        }
Exemplo n.º 58
0
        /// <summary>
        ///     Renders the object model in it's EPL syntax textual representation, using a whitespace-formatter as provided.
        /// </summary>
        /// <param name="formatter">the formatter to use</param>
        /// <param name="writer">writer to use</param>
        /// <throws>IllegalStateException if required clauses do not exist</throws>
        public void ToEPL(
            EPStatementFormatter formatter,
            TextWriter writer)
        {
            AnnotationPart.ToEPL(writer, Annotations, formatter);
            ExpressionDeclaration.ToEPL(writer, ExpressionDeclarations, formatter);
            ScriptExpression.ToEPL(writer, ScriptExpressions, formatter);
            ClassProvidedExpression.ToEPL(writer, ClassProvidedExpressions, formatter);

            if (ContextName != null)
            {
                formatter.BeginContext(writer);
                writer.Write("context ");
                writer.Write(ContextName);
            }

            if (CreateIndex != null)
            {
                formatter.BeginCreateIndex(writer);
                CreateIndex.ToEPL(writer);
                return;
            }

            if (CreateSchema != null)
            {
                formatter.BeginCreateSchema(writer);
                CreateSchema.ToEPL(writer);
                return;
            }

            if (CreateExpression != null)
            {
                formatter.BeginCreateExpression(writer);
                CreateExpression.ToEPL(writer);
                return;
            }

            if (CreateClass != null)
            {
                formatter.BeginCreateExpression(writer);
                CreateClass.ToEPL(writer);
                return;
            }

            if (CreateContext != null)
            {
                formatter.BeginCreateContext(writer);
                CreateContext.ToEPL(writer, formatter);
                return;
            }

            if (CreateWindow != null)
            {
                formatter.BeginCreateWindow(writer);
                CreateWindow.ToEPL(writer);

                writer.Write(" as ");

                if (SelectClause == null || SelectClause.SelectList.IsEmpty() && !CreateWindow.Columns.IsEmpty())
                {
                    CreateWindow.ToEPLCreateTablePart(writer);
                }
                else
                {
                    SelectClause.ToEPL(writer, formatter, false, false);
                    if (CreateWindow.AsEventTypeName != null)
                    {
                        writer.Write(" from ");
                        writer.Write(CreateWindow.AsEventTypeName);
                    }

                    CreateWindow.ToEPLInsertPart(writer);
                }

                return;
            }

            if (CreateVariable != null)
            {
                formatter.BeginCreateVariable(writer);
                CreateVariable.ToEPL(writer);
                return;
            }

            if (CreateTable != null)
            {
                formatter.BeginCreateTable(writer);
                CreateTable.ToEPL(writer);
                return;
            }

            if (CreateDataFlow != null)
            {
                formatter.BeginCreateDataFlow(writer);
                CreateDataFlow.ToEPL(writer, formatter);
                return;
            }

            var displayWhereClause = true;

            if (UpdateClause != null)
            {
                formatter.BeginUpdate(writer);
                UpdateClause.ToEPL(writer);
            }
            else if (OnExpr != null)
            {
                formatter.BeginOnTrigger(writer);
                writer.Write("on ");
                FromClause.Streams[0].ToEPL(writer, formatter);

                if (OnExpr is OnDeleteClause onDeleteClause)
                {
                    formatter.BeginOnDelete(writer);
                    writer.Write("delete from ");
                    onDeleteClause.ToEPL(writer);
                }
                else if (OnExpr is OnUpdateClause onUpdateClause)
                {
                    formatter.BeginOnUpdate(writer);
                    writer.Write("update ");
                    onUpdateClause.ToEPL(writer);
                }
                else if (OnExpr is OnSelectClause onSelectClause)
                {
                    InsertInto?.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, onSelectClause.IsDeleteAndSelect);
                    writer.Write(" from ");
                    onSelectClause.ToEPL(writer);
                }
                else if (OnExpr is OnSetClause onSetClause)
                {
                    onSetClause.ToEPL(writer, formatter);
                }
                else if (OnExpr is OnMergeClause onMergeClause)
                {
                    onMergeClause.ToEPL(writer, WhereClause, formatter);
                    displayWhereClause = false;
                }
                else
                {
                    var split = (OnInsertSplitStreamClause)OnExpr;
                    InsertInto.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, false);
                    if (WhereClause != null)
                    {
                        writer.Write(" where ");
                        WhereClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
                    }

                    split.ToEPL(writer, formatter);
                    displayWhereClause = false;
                }
            }
            else
            {
                IntoTableClause?.ToEPL(writer);

                if (SelectClause == null)
                {
                    throw new IllegalStateException("Select-clause has not been defined");
                }

                if (FromClause == null)
                {
                    throw new IllegalStateException("From-clause has not been defined");
                }

                if (FireAndForgetClause is FireAndForgetUpdate fireAndForgetUpdate)
                {
                    writer.Write("update ");
                    FromClause.ToEPLOptions(writer, formatter, false);
                    writer.Write(" ");
                    UpdateClause.RenderEPLAssignments(writer, fireAndForgetUpdate.Assignments);
                }
                else if (FireAndForgetClause is FireAndForgetInsert fireAndForgetInsert)
                {
                    InsertInto.ToEPL(writer, formatter, true);
                    if (fireAndForgetInsert.IsUseValuesKeyword)
                    {
                        writer.Write(" values (");
                        var delimiter = "";
                        foreach (var element in SelectClause.SelectList)
                        {
                            writer.Write(delimiter);
                            element.ToEPLElement(writer);
                            delimiter = ", ";
                        }

                        writer.Write(")");
                    }
                    else
                    {
                        SelectClause.ToEPL(writer, formatter, true, false);
                    }
                }
                else if (FireAndForgetClause is FireAndForgetDelete)
                {
                    writer.Write("delete ");
                    FromClause.ToEPLOptions(writer, formatter, true);
                }
                else
                {
                    InsertInto?.ToEPL(writer, formatter, true);
                    SelectClause.ToEPL(writer, formatter, true, false);
                    FromClause.ToEPLOptions(writer, formatter, true);
                }
            }

            MatchRecognizeClause?.ToEPL(writer);

            if (WhereClause != null && displayWhereClause)
            {
                formatter.BeginWhere(writer);
                writer.Write("where ");
                WhereClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
            }

            if (GroupByClause != null)
            {
                formatter.BeginGroupBy(writer);
                writer.Write("group by ");
                GroupByClause.ToEPL(writer);
            }

            if (HavingClause != null)
            {
                formatter.BeginHaving(writer);
                writer.Write("having ");
                HavingClause.ToEPL(writer, ExpressionPrecedenceEnum.MINIMUM);
            }

            if (OutputLimitClause != null)
            {
                formatter.BeginOutput(writer);
                writer.Write("output ");
                OutputLimitClause.ToEPL(writer);
            }

            if (OrderByClause != null)
            {
                formatter.BeginOrderBy(writer);
                writer.Write("order by ");
                OrderByClause.ToEPL(writer);
            }

            if (RowLimitClause != null)
            {
                formatter.BeginLimit(writer);
                writer.Write("limit ");
                RowLimitClause.ToEPL(writer);
            }

            if (ForClause != null)
            {
                formatter.BeginFor(writer);
                ForClause.ToEPL(writer);
            }
        }
Exemplo n.º 59
0
        private void TryScheduleJob(
            JobStorage storage,
            IStorageConnection connection,
            string recurringJobId,
            IReadOnlyDictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var cronSchedule  = CrontabSchedule.Parse(cron);

            try
            {
                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                    ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"])
                    : TimeZoneInfo.Utc;

                var nowInstant    = _instantFactory(cronSchedule, timeZone);
                var changedFields = new Dictionary <string, string>();

                var lastInstant = GetLastInstant(recurringJob, nowInstant);

                if (nowInstant.GetNextInstants(lastInstant).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"]))
                    {
                        state.Queue = recurringJob["Queue"];
                    }

                    var context = new CreateContext(storage, connection, job, state);
                    context.Parameters["RecurringJobId"] = recurringJobId;

                    var backgroundJob = _factory.Create(context);
                    var jobId         = backgroundJob?.Id;

                    if (String.IsNullOrEmpty(jobId))
                    {
                        Logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled.");
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                // Fixing old recurring jobs that doesn't have the CreatedAt field
                if (!recurringJob.ContainsKey("CreatedAt"))
                {
                    changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                }

                changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null);

                connection.SetRangeInHash(
                    $"recurring-job:{recurringJobId}",
                    changedFields);
            }
#if NETFULL
            catch (TimeZoneNotFoundException ex)
            {
#else
            catch (Exception ex)
            {
                // https://github.com/dotnet/corefx/issues/7552
                if (!ex.GetType().Name.Equals("TimeZoneNotFoundException"))
                {
                    throw;
                }
#endif

                Logger.ErrorException(
                    $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.",
                    ex);
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// Creates the actual instance
        /// </summary>
        /// <param name="context"></param>
        /// <param name="arguments">Constructor arguments</param>
        /// <returns>
        /// Created instance.
        /// </returns>
        /// <remarks>Uses the </remarks>
        protected override object Create(CreateContext context, object[] arguments)
        {
            var type = ConcreteType.MakeGenericType(context.RequestedService.GetGenericArguments());

            return(Activator.CreateInstance(type, arguments));
        }