예제 #1
0
 private void PublishModelEvent(TModel model, ModelAction action)
 {
     if (PublishModelEvents)
     {
         _eventAggregator.PublishEvent(new ModelEvent <TModel>(model, action));
     }
 }
예제 #2
0
        /// <summary>
        /// Oks the specified event action.
        /// </summary>
        /// <param name="eventAction">The event action.</param>
        /// <param name="eventStatus">The event status.</param>
        /// <param name="data">The data.</param>
        /// <param name="msg">The MSG.</param>
        /// <returns></returns>
        protected IHttpActionResult Ok(ModelAction eventAction, EventStatus eventStatus, object data = null, string msg = null)
        {
            var action = eventAction.GetDescription().ToLower();

            if (string.IsNullOrEmpty(msg))
            {
                switch (eventStatus)
                {
                case EventStatus.Success:
                    msg = String.Format("{0} {1} com sucesso", string.Format("{0}(s)", Module.GetDescription()), action);
                    break;

                case EventStatus.Failure:
                    msg = String.Format("Um erro ocorreu. {0} não pode ser {1}", Module.GetDescription(), action);
                    break;

                case EventStatus.Pending:
                    msg = String.Format("{0} ação {1} está pendente no momento", action, Module.GetDescription());
                    break;

                case EventStatus.NoAction:
                    msg = String.Format("{0} está atualizado(a). Nenhuma ação foi realizada", Module.GetDescription());
                    break;
                }
            }
            var content = data == null ? (object)new { Message = msg } : new { Message = msg, Data = data };

            return(Ok(content));
        }
예제 #3
0
        /**
         * Constructs an ExecutionAction that knows how to run a ModelAction.
         *
         * @param modelTask
         *            the ModelAction to run.
         * @param executor
         *            the BTExecutor that will manage this ExecutionAction.
         * @param parent
         *            the parent ExecutionTask of this task.
         */

        protected ExecutionAction(ModelAction modelTask, BTExecutor executor, ExecutionTask parent)
            : base(modelTask, executor, parent)
        {
            if (modelTask == null)
            {
                throw new ArgumentException("The ModelTask must not be null");
            }
        }
 public ModelPermissionAttribute(
     HttpRequestMethod requestMethod,
     ModelAction modelAction,
     Type AccessChainResolver)
 {
     this.RequestMethod       = requestMethod;
     this.ModelAction         = modelAction;
     this.AccessChainResolver = AccessChainResolver;
 }
예제 #5
0
        public ResourceChangeMessage(ModelAction action)
        {
            if (action != ModelAction.Deleted || action != ModelAction.Sync)
            {
                throw new InvalidOperationException("Resource message without a resource needs to have Delete or Sync as action");
            }

            Action = action;
        }
예제 #6
0
        protected void BroadcastResourceChange(ModelAction action)
        {
            var signalRMessage = new SignalRMessage
            {
                Name = Resource,
                Body = new ResourceChangeMessage <TResource>(action)
            };

            _commandExecutor.PublishCommand(new BroadcastSignalRMessage(signalRMessage));
        }
 public dynamic Validate(
     DbContext dbContext,
     string requesterID,
     IRequest request,
     object modelItself,
     string typeName,
     object typeValue,
     ModelAction modelAction,
     HttpRequestMethod requestMethod,
     Object relationType) => true;
        protected void BroadcastResourceChange(ModelAction action)
        {
            var signalRMessage = new SignalRMessage
            {
                Name = Resource,
                Body = new ResourceChangeMessage <TResource>(action)
            };

            _signalRBroadcaster.BroadcastMessage(signalRMessage);
        }
예제 #9
0
 public void Deserialize()
 {
     // Check deserialization of actions.
     foreach (Tuple <ModelAction, string> tuple in actions)
     {
         ModelAction action = ModelAction.Deserialize(tuple.Item2);
         Console.WriteLine(action);
         Assert.AreEqual(tuple.Item1, action);
     }
 }
