Exemplo n.º 1
0
        private void HandleContextMenuInvoked(object sender, MouseEventArgs e)
        {
            if (!IsHandleCreated || !Visible)
            {
                return;
            }

            if (_jetListView.IsColumnHeaderAt(e.X, e.Y))
            {
                if (_headerContextMenu != null)
                {
                    _headerContextMenu.Show(this, new Point(e.X, e.Y));
                }
            }
            else if (_showContextMenu)
            {
                IActionContext actionContext = _contextProvider.GetContext(ActionContextKind.ContextMenu);
                if (_jetListView.GetNodeAt(e.X, e.Y) == null)
                {
                    ActionContext context = actionContext as ActionContext;
                    if (context != null)
                    {
                        context.SetSelectedResources(Core.ResourceStore.EmptyResourceList);
                    }
                }
                Core.ActionManager.ShowResourceContextMenu(actionContext,
                                                           this, e.X, e.Y);
            }
        }
        private static void RunTest(IContextProvider contextProvider)
        {
            List <Contact> contacts = new List <Contact>();

            var ctx = contextProvider.GetContext();

            contacts = ctx.Contacts.ToList();

            foreach (var contact in contacts.Take(2000))
            {
                ctx = contextProvider.GetContext();

                // get a copy of the contact - either new or cached depending on our context provider
                var localContact = ctx.Contacts.Single(c => c.ContactId == contact.ContactId);
                // create a new account
                Account acc = new Account()
                {
                    Name = contact.Name
                };
                // link contact and account
                localContact.Account = acc;
                // save changes
                ctx.SaveChanges();
            }
        }
        /// <summary>
        /// Deserializes the NQuads into a typed model
        /// </summary>
        /// <typeparam name="T">destination entity model type</typeparam>
        /// <param name="nQuads">RDF data in NQuads.</param>
        public T Deserialize <T>(string nQuads)
        {
            var jsonLdObject  = JsonLdProcessor.FromRDF(nQuads);
            var jsonLdContext = _contextProvider.GetContext(typeof(T));

            if (jsonLdContext == null)
            {
                throw new ContextNotFoundException(typeof(T));
            }

            return(JsonLdProcessor.Compact(jsonLdObject, jsonLdContext, new JsonLdOptions()).ToObject <T>(_jsonSerializer));
        }
Exemplo n.º 4
0
        public void Update(IContextProvider contextProvider)
        {
            ContextProvider = contextProvider;
            var parameter = ContextProvider.GetContext();

            Update(parameter);
        }
Exemplo n.º 5
0
 public void GenerateFakeUsers()
 {
     using (var context = _provider.GetContext <UserModel>())
     {
         context.AddManyAsync(GetUsers());
     }
 }
        /// <summary>
        /// Registers the Disqus client resources to be rendered in defined areas.
        /// </summary>
        /// <param name="requiredResources">The required resources.</param>
        public void RegisterResources(IRequiredClientResourceList requiredResources)
        {
            var renderingContext = _contextProvider.GetContext();

            if (!renderingContext.IsInPreviewMode && !renderingContext.IsInEditMode)
            {
                return;
            }

            if (renderingContext.IsInEditMode)
            {
                requiredResources.Require("duk-disqus.EditMode");

                // Hack: output text in Edit mode to indicate thread placeholders that were not used by Disqus.
                // For example, it can be a case when there are several placeholders on a page.
                // We have to inject inline CSS here to be able to provide localized message text.
                var inlineStyle = string.Format(CultureInfo.InvariantCulture, "div#disqus_thread:empty:before {{content: '{0}';}}",
                                                _localizationService.GetString("/disqus/ui/rendering/severalthreadsonpage"));

                requiredResources.RequireStyleInline(inlineStyle, "duk-disqus.EditMode.severalThreadsIndicator", null);
            }

            // Inject the following styles for Edit and Preview modes
            requiredResources.Require("duk-disqus.PreviewMode");

            var httpContext = HttpContext.Current;

            if (httpContext != null)
            {
                httpContext.Items[ResourcesAreRegisteredKey] = true;
            }
        }
        public async Task <IActionResult> List([FromRoute] string dbId)
        {
            var dbContext = _contextProvider.GetContext(dbId);
            var list      = await dbContext.Table.ToListAsync();

            return(Ok(list));
        }
