Example #1
0
        public Property Only_Entries_With_Allowed_Operations_Are_Deleted()
        {
            return(Prop.ForAll(
                       SupportedProviderSettings(),
                       Arb.From <Operation>(),
                       (specificSettings, operation) =>
            {
                // Arrange
                OverrideWithSpecificSettings(specificSettings);

                string id = GenId();
                InMessage m = CreateInMessage(id, insertionTime: DayBeforeYesterday);
                m.Operation = operation;

                IConfig config = EnsureLocalConfigPointsToCreatedDatastore();
                var spy = new DatabaseSpy(config);
                spy.InsertInMessage(m);

                // Act
                ExerciseStartCleaning();

                // Assert
                bool hasEntries = spy.GetInMessages(id).Any();
                string description = $"InMessage {(hasEntries ? "isn't" : "is")} deleted, with Operation: {operation}";
                return (hasEntries == !AllowedOperations.Contains(operation)).Collect(description);
            }));
        }
        protected KnockoutBindingGroup BuildControlKnockoutBinding()
        {
            var binding = new KnockoutBindingGroup();

            binding.Add("maxItemsCount", this, MaxItemsCountProperty, () =>
            {
                binding.Add("maxItemsCount", MaxItemsCount.ToString());
            });

            binding.Add("groupName", this, GroupNameProperty, () =>
            {
                binding.Add("groupName", KnockoutHelper.MakeStringLiteral(GroupName));
            });

            binding.Add("allowedOperations", KnockoutHelper.MakeStringLiteral(AllowedOperations.ToString()));

            if (HasBinding(ItemDroppedProperty))
            {
                var tempContainer = GetDataContextTarget(this, ItemDroppedProperty);
                var function      = KnockoutHelper.GenerateClientPostBackExpression(nameof(ItemDropped), GetCommandBinding(ItemDroppedProperty), tempContainer, new PostbackScriptOptions()
                {
                    ElementAccessor = CodeParameterAssignment.FromIdentifier("target")
                });
                binding.Add("onItemDropped", $"function (target) {{ {function} }}");
            }

            return(binding);
        }
Example #3
0
 /// <summary>
 /// Конструктор, недоступный вне проекта EditorModel
 /// (только для внутреннего использования)
 /// </summary>
 /// <param name="path">Закрепляемый путь для примитивной геометрии</param>
 /// <param name="allowed">набор прав для операций</param>
 internal PrimitiveGeometry(GraphicsPath path, AllowedOperations allowed)
 {
     // запоминаем переданный в конструкторе путь в локальном поле
     _path = path;
     // запоминаем ограничения для операций в локальном поле
     _allowedOperations = allowed;
 }
 /// <summary>
 /// Конструктор, недоступный вне проекта EditorModel
 /// (только для внутреннего использования)
 /// </summary>
 internal TextGeometry()
 {
     _allowedOperations = AllowedOperations.All;
     Text     = String.Empty;
     FontName = "Arial";
     FontSize = 14f;
 }
Example #5
0
        /// <summary>
        /// Конструктор с настройками по умолчанию
        /// </summary>
        internal PolygoneGeometry(bool isClosed = true, PointF[] points = null)
        {
            IsClosed           = isClosed;
            _allowedOperations = AllowedOperations.All ^ AllowedOperations.Pathed;
            var rect = new RectangleF(-0.5f, -0.5f, 1, 1);

            if (points != null)
            {
                _points = (PointF[])points.Clone();
            }
            else if (isClosed)
            {
                _points = new[]
                {
                    new PointF(rect.Left, rect.Top),
                    new PointF(rect.Left + rect.Width, rect.Top),
                    new PointF(rect.Left + rect.Width, rect.Top + rect.Height),
                    new PointF(rect.Left, rect.Top + rect.Height)
                }
            }
            ;
            else
            {
                _points = new[]
                {
                    new PointF(rect.Left, rect.Top),
                    new PointF(rect.Left + rect.Width, rect.Top + rect.Height)
                }
            };
        }
Example #6
0
 /// <summary>
 /// Обработчик пункта меню "Вход..."
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void tsmiLogin_Click(object sender, EventArgs e)
 {
     // если есть хотя бы один администратор, записанный в модели данных
     if (_hotel.IsAdministratorDefined())
     {
         // вызываем форму регистрации, передавая в конструктор ссылку на модель данных
         var frm   = new LoginForm(_hotel);
         var users = _hotel.GetUsers(); // список пользователей получаем соответствующим методом
         frm.Build(users);              // форма настраивает свои компоненты, используя передаваемый в метод этот список
         // показываем форму в диалогом режиме
         if (frm.ShowDialog(this) == DialogResult.OK)
         {
             // если пользователь нажал кнопку "ОК"
             _allowedOperations = frm.AllowedOperations; // получаем набор прав пользователя
             _hotel.CurrentUser = frm.User;              // получаем ссылку на выбранного пользователя
             ShowDefault();                              // показываем "заставку"
             tsslStatusLabel.Text = "";                  // и очищаем статусную строку
         }
     }
     else // нет администраторов в системе
     {
         _allowedOperations = AllowedOperations.All; // назначаем полный доступ
         _hotel.CurrentUser = null; // сброс текущего пользователя
         // сообщаем пользователю это:
         MessageBox.Show("Вам доступны все функции программы, пока не будет определён пользователь с административными правами");
     }
 }
