Exemple #1
0
        public bool TryRequestDecision(string contextJson, ActionFlags flags, DecisionResponse response, ApiStatus apiStatus)
        {
            int result = LiveModelRequestDecisionWithFlags(this.DangerousGetHandle(), contextJson, (uint)flags, response.DangerousGetHandle(), apiStatus.ToNativeHandleOrNullptrDangerous());

            GC.KeepAlive(this);
            return(result == NativeMethods.SuccessStatus);
        }
Exemple #2
0
        public bool TryRequestMultiSlotDecision(string eventId, string contextJson, ActionFlags flags, out MultiSlotResponse response, ApiStatus apiStatus)
        {
            response = new MultiSlotResponse();

            GC.KeepAlive(this);
            return(this.TryRequestMultiSlotDecision(eventId, contextJson, flags, response, apiStatus));
        }
Exemple #3
0
        public Response <PersonalizerMultiSlotRankResult> Rank(PersonalizerRankMultiSlotOptions options)
        {
            string eventId = options.EventId;

            if (String.IsNullOrEmpty(eventId))
            {
                eventId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            }

            Dictionary <string, int>             actionIdToActionIndex = RlObjectConverter.GetActionIdToIndexMapping(options.Actions);
            Dictionary <string, IList <object> > slotIdToFeatures      = new Dictionary <string, IList <object> >();

            foreach (var slot in options.Slots)
            {
                slotIdToFeatures.Add(slot.Id, RlObjectConverter.GetIncludedActionsForSlot(slot, actionIdToActionIndex));
            }

            // Convert options to the compatible parameter for ChooseRank
            DecisionContext decisionContext = new DecisionContext(options, slotIdToFeatures);
            var             contextJson     = JsonSerializer.Serialize(decisionContext);
            ActionFlags     flags           = options.DeferActivation == true ? ActionFlags.Deferred : ActionFlags.Default;

            int[] baselineActions = RlObjectConverter.ExtractBaselineActionsFromRankRequest(options);

            // Call ChooseRank of local RL.Net
            MultiSlotResponseDetailedWrapper multiSlotResponseDetailedWrapper = liveModel.RequestMultiSlotDecisionDetailed(eventId, contextJson, flags, baselineActions);

            // Convert response to PersonalizerRankResult
            var value = RlObjectConverter.GenerateMultiSlotRankResponse(options.Actions, multiSlotResponseDetailedWrapper, eventId);

            return(Response.FromValue(value, default));
        }
Exemple #4
0
        public bool TryChooseRank(string eventId, string contextJson, ActionFlags flags, RankingResponse response, ApiStatus apiStatus = null)
        {
            int result = LiveModelChooseRankWithFlags(this.DangerousGetHandle(), eventId, contextJson, (uint)flags, response.DangerousGetHandle(), apiStatus.ToNativeHandleOrNullptrDangerous());

            GC.KeepAlive(this);
            return(result == NativeMethods.SuccessStatus);
        }
        /// <summary>
        /// Verifies passed arguments
        /// </summary>
        /// <param name="Args">sArguments passed to program</param>
        /// <param name="Flags"><see cref="ActionFlags"/> used for factoring <see cref="IRepresenter"/> object</param>
        /// <returns><see cref="VerifyResult"/>.Success if passed arguments are valid and <see cref="VerifyResult"/>.Fail otherwise</returns>
        public virtual VerifyResult Verify(string[] Args, out ActionFlags Flags)
        {
            VerifyResult a = VerifyFilePath(Args);
            VerifyResult b = VerifyFlags(Args, out Flags);

            return(a == VerifyResult.Success ? b : a);
        }
        public static ActionRec Create(float factor, ActionFlags flags)
        {
            ActionRec result = new ActionRec();

            result.Factor = factor;
            result.Flags  = flags;
            return(result);
        }
Exemple #7
0
        public static Type GetActionValidatorType(ActionFlags value)
        {
            var type = value.GetType();
            var name = Enum.GetName(type, value);
            var objs = (ActionValidatorAttribute[])type.GetField(name).GetCustomAttributes(typeof(ActionValidatorAttribute), false);

            return(objs[0].ValidatorType);
        }