예제 #10
0
        public dynamic GeneralAccessChainValidation(
            IRequest Request,
            MemberInfo Type,
            ModelAction ModelAction,
            HttpRequestMethod RequestMethod,
            TRelation RelationType,
            object ModelItself,
            object TypeValue   = null,
            bool DefaultPolicy = false)
        {
            var typeName         = Type.GetType().GetProperty("Name").GetValue(Type) as string;
            var modelPermissions = Type.GetCustomAttributes <ModelPermissionAttribute> ();

            var requirements = modelPermissions
                               .AsParallel()
                               .Where(requirement =>
                                      requirement.ModelAction == ModelAction &&
                                      requirement.RequestMethod == RequestMethod)
                               .ToList();

            if (requirements != null && requirements.Count > 0)
            {
                foreach (var requirement in requirements)
                {
                    var validation = APIUtils.InvokeMethod(
                        requirement.AccessChainResolver,
                        "Validate",
                        new object[] {
                        DbContext,
                        RequesterID,
                        Request,
                        ModelItself,
                        typeName,
                        TypeValue,
                        ModelAction,
                        RequestMethod,
                        RelationType
                    });

                    if (!(validation is bool && (bool)validation))
                    {
                        return("Requirement validation with name { " + requirement.AccessChainResolver.Name +
                               " } has been failed with result { " + validation + " }");
                    }
                }
            }
            else if (DefaultPolicy == false)
            {
                return("Requested action { " + ModelAction + " } is not valid for request method { " +
                       RequestMethod + " }, or this action is not valid for this type { " +
                       typeName + " } at all");
            }

            return(true);
        }
 public DependentValueAttribute(
     HttpRequestMethod RequestMethod,
     ModelAction ModelAction,
     Type Resolver,
     string DependentOn = null)
 {
     this.RequestMethod = RequestMethod;
     this.ModelAction   = ModelAction;
     this.Resolver      = Resolver;
     this.DependentOn   = DependentOn;
 }
예제 #12
0
        public static void OpenNewDialogWindow(object viewModel, ModelAction action)
        {
            var    viewType = _windows[new Tuple <Type, ModelAction>(viewModel.GetType(), action)];
            Window newWindow;

            newWindow = Activator.CreateInstance(viewType) as Window;
            if (viewModel.GetType() == typeof(ContactVM))
            {
                ((ContactVM)viewModel).CancelCommand = new DelegateCommand(newWindow.Close);
            }
            newWindow.DataContext = viewModel;

            newWindow.ShowDialog();
        }
예제 #13
0
    private void _Dispatch(ModelAction _action)
    {
        // обходим dobj нашего акшона, проверяем есть ли в модели узлы, соответствующие текущим поддеревьям
        // нужна проверка в каждом поддереве что хешсуммы dodj совпадают, оптимизация короч

        // тут и a_Data должен быть null
        if (a_Root == null)
        {
        }
        else
        {
            Merge(a_Data, _action.Data, a_Root);
        }
    }
예제 #14
0
 public IActionResult Handle(
     string resourceName,
     ModelAction requestedAction,
     long extra) =>
 Handle(new IRequest {
     ResourceName    = resourceName,
     IdentifierName  = null,
     IdentifierValue = null,
     ExtraCode       = extra
 },
        requestedAction,
        default(TRelation),
        null,
        new StreamReader(Request.Body, Encoding.UTF8).ReadToEnd());
예제 #15
0
 public dynamic ModelPropertyValidation(
     IRequest Request,
     PropertyInfo PropertyInfo,
     object Model,
     ModelAction ModelAction,
     HttpRequestMethod RequestMethod) =>
 GeneralAccessChainValidation(
     Request: Request,
     Type: PropertyInfo,
     ModelAction: ModelAction,
     RequestMethod: RequestMethod,
     RelationType: default(TRelation),
     TypeValue: PropertyInfo.GetValue(Model),
     ModelItself: Model,
     DefaultPolicy: true);
예제 #16
0
 public dynamic ModelValidation(
     IRequest Request,
     Type ModelType,
     ModelAction ModelAction,
     HttpRequestMethod RequestMethod,
     TRelation RelationType) =>
 GeneralAccessChainValidation(
     Request: Request,
     Type: ModelType,
     ModelAction: ModelAction,
     RequestMethod: RequestMethod,
     RelationType: RelationType,
     ModelItself: null,
     TypeValue: Request.IdentifierValue,
     DefaultPolicy: false);