Example #7
0
 /// <summary>
 /// Добавить должность
 /// </summary>
 /// <param name="nameRole">Должность</param>
 /// <param name="salary">Зарплата</param>
 /// <param name="allowedOperations">Права доступа в программе</param>
 public void Add(string nameRole, decimal salary, AllowedOperations allowedOperations)
 {
     base.Add(new EmployeeRole
     {
         NameRole          = nameRole,
         Salary            = salary,
         AllowedOperations = allowedOperations
     });
 }
        /// <summary>
        /// Конструктор с настройками по умолчанию
        /// </summary>
        internal PolylineGeometry()
        {
            _allowedOperations = AllowedOperations.All;
            var rect = new RectangleF(-0.5f, -0.5f, 1, 1);

            _points = new[]
            {
                new PointF(rect.Left, rect.Top),
                new PointF(rect.Left + rect.Width, rect.Top + rect.Height)
            };
        }
        public void IsAllowed_NoOperationsPermitted_OperationIsNotAllowed()
        {
            // Arrange
            var operationToCheck  = Tuple.Create(AREA_1_ID, OPERATION_3_ID);
            var allowedOperations = new AllowedOperations(new List <AuthOperation>());

            // Act
            bool result = allowedOperations.IsAllowed(operationToCheck);

            // Assert
            Assert.IsFalse(result);
        }
        public async Task<string> makeOperationAsync(AllowedOperations op, Cours reqCours = null, int resID = -1)
        {
            if (ApplicationModel.Current.IsConnected)
            {
                if (!isExpired || (await getSessionCookieAsync()))
                {
                    CallbackArgs args = null;
                    switch (op)
                    {
                        case AllowedOperations.getSingleAnnounce:
                            if (reqCours == null && resID < 0)
                            {
                                return "";
                            }
                            args = new CallbackArgs() { cidReq = reqCours, resId = resID, operation = op };
                            break;
                        case AllowedOperations.getCourseToolList:
                        case AllowedOperations.getDocList:
                        case AllowedOperations.getAnnounceList:
                            if (reqCours == null)
                            {
                                return "";
                            }
                            args = new CallbackArgs() { cidReq = reqCours, operation = op };
                            break;
                        case AllowedOperations.getUserData:
                        case AllowedOperations.getCourseList:
                        case AllowedOperations.getUpdates:
                            args = new CallbackArgs() { operation = op };
                            break;
                    }

                    HttpResponseMessage response = null;
                    HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post,
                                                 ApplicationModel.Current.Domain + ApplicationModel.Current.WebServicePath);
                    
                    StringContent content = new StringContent(args.ToString());
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    message.Content = content;
                    HttpClient request = getClient();
                    response = await request.SendAsync(message);
                    String result = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine("Fin de la méthode " + op.ToString() + " : " + result);
                    return result;
                }
            }
                //TODO tell the user the network is unavailable
                return "";

        }