Exemplo n.º 8
0
        public void Process(IContextProvider contextProvider)
        {
            var context = contextProvider.GetContext();

            if (Time.time >= _nextUpdateTime)
            {
                _nextUpdateTime = Time.time + brain.settings.updateInterval;

                if (AIDebuggingHook.currentDebuggedContextProvider == contextProvider)
                {
                    AIDebuggingHook.debugger = AIDebuggingHook.currentDebugger;
                    AIDebuggingHook.debugger.FrameReset();
                }

                var bestQualifier = _brain.root.Select(context);

                AIDebuggingHook.debugger = null;

                if (_currentAction != null && (bestQualifier == null || bestQualifier.action != _currentAction))
                {
                    _currentAction.Stop(context);
                }

                if (bestQualifier != null)
                {
                    _currentAction = bestQualifier.action;
                }
            }

            if (_currentAction != null)
            {
                _currentAction.Execute(context);
            }
        }
Exemplo n.º 9
0
        public void Deserializing_quads_should_throw_when_context_isnt_found()
        {
            // given
            A.CallTo(() => _provider.GetContext(typeof(Person))).Returns(null);

            // when
            _serializer.Deserialize <Person>(string.Empty);
        }
Exemplo n.º 10
0
        private IActionContext GetContext()
        {
            if (_contextProvider == null)
            {
                return(new ActionContext(ActionContextKind.Toolbar, null, null));
            }

            return(_contextProvider.GetContext(ActionContextKind.Toolbar));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> GetAll()
        {
            IEnumerable <TstModel> result;

            using (var context = _contextProvider.GetContext <TstModel>())
            {
                result = await context.GetAllAsync();
            }
            return(Ok(result));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Executes the AI. Typically this is called by whatever manager controls the AI execution cycle.
        /// </summary>
        public void Execute()
        {
            IAIContext context = _contextProvider.GetContext(_ai.id);

            var action = _ai.Select(context);

            bool finalActionFound = false;

            while (!finalActionFound)
            {
                //While we could treat all connectors the same, most connectors will not have anything to execute, so this way we save the call to Execute.
                var composite = action as ICompositeAction;
                if (composite == null)
                {
                    var connector = action as IConnectorAction;
                    if (connector == null)
                    {
                        finalActionFound = true;
                    }
                    else
                    {
                        action = connector.Select(context);
                    }
                }
                else
                {
                    //For composites that also connect, we execute the child actions before moving on.
                    //So action is executed and then reassigned to the selected action if one exists.
                    if (composite.isConnector)
                    {
                        action.Execute(context);
                        action = composite.Select(context);
                    }
                    else
                    {
                        finalActionFound = true;
                    }
                }
            }

            if (_activeAction != null && !object.ReferenceEquals(_activeAction, action))
            {
                _activeAction.Terminate(context);
                _activeAction = action as IRequireTermination;
            }
            else if (_activeAction == null)
            {
                _activeAction = action as IRequireTermination;
            }

            if (action != null)
            {
                action.Execute(context);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Provides the action execution context by quering the supplied context provider.
        /// </summary>
        public IActionContext GetContext(ActionContextKind kind)
        {
            // Relay context acquision to the supplied context provider, if specified
            if (_contextprovider != null)
            {
                return(_contextprovider.GetContext(kind));
            }

            // Generate an empty context, if not set
            return(new ActionContext(kind, this, null));
        }
Exemplo n.º 14
0
        public async Task Invoke(HttpContext httpContext)
        {
            Context context = contextProvider.GetContext();

            if (context == null)
            {
                context = new Context();
                contextProvider.SetContext(context);
            }
            await requestDelegate.Invoke(httpContext);
        }
Exemplo n.º 15
0
 private object CreateExecutionContext()
 {
     try
     {
         return(_contextProvider.GetContext());
     }
     catch (Exception e)
     {
         throw new InvalidOperationException($"Context initialization failed: {e.Message}", e);
     }
 }
Exemplo n.º 16
0
 public IActionContext GetContext(ActionContextKind kind)
 {
     if (_lastActivePaneData != null)
     {
         IContextProvider provider = _lastActivePaneData.Pane as IContextProvider;
         if (provider != null)
         {
             return(provider.GetContext(kind));
         }
     }
     return(null);
 }
        public static IServiceContext Create(IContextProvider provider, IServiceProfile profile)
        {
            if (provider.GetContext <ILightweightContext>() != null)
            {
                throw new InvalidOperationException($"Only one instance of '{nameof(ILightweightProfile)}' is allowed.");
            }

            // ReSharper disable once UseNegatedPatternMatching
            // ReSharper disable once SuspiciousTypeConversion.Global
            var lightweightProfile = (ILightweightProfile)profile;

            return(lightweightProfile == null ? null : new LightweightContext(provider, lightweightProfile));
        }
Exemplo n.º 18
0
        private static void Execute(Action cb, TService service, MethodInfo methodInfo, object[] args, TPolicyProvider provider, IContextProvider contextProvider)
        {
            var context = contextProvider.GetContext(typeof(TService), service, methodInfo, args);
            var policy  = provider.GetSyncPolicy(context);

            if (policy == null)
            {
                cb();
                return;
            }

            policy.Execute(ctx => cb(), context);
        }
Exemplo n.º 19
0
 protected override bool HandleContextMenu(JetListViewNode node, int x, int y)
 {
     if (_contextProvider != null)
     {
         IResource      res     = (IResource)node.Data;
         ICustomColumn  col     = GetCustomColumn(res);
         IActionContext context = _contextProvider.GetContext(ActionContextKind.ContextMenu);
         if (col.ShowContextMenu(context, OwnerControl, new Point(x, y)))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 20
0
        private static async Task <object> ExecuteAsync(Func <Task <object> > cb, TService service, MethodInfo methodInfo, object[] args, TPolicyProvider provider, IContextProvider contextProvider)
        {
            var context = contextProvider.GetContext(typeof(TService), service, methodInfo, args);
            var policy  = provider.GetAsyncPolicy(context);

            if (policy == null)
            {
                return(await cb());
            }

            var result = await policy.ExecuteAsync(ctx => cb(), context);

            return(result);
        }
Exemplo n.º 21
0
        private static object Execute(Func <object> cb, TService service, MethodInfo methodInfo, object[] args, TPolicyProvider provider, IContextProvider contextProvider)
        {
            var context = contextProvider.GetContext(typeof(TService), service, methodInfo, args);
            var policy  = provider.GetSyncPolicy(context);

            if (policy == null)
            {
                return(cb());
            }

            var result = policy.Execute(ctx => cb(), context);

            return(result);
        }
Exemplo n.º 22
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult)
            {
                object resultObject = ((ObjectResult)context.Result).Value;
                if (resultObject is BaseResponse)
                {
                    IContextProvider contextProvider = context.HttpContext.RequestServices.GetRequiredService <IContextProvider>();
                    ((BaseResponse)resultObject).Context = contextProvider.GetContext();
                }
            }

            base.OnActionExecuted(context);
        }
Exemplo n.º 23
0
 public void ExecuteAction(IServiceProvider serviceProvider, ref object request, ref BaseResponse response)
 {
     if (serviceProvider == null)
     {
         throw new JMException("ContextNotFound");
     }
     else
     {
         IContextProvider contextProvider = serviceProvider.GetService(typeof(IContextProvider)) as IContextProvider;
         if (contextProvider == null || contextProvider.GetContext() == null)
         {
             throw new JMException("ContextNotFound");
         }
     }
 }
Exemplo n.º 24
0
        public string Post([FromBody] RequestPayload requestMessage)
        {
            try
            {
                contextProvider.SetContext(requestMessage.Context);
                FlowConfiguration configuration = flowConfigurationProvider.GetConfiguration(requestMessage.Action);
                ValidationHelper.ExecuteValidations(configuration, requestMessage.Request);
                BaseResponse    response        = flowProvider.ExecuteFlow(serviceProvider, requestMessage.Action, requestMessage.Request);
                ResponsePayload responseMessage = new ResponsePayload
                {
                    Context  = contextProvider.GetContext(),
                    Response = response
                };

                return(responseMessage.ToJson());
            }
            catch (Exception e)
            {
                try
                {
                    JMResult result  = serviceProvider.GetRequiredService <IExceptionHandler>().HandleException(e);
                    Context  context = contextProvider.GetContext();
                    context.ActiveResult = result;
                    return(new ResponsePayload
                    {
                        Context = context,
                        Response = null
                    }.ToJson());
                }
                catch (Exception innerException)
                {
                    DefaultLogger.Error(innerException);
                    return(new ResponsePayload().ToJson());
                }
            }
        }
Exemplo n.º 25
0
 public async Task <UserModel> GetUserByLoginAsync(string login)
 {
     try
     {
         using (var context = _contextProvider.GetContext <UserModel>())
         {
             return(await context.GetSingleAsync(x => x.UserLogin == login));
         }
     }
     catch (Exception ex)
     {
         //#TODO log
         throw new ArgumentException("User not found");
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Intercept the invocation
        /// </summary>
        /// <param name="invocation"></param>
        public void Intercept(_IInvocation invocation)
        {
            if (!invocation.Method.IsVirtual || invocation.Method.IsFinal)
            {
                invocation.Proceed();
                return;
            }

            var methodExecutingContext = new MethodExecutingContext
            {
                InvocationContext = _contextProvider.GetContext(),
                MethodInfo        = invocation.Method,
                Invocation        = invocation
            };

            var attributes = GetInvocationMethodFilterAttributes(invocation, methodExecutingContext.InvocationContext);

            if (attributes.Any(a => a is NoInterceptAttribute))
            {
                invocation.Proceed();
                return;
            }

            var filterAttributes = attributes.OfType <MethodFilterAttribute>().OrderBy(x => x.Order).ToList();
            var isAsync          = typeof(Task).IsAssignableFrom(invocation.Method.ReturnType);

            if (isAsync)
            {
                if (invocation.Method.ReturnType.IsGenericType && invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    var taskResultType = invocation.Method.ReturnType.GetGenericArguments()[0];
                    var mInfo          = _handleAsyncWithTypeMethod.MakeGenericMethod(taskResultType);
                    filterAttributes.Add(new InvocationAttribute(invocation, taskResultType));
                    invocation.ReturnValue = mInfo.Invoke(this, new object[] { filterAttributes, methodExecutingContext, taskResultType });
                }
                else
                {
                    filterAttributes.Add(new InvocationAttribute(invocation));
                    invocation.ReturnValue = HandleAsync(filterAttributes, methodExecutingContext);
                }
            }
            else
            {
                filterAttributes.Add(new InvocationAttribute(invocation));
                HandleSync(filterAttributes, methodExecutingContext);
            }
        }
Exemplo n.º 27
0
        public BaseResponse ExecuteFlow(IServiceProvider serviceProvider, string actionName, object request)
        {
            FlowConfiguration flowConfiguration = flowConfigurationProvider.GetConfiguration(actionName);

            contextProvider.GetContext().ActiveFlowConfiguration = flowConfiguration;
            Type         responseType = Type.GetType(flowConfiguration.ResponseIdentifier);
            BaseResponse response     = Activator.CreateInstance(responseType) as BaseResponse;

            foreach (FlowItemDefinition flowItem in flowExecutionConfigurationProvider.GetActiveConfiguration().FlowItems)
            {
                Type         flowItemType     = Type.GetType(flowItem.TypeIdentifier);
                BaseFlowItem flowItemInstance = Activator.CreateInstance(flowItemType) as BaseFlowItem;
                flowItemInstance.ExecuteFlow(serviceProvider, ref request, ref response);
            }

            return(response);
        }
Exemplo n.º 28
0
        public IActionContext GetContext(ActionContextKind kind)
        {
            ActionContext context;

            if (_contextProvider != null)
            {
                context = (ActionContext)_contextProvider.GetContext(kind);
            }
            else
            {
                context = new ActionContext(kind, this, null);
                context.SetCommandProcessor(this);
            }

            context.SetSelectedText(SelectedRtf, SelectedText, TextFormat.Rtf);

            return(context);
        }
Exemplo n.º 29
0
        public LoginResponse Post([FromBody] LoginRequest request)
        {
            LoginResponse response = authenticationProvider.Authenticate(request);

            if (response.Result != Entities.UserManagement.LoginResultEnum.Successful)
            {
                throw new JMException(response.Result.ToString());
            }
            else
            {
                //issue token
                response.Token = tokenProvider.IssueToken(request.Username.ToPlainString());
                Context context = contextProvider.GetContext();
                context.User = response.User;
                contextProvider.SetContext(context);
            }

            return(response);
        }
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, [AllowNull] object value, JsonSerializer serializer)
        {
            writer.WriteStartObject();

            var context = _contextProvider.GetContext(value.GetType());

            if (context != null)
            {
                writer.WritePropertyName("@context");
                serializer.Serialize(writer, context);
            }

            var types = GetTypes(value.GetType());

            if (types.Any())
            {
                writer.WritePropertyName("@type");
                writer.WriteStartArray();
                foreach (var type in types)
                {
                    writer.WriteValue(type);
                }

                writer.WriteEndArray();
            }

            var objectContract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());

            foreach (var property in objectContract.Properties)
            {
                var propVal = property.ValueProvider.GetValue(value);
                if (propVal != null)
                {
                    writer.WritePropertyName(property.PropertyName);
                    serializer.Serialize(writer, propVal);
                }
            }

            writer.WriteEndObject();
        }