예제 #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(Request["pageNum"]))
        {
            pageNum = int.Parse(Request["pageNum"]);
        }
        string path         = Request.ApplicationPath;
        string absolutePaht = Server.MapPath("~/");

        absolutePaht = absolutePaht + "//Data";
        ModelAction modelAction = new ModelAction();

        //总商品数
        int allGoodsCount = modelAction.ExcelCount(absolutePaht);

        if (Request["action"] == "search")
        {
            string condition = Request.Form["searchCondition"];
            sc                 = condition;
            modelList          = modelAction.ReadDataToExcel(absolutePaht, pageNum, "S", condition);
            pageCountOneScream = modelList.Count / 50 > 20 ? 20 : modelList.Count / 50;
            return;
        }

        if (!string.IsNullOrWhiteSpace(Request["sc"]))
        {
            string condition = Request.Form["searchCondition"];
            sc                 = Request["sc"];
            modelList          = modelAction.ReadDataToExcel(absolutePaht, pageNum, "S", Request["sc"]);
            pageCountOneScream = modelList.Count > 20 ? 20 : modelList.Count;
            return;
        }

        if (Request["action"] == "lucky")
        {
            Random random = new Random();
            pageNum            = random.Next(1, allGoodsCount / 50);
            modelList          = modelAction.ReadDataToExcel(absolutePaht, pageNum, "", "");
            pageCountOneScream = modelList.Count > 20 ? 20 : modelList.Count;
            return;
        }

        modelList = modelAction.ReadDataToExcel(absolutePaht, pageNum, "", "");

        pageCountOneScream = modelList.Count > 20 ? 20 : modelList.Count;
    }
 public SerializeValueProvider(
     IValueProvider ValueProvider,
     PermissionHandler <TRelation, TUser> PermissionHandler,
     IRequest IRequest,
     TRelation Relation,
     PropertyInfo PropertyType,
     ModelAction modelAction,
     HttpRequestMethod requestMethod)
 {
     this.ValueProvider     = ValueProvider;
     this.PermissionHandler = PermissionHandler;
     this.IRequest          = IRequest;
     this.PropertyType      = PropertyType;
     this.ModelAction       = modelAction;
     this.RequestMethod     = requestMethod;
     this.Relation          = Relation;
 }
예제 #19
0
        protected void BroadcastResourceChange(ModelAction action)
        {
            if (!_signalRBroadcaster.IsConnected)
            {
                return;
            }

            if (GetType().Namespace.Contains("V1"))
            {
                var signalRMessage = new SignalRMessage
                {
                    Name   = Resource,
                    Body   = new ResourceChangeMessage <TResource>(action),
                    Action = action
                };

                _signalRBroadcaster.BroadcastMessage(signalRMessage);
            }
        }
예제 #20
0
        protected void BroadcastResourceChange(ModelAction action, int id)
        {
            if (!_signalRBroadcaster.IsConnected)
            {
                return;
            }

            if (action == ModelAction.Deleted)
            {
                BroadcastResourceChange(action, new TResource {
                    Id = id
                });
            }
            else
            {
                var resource = GetResourceById(id);
                BroadcastResourceChange(action, resource);
            }
        }
예제 #21
0
        private void Refresh(object sender, ModelAction <Transaction> obj)
        {
            var menuItem = Items.Where(i => i is AccountMenuItem)
                           .Cast <AccountMenuItem>()
                           .SingleOrDefault(i => i.Id == obj.Item.AccountId);

            if (menuItem != null)
            {
                var account = menuItem.Account;
                switch (obj.Action)
                {
                case ActionType.Add:
                    account.CurrentBalance += obj.Item.Amount;
                    break;

                case ActionType.Delete:
                    account.CurrentBalance -= obj.Item.Amount;
                    break;
                }
                menuItem.Balance = account.CurrentBalance;
            }
        }
예제 #22
0
 public IActionResult Handle(
     string resourceName,
     string identifierName,
     string identifierValue,
     ModelAction requestedAction,
     TRelation relationType,
     string relatedResourceName,
     string relatedIdentifierName,
     string relatedIdentifierValue,
     long extra) =>
 Handle(new IRequest {
     ResourceName    = resourceName,
     IdentifierName  = identifierName,
     IdentifierValue = identifierValue,
     ExtraCode       = extra
 },
        requestedAction, relationType,
        new IRequest {
     ResourceName    = relatedResourceName,
     IdentifierName  = relatedIdentifierName,
     IdentifierValue = relatedIdentifierValue
 },
        new StreamReader(Request.Body, Encoding.UTF8).ReadToEnd());
예제 #23
0
 private void CallModel(ModelAction modelAction)
 {
     GetText();
     modelAction();
     PutText(textBox, model.LinesArray(), model.SelectionStart);
 }
예제 #24
0
 public bool IsActionHolded(ModelAction i_ModelAction)
 {
     return(rewiredPlayer.GetButton(i_ModelAction.controlName));
 }
예제 #25
0
 public ResourceChangeMessage(TResource resource, ModelAction action)
 {
     Resource = resource;
     Action   = action;
 }