Example #11
0
        /// <summary>
        /// Обработчик пункта меню "Строка подключения к серверу..."
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiConnectionString_Click(object sender, EventArgs e)
        {
            var frm = new ConnectionStringForm();

            frm.Build(Properties.Settings.Default.ConnectionString);
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                Properties.Settings.Default.ConnectionString = frm.Data;
                Properties.Settings.Default.Save();
                tsslStatusLabel.Text = "Загрузка данных...";
                ShowDefault();
                _allowedOperations = AllowedOperations.None;
                LoadFromBaseAsync();
            }
        }
        public void IsAllowed_OperationPermitted_OperationIsAllowed()
        {
            // Arrange
            var operationToCheck  = Tuple.Create(AREA_1_ID, OPERATION_1_ID);
            var allowedOperations = new AllowedOperations(new List <AuthOperation>
            {
                Tuple.Create(AREA_1_ID, OPERATION_1_ID),
                Tuple.Create(AREA_1_ID, OPERATION_2_ID)
            });

            // Act
            bool result = allowedOperations.IsAllowed(operationToCheck);

            // Assert
            Assert.IsTrue(result);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello!");
            Console.WriteLine("Insert first number and click enter:");
            int.TryParse(Console.ReadLine(), out int A);
            Console.WriteLine("Insert secound number and click enter:");
            int.TryParse(Console.ReadLine(), out int B);

            AllowedOperations choosenOperation = ChooseDesiredOperation();
            Number            number           = new Number(A, B, choosenOperation);

            InitializeNewOperations();
            InitializeChainOfResponsibility();

            Console.ForegroundColor = ConsoleColor.Green;
            addition.Calculate(number);
            Console.ForegroundColor = ConsoleColor.White;
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ASRProtectionEntity" /> class when it is protected
        /// </summary>
        /// <param name="pi">Protectable Item to read values from</param>
        /// <param name="rpi">Replication Protected Item to read values from</param>
        public ASRProtectionEntity(ProtectableItem pi, ReplicationProtectedItem rpi, Policy policy = null) : this(pi)
        {
            this.Type = rpi.Type;
            this.ProtectionStateDescription = rpi.Properties.ProtectionStateDescription;

            if (rpi.Properties.AllowedOperations != null)
            {
                this.AllowedOperations = new List<string>();
                foreach (String op in rpi.Properties.AllowedOperations)
                {
                    AllowedOperations.Add(op);
                }
            }
            this.ReplicationProvider = rpi.Properties.ProviderSpecificDetails.InstanceType;
            this.ActiveLocation = rpi.Properties.ActiveLocation;
            this.ReplicationHealth = rpi.Properties.ReplicationHealth;
            this.TestFailoverStateDescription = rpi.Properties.TestFailoverStateDescription;
            this.ProtectionStatus = rpi.Properties.ProtectionState;
            if (policy != null)
            {
                this.Policy = new ASRPolicy(policy);
            }
        }
 /// <summary>
 /// Конструктор, недоступный вне проекта EditorModel
 /// (только для внутреннего использования)
 /// </summary>
 internal TextGeometry()
 {
     _allowedOperations = AllowedOperations.All ^ AllowedOperations.Pathed;
     Text     = String.Empty;
     FontName = "Arial";
 }
Example #16
0
 internal PrimitiveGeometry(SerializableGraphicsPath path, AllowedOperations allowed)
 {
     Name  = "Primitive";
     _path = path;
     _allowedOperations = allowed;
 }
 public Number(int numberOne, int numberTwo, AllowedOperations operationWanted)
 {
     NumberOne       = numberOne;
     NumberTwo       = numberTwo;
     OperationWanted = operationWanted;
 }
 internal BezierGeometry(PointF[] points, byte[] types)
 {
     _allowedOperations = AllowedOperations.All ^ AllowedOperations.Pathed;
     Points             = points;
     Types = types;
 }
Example #19
0
        public XmlNode ToXml(XmlDocument doc)
        {
            XmlNode      tableNode = doc.CreateElement("Table");
            XmlAttribute Id        = doc.CreateAttribute("Id");

            Id.Value = ObjectId;
            tableNode.Attributes.Append(Id);
            XmlAttribute aName = doc.CreateAttribute("Name");

            aName.Value = Name;
            tableNode.Attributes.Append(aName);

            XmlAttribute create = doc.CreateAttribute("Create");

            create.Value = AllowedOperations.CanCreate().ToString();
            tableNode.Attributes.Append(create);

            XmlAttribute read = doc.CreateAttribute("Read");

            read.Value = AllowedOperations.CanRead().ToString();
            tableNode.Attributes.Append(read);

            XmlAttribute update = doc.CreateAttribute("Update");

            update.Value = AllowedOperations.CanUpdate().ToString();
            tableNode.Attributes.Append(update);


            XmlAttribute delete = doc.CreateAttribute("Delete");

            delete.Value = AllowedOperations.CanDelete().ToString();
            tableNode.Attributes.Append(delete);


            XmlNode columnsNode = doc.CreateElement("Columns");

            foreach (RbacColumn column in Columns)
            {
                columnsNode.AppendChild(column.ToXml(doc));
            }
            tableNode.AppendChild(columnsNode);

            XmlElement relationsNode = doc.CreateElement("Relations");

            foreach (RbacRelation relation in Relations)
            {
                relationsNode.AppendChild(relation.ToXml(doc));
            }
            tableNode.AppendChild(relationsNode);

            XmlNode condnsNode = doc.CreateElement("Conditions");

            foreach (RbacCondition condition in Conditions)
            {
                condnsNode.AppendChild(condition.ToXml(doc));
            }
            tableNode.AppendChild(condnsNode);

            XmlNode paramsNode = doc.CreateElement("Parameters");

            foreach (RbacParameter parameter in Parameters)
            {
                paramsNode.AppendChild(parameter.ToXml(doc));
            }
            tableNode.AppendChild(paramsNode);

            return(tableNode);
        }
Example #20
0
 internal PrimitiveBezier(SerializableGraphicsPath path, AllowedOperations allowed) : base(path, allowed)
 {
     Name    = "Bezier";
     _points = path.Path.PathPoints;
     _types  = path.Path.PathTypes;
 }
 public CapabilityResource AllowPublish()
 {
     AllowedOperations.Add(AllowedOps.Publish);
     return(this);
 }
 public CapabilityResource AllowSubscribe()
 {
     AllowedOperations.Add(AllowedOps.Subscribe);
     return(this);
 }
 public CapabilityResource AllowPresence()
 {
     AllowedOperations.Add(AllowedOps.Presence);
     return(this);
 }
 public void AllowAll()
 {
     AllowedOperations.Add(AllowedOps.All);
 }
Example #25
0
 /// <summary>
 /// Конструктор с настройками по умолчанию
 /// </summary>
 internal PolygoneGeometry()
 {
     _allowedOperations = AllowedOperations.All;
 }