Exemple #8
0
 public CE_USER_NOTIFICATION(string title, string text)
 {
     actionFlags     = ActionFlags.PUN_DIALOG;
     pwszDialogTitle = new SmartString(title);
     pwszDialogText  = new SmartString(text);
     pwszSound       = new SmartString(null);
     dwMaxSound      = 0;
     dwReserved      = 0;
 }
        /// <summary>
        /// Action Name Attribute constructor
        /// </summary>
        /// <param name="name">Name</param>
        /// <param name="action">Action</param>
        public ActionNameAttribute(string name, ActionFlags action = ActionFlags.Load)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("name parameter is invalid");
            }

            this.name = name;
            this.action = action;
        }
Exemple #10
0
        /// <summary>
        /// Action Name Attribute constructor
        /// </summary>
        /// <param name="action">Action</param>
        /// <param name="name">Name</param>
        public ActionNameAttribute(ActionFlags action, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("name parameter is invalid");
            }

            this.action = action;
            this.name   = name;
        }
Exemple #11
0
        /// <summary>
        /// Load Object from Data Set
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="ds">Data Set</param>
        /// <param name="action">Action</param>
        /// <returns>Objects</returns>
        public static IList <T> LoadObjects <T>(this DataSet ds, ActionFlags action = ActionFlags.Load)
            where T : new()
        {
            var values = new List <T>();

            foreach (DataTable table in ds.Tables)
            {
                values.AddRange(table.LoadObjects <T>(action));
            }

            return(values);
        }
        public RankingResponse ChooseRank(string eventId, string contextJson, ActionFlags flags)
        {
            RankingResponse result = new RankingResponse();

            using (ApiStatus apiStatus = new ApiStatus())
                if (!this.TryChooseRank(eventId, contextJson, flags, result, apiStatus))
                {
                    throw new RLException(apiStatus);
                }

            return(result);
        }
        public DecisionResponse RequestDecision(string contextJson, ActionFlags flags)
        {
            DecisionResponse result = new DecisionResponse();

            using (ApiStatus apiStatus = new ApiStatus())
                if (!this.TryRequestDecision(contextJson, flags, result, apiStatus))
                {
                    throw new RLException(apiStatus);
                }

            return(result);
        }
Exemple #14
0
        private static IActionValidator GetValidator(ActionFlags flag)
        {
            if (validators.ContainsKey(flag))
            {
                return(validators[flag]);
            }

            Type             t         = ActionValidatorAttribute.GetActionValidatorType(flag);
            IActionValidator validator = (IActionValidator)Activator.CreateInstance(t);

            validators.Add(flag, validator);

            return(validator);
        }
        protected override void AuditEntry(ActionFlags flag, object entity, string name)
        {
            if (string.IsNullOrWhiteSpace(CurrentUserId))
            {
                return;
            }

            var instance = (IAuditTrailEntry)Activator.CreateInstance <AuditTrailMock>();

            instance.TableName   = name;
            instance.DateCreated = DateTime.UtcNow;
            instance.Action      = (int)flag;
            instance.UserId      = CurrentUserId;
            instance.JsonBody    = Json.SerializeExcluding(entity, false, "Image");

            Context.Entry(instance).State = EntityState.Added;
        }