예제 #26
0
 void DialogFileAction(FileDialog dialog, ModelAction action)
 {
     dialog.Filter = "XML Files (*.xml) | *.xml | All Files (*.*) | *.*";
     dialog.FilterIndex = 1;
     dialog.RestoreDirectory = true;
     if(dialog.ShowDialog() == DialogResult.OK)
     {
         fileName = dialog.FileName;
         CallModel(action);
     }
 }
예제 #27
0
 public DomainEvent(ModelType domain, ModelAction action)
     : this(domain, action, null)
 {
 }
예제 #28
0
 public ModelEvent(TModel model, ModelAction action)
 {
     ModelId = model.Id;
     Model   = model;
     Action  = action;
 }
예제 #29
0
 // explicit ModelAction:
 public bool Can(ModelAction ma)
 {
     return Actions.ContainsKey(Controller) && (Actions[Controller] & (ActionFlags)ma) > 0;
 }
예제 #30
0
		private void	ExecuteAction(ModelAction action)
		{
			//CallBefore, actions
			//TODO: What happens if this now meets the requirements?
			foreach(ModelAction before in this.GetPossibleActions(action.Model.Actions.FindFlag(ModelActionFlags.CallBefore)))
				this.ExecuteActionInfo(new ModelActionInfo(before, this.DetermineParameters(before), null));

			//Execute Action
			this.ExecuteActionInfo(new ModelActionInfo(action, this.DetermineParameters(action), null));

			//CallAfter, actions
			//TODO: What happens if this now meets the requirements?
			foreach(ModelAction after in this.GetPossibleActions(action.Model.Actions.FindFlag(ModelActionFlags.CallAfter)))
				this.ExecuteActionInfo(new ModelActionInfo(after, this.DetermineParameters(after), null));
		}
예제 #31
0
		protected ModelParameters		DetermineParameters(ModelAction action)
		{
			try
			{
				ModelParameters allparameters = action.Parameters;
				ModelParameters choosen = new ModelParameters();

				//Loop through the method parameters
				foreach(ParameterInfo info in action.Method.GetParameters())
				{
					//Find the all parameters assoicated with this param
					ModelParameters parameters = allparameters.Find(info.Name);
					//Exclude invalid parameters (if not requested)
					if(!this.InvalidParameters)
						parameters = (ModelParameters)parameters.FindFlag((int)ModelItemFlags.Throws, false);
					if(parameters.Count <= 0)
						throw new ModelException(this, "Unable to find a ModelParameter for method parameter: '" + info.Name + "'");

					//Choose one of the parameters, based upon weight
                    ModelParameter parameter = parameters.Choose(this);
                    parameter.Accessed++;
                    
                    //Note: We cloning the param, since were choosing only one of the values to use this time.
                    parameter = (ModelParameter)parameter.Clone();

					//Choose (or generate) one of the values
					ModelValue value = DetermineParameterValue(parameter);
					value.Accessed++;
			
					//Add it to the array
					parameter.Value = value;
					choosen.Add(parameter);
				}
				
				return choosen;
			}
			catch(Exception e)
			{
				//Make this easier to debug
				throw new ModelException(this, "DetermineParameters", e);
			}
		}
예제 #32
0
 void InitializeDelegates(TextModel model)
 {
     enterDelegate = new ModelAction(model.InsertParagraphTag);
     shiftEnterDelegate = new ModelAction(model.InsertReturn);
     insertSectionDelegate = new ModelAction(model.InsertSectionTag);
     insertPreDelegate = new ModelAction(model.InsertPreTag);
     saveAction = new ModelAction(this.SaveFile);
     loadAction = new ModelAction(this.LoadFile);
     insertUnorderedListAction = new ModelAction(model.InsertUnorderedList);
 }
예제 #33
0
 // set individual flag:
 public void Allow(string controller, ModelAction a)
 {
     Actions[controller] = Actions.ContainsKey(controller) ? Actions[controller] | (ActionFlags)a : (ActionFlags)a;
 }
예제 #34
0
 public ModelEvent(int modelId, ModelAction action)
 {
     ModelId = modelId;
     Action  = action;
 }
예제 #35
0
 void FileOperation(FileDialog dialog, ModelAction action)
 {
     if(displayDialog)
     {
         displayDialog = true;
         DialogFileAction(dialog, action);
         return;
     }
     CallModel(action);
 }