Exemple #16
0
        public Response <PersonalizerRankResult> Rank(PersonalizerRankOptions options)
        {
            string eventId = options.EventId;

            if (String.IsNullOrEmpty(eventId))
            {
                eventId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            }

            HashSet <string> excludedSet = new HashSet <string>(options.ExcludedActions);

            // Store the original action list
            List <PersonalizerRankableAction> originalActions = new List <PersonalizerRankableAction>();
            List <PersonalizerRankableAction> rankableActions = new List <PersonalizerRankableAction>();
            List <PersonalizerRankableAction> excludedActions = new List <PersonalizerRankableAction>();
            int idx = 0;

            foreach (var action in options.Actions)
            {
                PersonalizerRankableAction actionCopy = new PersonalizerRankableAction(action.Id, action.Features);
                actionCopy.Index = idx;
                originalActions.Add(actionCopy);
                if (excludedSet.Contains(actionCopy.Id))
                {
                    excludedActions.Add(actionCopy);
                }
                else
                {
                    rankableActions.Add(actionCopy);
                }
                ++idx;
            }

            // Convert options to the compatible parameter for ChooseRank
            var         contextJson = RlObjectConverter.ConvertToContextJson(options.ContextFeatures, rankableActions);
            ActionFlags flags       = options.DeferActivation == true ? ActionFlags.Deferred : ActionFlags.Default;

            // Call ChooseRank of local RL.Net
            RankingResponseWrapper rankingResponseWrapper = liveModel.ChooseRank(eventId, contextJson, flags);

            // Convert response to PersonalizerRankResult
            var value = RlObjectConverter.GenerateRankResult(originalActions, rankableActions, excludedActions, rankingResponseWrapper, options.EventId);

            return(Response.FromValue(value, default));
        }
Exemple #17
0
        private void AuditEntry(ActionFlags flag, object entity, string name)
        {
            if (string.IsNullOrWhiteSpace(_currentUserId))
            {
                return;
            }

            var instance = (IAuditTrailEntry)Activator.CreateInstance <TEntity>();

            instance.TableName   = name;
            instance.DateCreated = DateTime.UtcNow;
            instance.Action      = (int)flag;
            instance.UserId      = _currentUserId;

            // TODO: Why the legacy doesn't save the body at delete method
            instance.JsonBody = Json.Serialize(entity);

            Context.Entry(instance).State = EntityState.Added;
        }
Exemple #18
0
        /// <summary>
        /// Load Object from Data Table
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="table">Data Table</param>
        /// <param name="action">Action</param>
        /// <returns>Object</returns>
        public static T LoadObject <T>(this DataTable table, ActionFlags action = ActionFlags.Load)
            where T : new()
        {
            var  type  = typeof(T);
            T    value = Activator.CreateInstance <T>();
            Type createType;
            var  isEnumerable = type.IsGenericType && value is IEnumerable;

            if (isEnumerable)
            {
                createType = type.GetGenericArguments()[0];
            }
            else
            {
                value      = default(T);
                createType = type;
            }

            var list    = value as IList;
            var columns = table.Columns.ToArray();

            foreach (DataRow row in table.Rows)
            {
                var instance = Activator.CreateInstance(createType);

                instance.Fill(columns, row.ItemArray, action);

                if (isEnumerable)
                {
                    if (null != list)
                    {
                        list.Add(instance);
                    }
                }
                else
                {
                    return((T)instance);
                }
            }

            return(value);
        }
        /// <summary>
        /// Adds types to action
        /// </summary>
        /// <param name="action"></param>
        /// <param name="types"></param>
        public void AddTypes(ActionFlags action, Type[] types)
        {
            switch (action)
            {
            case ActionFlags.None:
                break;

            case ActionFlags.Create:
                _validCreateTypes.AddRange(types);
                break;

            case ActionFlags.Update:
                _validUpdateTypes.AddRange(types);
                break;

            case ActionFlags.Delete:
                _validDeleteTypes.AddRange(types);
                break;
            }
        }
        /// <summary>
        /// Wraps a <see cref="Representer"/> in the correct order into needed <see cref="IWrapper{IRepresenter}"/>, depending on passed <paramref name="Flags"/>
        /// </summary>
        /// <param name="Flags"><see cref="ActionFlags"/> value, that defines wrapping process</param>
        /// <returns>Custom <see cref="IRepresenter"/>, that was created corresponding to passed <paramref name="Flags"/> value</returns>
        public static IRepresenter GetRepresenter(ActionFlags Flags)
        {
            Flags = Flags & ~ActionFlags.Unrestrict;
            IRepresenter result = new Representer();

            if (Flags == (ActionFlags.Sheets | ActionFlags.Keys))
            {
                return(new KeyRepresenter(new LoneSheetRepresenter(new Representer())));
            }
            if (Flags == (ActionFlags.Sheets | ActionFlags.Count))
            {
                return(new LoneSheetRepresenter(new CountRepresenter(new Representer())));
            }
            if (Flags == (ActionFlags.Sheets | ActionFlags.Keys | ActionFlags.Count))
            {
                return(new KeyRepresenter(new LoneSheetRepresenter(new CountRepresenter(new Representer()))));
            }

            if ((Flags & ActionFlags.Names) > 0)
            {
                result = new CellNameRepresenter(result);
            }

            if ((Flags & ActionFlags.Count) > 0)
            {
                result = new CountRepresenter(result);
            }

            if ((Flags & ActionFlags.Sheets) > 0)
            {
                result = new SheetRepresenter(result);
            }

            if ((Flags & ActionFlags.Keys) > 0)
            {
                result = new KeyRepresenter(result);
            }

            return(result);
        }
        /// <summary>
        /// Executes the business rules methods via reflection and method invocation.
        /// </summary>
        /// <param name="state">The state.</param>
        /// <param name="action">The action.</param>
        private async Task ExecuteBusinessRulesMethods(EntityState state, ActionFlags action)
        {
            var selfTrackingEntries = Context.ChangeTracker.Entries()
                                      .Where(x => x.State == state)
                                      .Select(x => x.Entity)
                                      .Where(x => x != null);

            foreach (var entity in selfTrackingEntries)
            {
                var entityType = entity.GetType();

                if (entityType.BaseType != null && entityType.Namespace == DynamicProxiesNamespace)
                {
                    entityType = entityType.BaseType;
                }

                var methods = _methodInfoSet.Where(m => m.GetCustomAttributes(typeof(BusinessRuleAttribute), true)
                                                   .Select(a => a as BusinessRuleAttribute)
                                                   .Where(a => a != null)
                                                   .Any(
                                                       b => (b.EntityTypes == null ||
                                                             b.EntityTypes.Any(
                                                                 t => t == entityType)) &&
                                                       (b.Action & action) == action));

                foreach (var methodInfo in methods)
                {
                    if (methodInfo.ReturnType == typeof(Task))
                    {
                        await(Task) methodInfo.Invoke(this, new[] { entity });
                    }
                    else
                    {
                        methodInfo.Invoke(this, new[] { entity });
                    }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Adds the types.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="types">The types.</param>
        public void AddTypes(ActionFlags action, Type[] types)
        {
            switch (action)
            {
            case ActionFlags.None:
                break;

            case ActionFlags.Create:
                _validCreateTypes.AddRange(types);
                break;

            case ActionFlags.Update:
                _validUpdateTypes.AddRange(types);
                break;

            case ActionFlags.Delete:
                _validDeleteTypes.AddRange(types);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(action), action, null);
            }
        }
Exemple #23
0
        public virtual JsonResult InsertUpdate([FromBody] T formData)
        {
            ActionFlags      action  = formData.Flag;
            ExceptionMessage message = new ExceptionMessage("Enter GridController.InsertUpdateDetails");

            if (NotValidIdentity())
            {
                SessionExpired(message);
            }
            else
            {
                try
                {
                    if (action == ActionFlags.Add)
                    {
                        InternalUpdateNewDetails(formData, message);
                    }
                    else
                    {
                        T workingItem = new T();
                        workingItem = InternalUpdateExistingDetails(formData, message);
                    }
                    if (message.Status)
                    {
                        if (message.UserMessages.Count == 0)
                        {
                            message.LastUserMessage = action == ActionFlags.Add ? Messages.RecordCreatedSuccessfully : action == ActionFlags.Update ? Messages.RecordUpdatedSuccessfully : Messages.InsertUpdateCompleted;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogBaseControllerMessage(ex, message);
                }
            }
            return(Json(message));
        }
        private void AuditEntry(ActionFlags flag, object entity, string name)
        {
            if (string.IsNullOrWhiteSpace(_currentUserId))
            {
                return;
            }

            var entityState =
                ((IObjectContextAdapter)Context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);

            var instance = (IAuditTrailEntry)Activator.CreateInstance <TEntity>();

            instance.TableName   = name;
            instance.DateCreated = DateTime.UtcNow;
            instance.Action      = (int)flag;
            instance.UserId      = _currentUserId;

            if (flag != ActionFlags.Delete)
            {
                instance.JsonBody = JsonConvert.SerializeObject(ToDictionary(entityState.CurrentValues));
            }

            Context.Entry(instance).State = EntityState.Added;
        }
Exemple #25
0
        private void ExecuteBusinessRulesMethods(EntityState state, ActionFlags action)
        {
            var selfTrackingEntries = Context.ChangeTracker.Entries()
                                      .Where(x => x.State == state)
                                      .Select(x => x.Entity)
                                      .ToList();

            foreach (var entity in selfTrackingEntries)
            {
                var entityType = entity.GetType();

                var methods = _methodInfoSet
                              .Where(m => m.GetCustomAttributes(typeof(BusinessRuleAttribute), true)
                                     .Select(a => a as BusinessRuleAttribute)
                                     .Any(b => b != null && (b.EntityTypes == null ||
                                                             b.EntityTypes.Any(t => t == entityType)) &&
                                          (b.Action & action) == action));

                foreach (var methodInfo in methods)
                {
                    methodInfo.Invoke(this, new[] { entity });
                }
            }
        }
 public CE_USER_NOTIFICATION( string title, string text )
 {
     actionFlags = ActionFlags.PUN_DIALOG;
     pwszDialogTitle = new SmartString( title );
     pwszDialogText = new SmartString( text );
     pwszSound = new SmartString( null );
     dwMaxSound = 0;
     dwReserved = 0;
 }
        private ISuccessOrErrors <TDto> validateDtoState <TDto>(ISuccessOrErrors <TDto> status, TDto dto, ActionFlags flags)
            where TDto : DtoBase <TContext, TEntity, TDto>, new()
        {
            var currentItem = dto.FindItemTrackedForUpdate(dbContext);

            if (!new TDto().AllowedActions.HasFlag(ActionFlags.Update) && currentItem != null)
            {
                return(status.AddSingleError("Dto is not allowed for this kind of action"));
            }
            if (!new TDto().AllowedActions.HasFlag(ActionFlags.Create) && currentItem == null)
            {
                return(status.AddSingleError("Dto is not allowed for this kind of action"));
            }
            if (!flags.HasFlag(ActionFlags.Update) && currentItem != null)
            {
                return(status.AddSingleError("Object already exists"));
            }
            if (!flags.HasFlag(ActionFlags.Create) && currentItem == null)
            {
                return(status.AddSingleError("Object doesn't exist"));
            }

            return(status);
        }
        public async Task <ISuccessOrErrors <TDto> > CreateOrUpdateAsync <TDto>(TDto dto, ActionFlags actions)
            where TDto : DtoBase <TContext, TEntity, TDto>, new()
        {
            var status = SuccessOrErrors <TDto> .SuccessWithResult(null, "Success");

            status = validateDtoState(status, dto, actions);
            if (status.IsValid)
            {
                var entity = DTORepositoryContainer.Mapper.Map <TEntity>(dto, opts =>
                {
                    opts.Items["DbContext"]     = dbContext;
                    opts.Items["CurrentStatus"] = status;
                    opts.Items["ActionFlags"]   = actions;
                });
                if (status.IsValid)
                {
                    await dbContext.SaveChangesAsync();

                    DTORepositoryContainer.Mapper.Map <TEntity, TDto>(entity, dto, opts => {
                        opts.Items["ActionFlags"] = actions;
                        opts.Items["DbContext"]   = dbContext;
                    });
                    return(status.SetSuccessWithResult(dto, "Success"));
                }
            }
            return(status);
        }
 private void Init()
 {
     // initialize permissions from cached UserPermissions (test purposes only)...
     // NOTE, this must occur *BEFORE* any Controller actions.
     Context.Cache["UserPermissions"] = Context.Cache["UserPermissions"] ?? new UserPermissions();
     var up = (UserPermissions)Context.Cache["UserPermissions"];
     var af = new ActionFlags();
     af = up.PermitCreate ? af | ActionFlags.Create : af;
     af = up.PermitRead ? af | ActionFlags.Read : af;
     af = up.PermitUpdate ? af | ActionFlags.Update : af;
     af = up.PermitDelete ? af | ActionFlags.Delete : af;
     Allow(Controller, af);
 }
 /// <summary>
 /// Initializes an instance of a class dervied from DocumentAction.
 /// </summary>
 /// <param name="documentWorkspace">The DocumentWorkspace to interact with.</param>
 /// <param name="actionFlags">Flags that describe action behavior or requirements.</param>
 public DocumentWorkspaceAction(ActionFlags actionFlags)
 {
     this.actionFlags = actionFlags;
     SystemLayer.Tracing.LogFeature("DWAction(" + GetType().Name + ")");
 }
 /// <summary>
 /// Initializes an instance of a class dervied from DocumentAction.
 /// </summary>
 /// <param name="documentWorkspace">The DocumentWorkspace to interact with.</param>
 /// <param name="actionFlags">Flags that describe action behavior or requirements.</param>
 public DocumentWorkspaceAction(ActionFlags actionFlags)
 {
     this.actionFlags = actionFlags;
 }
 /// <summary>
 /// The type of XML execution plan that is contained with in a result set
 /// </summary>
 public SpecialAction()
 {
     flags = ActionFlags.None;
 }
 public bool TestButton(ActionFlags button)
 {
     return FlagsHelper.TestFlag(m_buttonFlags, button);
 }
 /// <summary>
 /// Specifies the types and actions that a method handles as a business rule
 /// </summary>
 /// <param name="entityType">Type of the entity.</param>
 /// <param name="actionFlags">The action flags the method can handle..</param>
 public BusinessRuleAttribute(Type entityType, ActionFlags actionFlags)
     : this(new[] { entityType }, actionFlags)
 {
 }
 /// <summary>
 /// Specifies the types and actions that a method handles as a business rule
 /// </summary>
 /// <param name="entityTypes">The entity types the method can handle.</param>
 /// <param name="actionFlags">The action flags the method can handle.</param>
 public BusinessRuleAttribute(Type[] entityTypes, ActionFlags actionFlags)
 {
     this.EntityTypes = entityTypes;
     this.Action = actionFlags;
 }
 public void RemoveButton(ActionFlags remButton)
 {
     FlagsHelper.UnsetFlag(ref m_buttonFlags, remButton);
 }
 /// <summary>
 /// Aggregate this special action with the input
 /// </summary>
 public void CombineSpecialAction(SpecialAction action)
 {
     flags |= ((action?.flags) ?? ActionFlags.None);
 }
 public void AddButton(ActionFlags newButton)
 {
     FlagsHelper.SetFlag(ref m_buttonFlags, newButton);
 }
 public ActionRec(float factor, ActionFlags flags)
 {
     Factor = factor;
     Flags  = flags;
 }
 public MovementCommand()
 {
     m_buttonFlags = ActionFlags.None;
     m_frontAxis = m_lateralAxis = 0;
 }
 public bool TryChooseRank(string eventId, string contextJson, ActionFlags flags, out RankingResponse response, ApiStatus apiStatus = null)
 {
     response = new RankingResponse();
     return(this.TryChooseRank(eventId, contextJson, flags, response, apiStatus));
 }
 public HistoryFunction(ActionFlags actionFlags)
 {
     this.actionFlags = actionFlags;
 }
 /// <summary>
 /// Specifies the types and actions that a method handles as a business rule
 /// </summary>
 /// <param name="actionFlags">The action flags the method can handle.</param>
 public BusinessRuleAttribute(ActionFlags actionFlags)
 {
     this.Action = actionFlags;
 }
 // sets all flags at once:
 public void Allow(string controller, ActionFlags af)
 {
     Actions[controller] = af;
 }