예제 #36
0
        public dynamic ValidateRequest(
            HttpRequestMethod requestMethod,
            IRequest request,
            ModelAction requestedAction,
            TRelation relationType)
        {
            if (request == null ||
                request.ResourceName == null || string.IsNullOrWhiteSpace(request.ResourceName))
            {
                return("Request Error: Route parameters should not be empty");
            }

            // Check ResourceName
            //* Check whether resource is exist or not? is direct access allowed or not?
            var resourceType = modelParser.GetResourceType(request.ResourceName);

            if (resourceType == null)
            {
                return("Requested resource {" + request.ResourceName +
                       "} is not exist or direct access is not permitted");
            }

            request.Temp_ResourceType = resourceType;

            if (requestedAction != ModelAction.Create)
            {
                if (request.IdentifierName == null || string.IsNullOrWhiteSpace(request.IdentifierName) ||
                    request.IdentifierValue == null || string.IsNullOrWhiteSpace(request.IdentifierValue))
                {
                    return("Request Error: Route parameters should not be empty");
                }

                //* Check whether this identifier is exist or not for model
                var identifierValidator =
                    (resourceType.GetCustomAttributes(typeof(IdentifierValidatorAttribute), true) as IdentifierValidatorAttribute[])
                    .Union(
                        resourceType.GetProperties()
                        .Where(property => property.IsDefined(typeof(IdentifierValidatorAttribute)))
                        .Select(validator => validator.GetCustomAttribute(typeof(IdentifierValidatorAttribute), true) as IdentifierValidatorAttribute)
                        )
                    .Where(validator => validator.PropertyName == request.IdentifierName)
                    .FirstOrDefault();

                if (identifierValidator == null || identifierValidator.Validator == null)
                {
                    return("Requested model identifier does not exist or it's not permitted to use it as an identifier");
                }

                var identifierValidation =
                    APIUtils.InvokeMethod(
                        identifierValidator.Validator,
                        "Validate",
                        new object[] {
                    request.IdentifierValue
                });

                if (!(identifierValidation is bool && (bool)identifierValidation))
                {
                    return("Request Error: The value {" + request.IdentifierValue +
                           "} is not a valid value for identifier {" + request.IdentifierName + "}");
                }
            }

            return(ModelValidation(
                       Request: request,
                       ModelType: resourceType,
                       ModelAction: requestedAction,
                       RequestMethod: requestMethod,
                       RelationType: relationType));
        }
예제 #37
0
        public void CheckPermissionRequirements(
            IRequest Request,
            ModelAction ModelAction,
            HttpRequestMethod RequestMethod,
            object model)
        {
            if (model == null)
            {
                return;
            }

            var protectedAttributes = model.GetPropertiesWithAttribute(typeof(ModelPermissionAttribute));

            foreach (var attribute in protectedAttributes)
            {
                var attributeValue = attribute.GetValue(model);
                if (attributeValue == null)
                {
                    continue;
                }

                var permission = ModelPropertyValidation(
                    Request: Request,
                    PropertyInfo: attribute,
                    Model: model,
                    ModelAction: ModelAction,
                    RequestMethod: RequestMethod);

                if (!(permission is bool && (bool)permission))
                {
                    attribute.SetValue(model, null);
                }
            }

            var innerProperties = model
                                  .GetType()
                                  .GetProperties()
                                  .Where(property =>
                                         property.PropertyType.FullName.Contains(
                                             AppDomain.CurrentDomain.FriendlyName
                                             ) ||
                                         property.PropertyType.FullName.StartsWith("API") ||
                                         (property.PropertyType.Name.StartsWith("ICollection") &&
                                          property.PropertyType
                                          .GetGenericArguments()
                                          .FirstOrDefault()
                                          .FullName
                                          .Contains(
                                              AppDomain.CurrentDomain.FriendlyName
                                              )
                                         ) &&
                                         !property.PropertyType.IsEnum &&
                                         property.PropertyType.IsClass
                                         ).ToList();

            foreach (var property in innerProperties)
            {
                if (property == null)
                {
                    continue;
                }

                var attributeValue = property.GetValue(model);
                if (attributeValue == null)
                {
                    continue;
                }

                if (property.PropertyType.Name.StartsWith("ICollection"))
                {
                    var collection = attributeValue as IEnumerable;
                    foreach (var item in collection)
                    {
                        CheckPermissionRequirements(Request, ModelAction, RequestMethod, item);
                    }
                }
                else
                {
                    CheckPermissionRequirements(Request, ModelAction, RequestMethod, attributeValue);
                }
            }
        }
예제 #38
0
 public DomainEvent(ModelType domain, ModelAction action, object data)
 {
     Module = domain.GetName();
     Action = action.GetName();
     Data   = data;
 }
예제 #39
0
 public void Disallow(string controller, ModelAction a)
 {
     if (Actions.ContainsKey(controller))
     {
         Actions[controller] = Actions[controller] ^ (ActionFlags)a;
     }
 }