Inheritance: MonoBehaviour
Beispiel #1
0
    // Use this for initialization
    protected void Start()
    {
        Action[] actions =  gameObject.GetComponents<Action>() as Action[];
        Trigger = gameObject.GetComponent<Trigger>();
        if (Trigger == null)
        {
            Debug.Log("No Trigger found." + gameObject.name + " interaction not initilized!");
            return;
        }

        if (actions == null)
        {
            Debug.Log("No actions found." + gameObject.name + " interaction not initilized!");
            return;
        }
        foreach (Action action in actions)
        {
            if (Interactions == null)
            {
                Interactions = new List<Action>();
            }
            Interactions.Add(action);
            Debug.Log("Adding interaction: " + action.GetType());
            Trigger.OnTriggerActivated += action.OnTriggerActivated;
            Trigger.OnTriggerDeactivated += action.OnTriggerDeactivated;

        }
    }
Beispiel #2
0
 protected virtual void OnTrigger(Trigger pTrigger)
 {
     if(m_Trigger != null && (m_Trigger.gameObject == pTrigger.gameObject))
     {
         Trigger();
     }
 }
        public PencilGamingWindows(int width, int height, string title, bool isFullscreen, bool shouldVsync)
        {
            onWindowOpened = new Trigger<PencilGamingWindows>();
            OnWindowOpened = onWindowOpened;

            onWindowClosed = new Trigger<PencilGamingWindows>();
            OnWindowClosed = onWindowClosed;

            onWindowResized = new Trigger<PencilGamingWindows>();
            OnWindowResized = onWindowResized;

            onKeyboard = new Trigger<PencilKeyInfo>();
            OnKeyboard = onKeyboard;

            onExit = new Trigger<PencilGamingWindows>();
            OnExit = onExit;

            window = GlfwWindowPtr.Null;
            this.width = width;
            this.height = height;
            this.title = title;
            this.isFullscreen = isFullscreen;
            this.shouldVsync = shouldVsync;
            this.firstTime = true;
            if (!Glfw.Init())
            {
                Console.Error.WriteLine("ERROR: Could not initialize GLFW, shutting down.");
                Environment.Exit(1);
            }
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Trigger t = new Trigger();
            t.Name = FileNameTextBox.Text;
            t.ID = IDTextBox.Text;
            t.Hash = BinaryEditor.HexStringToBytes(HashTextBox.Text);

            if (SizeLimitTextBox.Text.Trim() == "" || !Regex.IsMatch(SizeLimitTextBox.Text, "^[0-9]*$")) t.LimitSize = 0;
            else t.LimitSize = long.Parse(SizeLimitTextBox.Text);

            if (SizeLowerTextBox.Text.Trim() == "" || !Regex.IsMatch(SizeLowerTextBox.Text, "^[0-9]*$")) t.LowerSize = 0;
            else t.LowerSize = long.Parse(SizeLowerTextBox.Text);

            t.Category = new string[3] { "", "", "" };

            int i = 0;
            foreach (Match m in Regex.Matches(QueryTextBox.Text, "\"(.*?)\""))
            {
                if (i >= 3) break;
                t.Category[i] = m.Value.Trim('\"');
                i++;
            }

            t.Effect = EffectCheckBox.IsChecked == true ? true : false;
            t.Remove = TriggerDeleteCheckBox.IsChecked == true ? true : false;

            Settings.Default._triggerList.Add(t);

            this.DialogResult = true;
            this.Close();
        }
 override protected void SetDefaultTriggers()
 {
     SupportedTriggers = new Trigger[3]{
         AddHiddenComponent<EventTrigger>(),
         AddHiddenComponent<TrackTrigger>(),
         AddHiddenComponent<EventTrigger>()};
 }
		public override void SetUp()
		{
			base.SetUp();

			mockJobStore = Mocks.CreateMock<IJobStore>();
			mockJobRunner = Mocks.CreateMock<IJobRunner>();
			mockLogger = Mocks.CreateMock<ILogger>();
			mockTrigger = Mocks.PartialMock<Trigger>();
			scheduler = new DefaultScheduler(mockJobStore, mockJobRunner);

			dummyJobData = new JobData();
			dummyJobSpec = new JobSpec("foo", "bar", "key", mockTrigger);
			dummyJobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow);

			isWoken = false;

			// Ensure the scheduler is initialized.
			mockJobStore.RegisterScheduler(scheduler.Guid, scheduler.Name);
			Mocks.Replay(mockJobStore);
			scheduler.Initialize();
			Mocks.Verify(mockJobStore);
			Mocks.BackToRecord(mockJobStore);

			mockJobStore.UnregisterScheduler(scheduler.Guid);

			// Create a separate uninitialized scheduler for certain tests.
			uninitializedScheduler = new DefaultScheduler(mockJobStore, mockJobRunner);
		}
        public InputComponent(Game game)
            : base(game)
        {
            InteractTrigger = new Trigger<bool>();
            ApplyTrigger = new Trigger<bool>();
            InventoryTrigger = new Trigger<bool>();
            JumpTrigger = new Trigger<bool>();
            SlotLeftTrigger = new Trigger<bool>();
            SlotRightTrigger = new Trigger<bool>();
            SlotTrigger = new Trigger<bool>[SlotTriggerLength];
            for (int i = 0; i < SlotTrigger.Length; i++)
                SlotTrigger[i] = new Trigger<bool>();

            gamepad = new GamePadInput();
            keyboard = new KeyboardInput();
            mouse = new MouseInput(game);
            screenMouse = new MouseScreenInput();

            inputDevices = new List<IInputSet>{
                gamepad,
                keyboard,
                mouse
            };

            screenInputDevices = new List<IScreenInputSet>{
                screenMouse
            };
        }
Beispiel #8
0
 public override void Awake()
 {
     trigger = transform.Find("trigger").GetComponent<Trigger>();
     model = transform.Find("model").gameObject;
     controller = this.GetComponent<CharacterController>();
     base.Awake();
 }
Beispiel #9
0
 public static void AddTrigger(Trigger trigger)
 {
     if (triggers == null) {
         triggers = new List<Trigger>();
     }
     triggers.Add(trigger);
 }
        private void RegisterTargetTriggerEventHandler()
        {
            this.UnregisterTargetTriggerEventHandler();

            var t = this.Trigger;
            if (t == null) return;
            
            _targetTrigger = null;
            var arr = t.GetTriggers();
            if (arr.Length == 1)
            {
                _targetTrigger = arr[0];
            }
            else
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i].ObservableTriggerId == _triggerId)
                    {
                        _targetTrigger = arr[i];
                        break;
                    }
                }
            }

            if(_targetTrigger != null)
            {
                _targetTrigger.TriggerActivated += this.OnTriggerActivated;
            }
        }
 public void JobScheduled(Trigger trigger)
 {
     foreach (ISchedulerListener l in listeners)
     {
         l.JobScheduled(trigger);
     }
 }
 public override void perform(GameObject instigator, Trigger trig)
 {
     Player player = parent.GetComponent<Player>();
     if(player != null && !player.frozen) {
         player.die();
     }
 }
 public Movement(Type type, Trigger trigger, bool turnable, int frequency)
 {
     this.type = type;
     this.trigger = trigger;
     this.turnable = turnable;
     this.frequency = frequency;
 }
Beispiel #14
0
    public override void Off(Trigger trigger)
    {
        enable("blind");
        disable("look");

        base.Off(trigger);
    }
Beispiel #15
0
    public override void On(Trigger trigger)
    {
        enable("hear");

        base.On(trigger);
        Debug.Log("HearSense");
    }
Beispiel #16
0
 private void OnTrigger(Trigger pTrigger)
 {
     if(m_Trigger != null && (m_Trigger.gameObject == pTrigger.gameObject))
     {
         StartEmission ();
     }
 }
        public InputComponent(Game game)
            : base(game)
        {
            InteractTrigger = new Trigger<bool>();
            ApplyTrigger = new Trigger<bool>();
            InventoryTrigger = new Trigger<bool>();
            JumpTrigger = new Trigger<bool>();
            SlotLeftTrigger = new Trigger<bool>();
            SlotRightTrigger = new Trigger<bool>();
            SlotTrigger = new Trigger<bool>[SlotTriggerLength];
            for (int i = 0; i < SlotTrigger.Length; i++)
                SlotTrigger[i] = new Trigger<bool>();

            gamepad = new GamePadInput();
            keyboard = new KeyboardInput();
            mouse = new MouseInput(game);
            screenMouse = new MouseScreenInput();
            screenKeyboard = new KeyboardScreenInput();

            screenKeyboard.OnKeyDown += (key) => { if (OnKeyDown != null) OnKeyDown(key); };
            screenKeyboard.OnKeyUp += (key) => { if (OnKeyUp != null) OnKeyUp(key); };
            screenMouse.OnLeftMouseUp += (position) => { if (OnLeftMouseUp != null) OnLeftMouseUp(position); };

            inputDevices = new List<IInputSet>{
                gamepad,
                keyboard,
                mouse
            };

            screenInputDevices = new List<IScreenInputSet>{
                screenMouse
            };
        }
Beispiel #18
0
        public Trigger[] Load(IDbConnection connection)
        {
            var triggers = new List<Trigger>();

            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SELECT T.[object_id], T.[name], M.[definition] FROM sys.triggers T, sys.sql_modules M WHERE T.[object_id] = M.[object_id]";

                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        int objectId = reader.GetInt32(reader.GetOrdinal("object_id"));
                        string name = reader.GetString(reader.GetOrdinal("name"));
                        int definitionOrdinal = reader.GetOrdinal("definition");
                        string definition = reader.IsDBNull(definitionOrdinal) ? null : reader.GetString(definitionOrdinal);

                        var view = new Trigger(name, definition) {ObjectId = objectId};
                        triggers.Add(view);
                    }
                }
            }

            triggers.Sort((x, y) => string.CompareOrdinal(x.Name, y.Name));
            return triggers.ToArray();
        }
 public override void perform(GameObject instigator, Trigger trig)
 {
     LandMine mine = parent.GetComponent<LandMine>();
     if (mine != null) {
         mine.detonate();
     }
 }
 public override void perform(GameObject instigator, Trigger trig)
 {
     RobotController robot = parent.GetComponent<RobotController>();
     if(robot != null) {
         robot.dispose();
     }
 }
 public DbsyncTvTriggerType(Trigger trg)
 {
     this.trig = trg;
     this.Text = trg.Trigger_name;
     this.typeOfIcon = TriggerIcon;
     this.Name = this.Text;
 }
Beispiel #22
0
    public override void On(Trigger trigger)
    {
        base.On(trigger);

        World = Root.Instance.SenseManager.GetLayerItem("World");
        Player = Root.Instance.SenseManager.GetLayerItem("Player");

        if (World == null)
        {
            return;
        }

        if (Player != null)
        {
            playerPos = Player.transform.position;

            if (trigger != null && trigger.Item != null)
            {
                playerPos = trigger.Item.transform.position;
            }
        }

        startTime = Time.time;
        startRotation = World.transform.rotation.eulerAngles;
        endRotation = EndRotation;
    }
    void Start()
    {
        soundStopped = true;
        trigger = GetComponent<Trigger>();

        particles = GetComponent<ParticleSystem>();
    }
 static bool ActionIsTriggered(Trigger trigger, Settings  settings)
 {
     return 
            ((trigger == Trigger.New && settings.TrackingTriggerOnNew) ||
             ((trigger == Trigger.Update) && settings.TrackingTriggerOnUpdate) ||
             ((trigger == Trigger.Delete) && settings.TrackingTriggerOnDelete));
 }
Beispiel #25
0
    private void CollisionSettings(Trigger triggerObject)
    {
        using (new Vertical("box"))
        {
            GUILayout.Space(3f);
            showCollisionSettings = EditorGUILayout.Foldout(showCollisionSettings, "Collision Settings");

            GUILayout.Space(5f);

            if (showCollisionSettings)
            {
                if ((triggerObject.triggerType & Trigger.TriggerType.Collision) != 0)
                {
                    EditorGUILayout.PropertyField(impactForceThreshold, new GUIContent("Impact Force Threshold", "This is the minimum force required from a collision to trigger any fracture components this object is linked to.  Setting this to 0 would effectively make any collision trigger the fracture."));

                    EditorGUILayout.Separator();

                    EditorGUILayout.PropertyField(onlyTriggerWithTag, new GUIContent("Only Trigger With Tag", "If this checkbox is ticked, this object will only be triggered if the tag of the colliding object is the same as below."));
                    if(onlyTriggerWithTag.boolValue)
                    {
                        triggerTag.stringValue = EditorGUILayout.TagField(new GUIContent("Trigger Tag", "The desired tag to use for masking collisions by tag."), triggerTag.stringValue);
                    }
                }
                else
                {
                    using (new GUIColor(new Color(1.0f, 0.3f, 0.3f)))
                    {
                        GUILayout.Label("To use the collision settings, you must have enabled the collision trigger type.", EditorStyles.miniBoldLabel);
                    }
                }
            }
            GUILayout.Space(3f);
        }
    }
Beispiel #26
0
        /// <summary>
        /// Add or replace a trigger
        /// </summary>
        /// <param name="keyword">The keyword to trigger with</param>
        /// <param name="text">The text to respond with</param>
        /// <returns>True if replaced, false if added</returns>
        public bool Add(string keyword, string text)
        {
            foreach (Trigger needle in State.TriggerList.GetItems())
            {
                if (needle.Keyword == keyword)
                {
                    if (needle.Protect)
                    {
                        Irc.SendChannelMessage("Unable to remove protected trigger " + keyword + ".", false);
                        throw new Exception("Unable to remove protected trigger '" + keyword + "'");
                    }
                }
            }
            //check for existing command
            if (CommandHandler.GetCommands().ContainsKey(keyword))
            {
                Command existing = CommandHandler.GetCommands()[keyword];
                if (existing is TriggerInstance)
                {
                    //remove old trigger from command list
                    CommandHandler.GetCommands().Remove(keyword);
                    CommandHandler.RaiseChanged();
                }
                else
                {
                    //cannot remove non-trigger commands
                    throw new Exception("Cannot override existing non-trigger command '" + keyword + "'");
                }
            }

            //add new trigger command
            new TriggerInstance(text, keyword, false);

            //update trigger in state
            Trigger trigger = new Trigger();
            trigger.Keyword = keyword;
            trigger.Text = text;
            trigger.Protect = false;

            foreach (Trigger needle in State.TriggerList.GetItems())
            {
                if (needle.Keyword == keyword)
                {
                    //need to replace
                    if (needle.Text != text)
                    {
                        //remove old and add new
                        State.TriggerList.Remove(needle);
                        if (needle.Protect == true) trigger.Protect = true;
                        State.TriggerList.Add(trigger);
                    }
                    return true;
                }
            }

            //new trigger
            State.TriggerList.Add(trigger);
            return false;
        }
Beispiel #27
0
 public TriggerState(Trigger trigger)
 {
     this.id                   = trigger.triggerID;
     this.state                = trigger.state;
     this.isTriggered          = trigger.isTriggered;
     this.isReadyToBeTriggered = trigger.isReadyToBeTriggered;
     this.canReset             = trigger.canReset;
 }
 public GamePadTriggerCondition(string name, PlayerIndex playerIndex, Trigger trigger, Operator inputOperator, float compareValue)
 {
     Name = name;
     Player = playerIndex;
     Trigger = trigger;
     Operator = inputOperator;
     CompareValue = compareValue;
 }
Beispiel #29
0
 protected override void Start()
 {
     base.Start ();
     mHingeJoint = GetComponent<HingeJoint2D> ();
     mHalfAngleLimits = (int)((mHingeJoint.limits.max - mHingeJoint.limits.min) / 2);
     mHalfAngleLimits = Mathf.Abs (mHalfAngleLimits);
     mTrigger = GetComponent<Trigger> ();
 }
Beispiel #30
0
    public override void On(Trigger trigger)
    {
        enable("look");
        disable("blind");

        base.On(trigger);
        Debug.Log("LookSense");
    }
 void EnqueueTrigger(Trigger @event)
 {
     lock (this.stateMachine)
         this.stateMachine.Fire(@event);
 }
Beispiel #32
0
        private void UpdateTriggerControls(Trigger trigger, TriggerEvent triggerEvent, TriggerAction triggerAction, ComboBox eventComboBox, NumericUpDown eventNud, ComboBox eventValueComboBox, ComboBox actionComboBox, NumericUpDown actionNud, ComboBox actionValueComboBox)
        {
            eventNud.Visible = false;
            eventNud.DataBindings.Clear();
            eventValueComboBox.Visible = false;
            eventValueComboBox.DataBindings.Clear();
            eventValueComboBox.DataSource    = null;
            eventValueComboBox.DisplayMember = null;
            eventValueComboBox.ValueMember   = null;

            if (triggerEvent != null)
            {
                switch (plugin.GameType)
                {
                case GameType.TiberianDawn:
                    switch (eventComboBox.SelectedItem)
                    {
                    case TiberianDawn.EventTypes.EVENT_TIME:
                    case TiberianDawn.EventTypes.EVENT_CREDITS:
                    case TiberianDawn.EventTypes.EVENT_NUNITS_DESTROYED:
                    case TiberianDawn.EventTypes.EVENT_NBUILDINGS_DESTROYED:
                        eventNud.Visible = true;
                        eventNud.DataBindings.Add("Value", triggerEvent, "Data");
                        break;

                    case TiberianDawn.EventTypes.EVENT_BUILD:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = plugin.Map.BuildingTypes.Select(t => new { Name = t.DisplayName, Value = (long)t.ID }).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    default:
                        break;
                    }
                    break;

                case GameType.RedAlert:
                    switch (eventComboBox.SelectedItem)
                    {
                    case RedAlert.EventTypes.TEVENT_LEAVES_MAP:
                        eventValueComboBox.Visible    = true;
                        eventValueComboBox.DataSource = plugin.Map.TeamTypes.Select(t => t.Name).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedItem", triggerEvent, "Team");
                        break;

                    case RedAlert.EventTypes.TEVENT_PLAYER_ENTERED:
                    case RedAlert.EventTypes.TEVENT_CROSS_HORIZONTAL:
                    case RedAlert.EventTypes.TEVENT_CROSS_VERTICAL:
                    case RedAlert.EventTypes.TEVENT_ENTERS_ZONE:
                    case RedAlert.EventTypes.TEVENT_LOW_POWER:
                    case RedAlert.EventTypes.TEVENT_THIEVED:
                    case RedAlert.EventTypes.TEVENT_HOUSE_DISCOVERED:
                    case RedAlert.EventTypes.TEVENT_BUILDINGS_DESTROYED:
                    case RedAlert.EventTypes.TEVENT_UNITS_DESTROYED:
                    case RedAlert.EventTypes.TEVENT_ALL_DESTROYED:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = new { Name = "None", Value = (long)-1 }.Yield().Concat(plugin.Map.Houses.Select(t => new { t.Type.Name, Value = (long)t.Type.ID })).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    case RedAlert.EventTypes.TEVENT_BUILDING_EXISTS:
                    case RedAlert.EventTypes.TEVENT_BUILD:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = plugin.Map.BuildingTypes.Select(t => new { Name = t.DisplayName, Value = (long)t.ID }).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    case RedAlert.EventTypes.TEVENT_BUILD_UNIT:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = plugin.Map.UnitTypes.Where(t => t.IsUnit).Select(t => new { Name = t.DisplayName, Value = (long)t.ID }).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    case RedAlert.EventTypes.TEVENT_BUILD_INFANTRY:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = plugin.Map.InfantryTypes.Select(t => new { Name = t.DisplayName, Value = (long)t.ID }).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    case RedAlert.EventTypes.TEVENT_BUILD_AIRCRAFT:
                        eventValueComboBox.Visible       = true;
                        eventValueComboBox.DisplayMember = "Name";
                        eventValueComboBox.ValueMember   = "Value";
                        eventValueComboBox.DataSource    = plugin.Map.UnitTypes.Where(t => t.IsAircraft).Select(t => new { Name = t.DisplayName, Value = (long)t.ID }).ToArray();
                        eventValueComboBox.DataBindings.Add("SelectedValue", triggerEvent, "Data");
                        break;

                    case RedAlert.EventTypes.TEVENT_NUNITS_DESTROYED:
                    case RedAlert.EventTypes.TEVENT_NBUILDINGS_DESTROYED:
                    case RedAlert.EventTypes.TEVENT_CREDITS:
                    case RedAlert.EventTypes.TEVENT_TIME:
                    case RedAlert.EventTypes.TEVENT_GLOBAL_SET:
                    case RedAlert.EventTypes.TEVENT_GLOBAL_CLEAR:
                        eventNud.Visible = true;
                        eventNud.DataBindings.Add("Value", triggerEvent, "Data");
                        break;

                    default:
                        break;
                    }
                    break;
                }
            }

            actionNud.Visible = false;
            actionNud.DataBindings.Clear();
            actionNud.Minimum           = long.MinValue;
            actionNud.Maximum           = long.MaxValue;
            actionValueComboBox.Visible = false;
            actionValueComboBox.DataBindings.Clear();
            actionValueComboBox.DataSource    = null;
            actionValueComboBox.DisplayMember = null;
            actionValueComboBox.ValueMember   = null;

            if (triggerAction != null)
            {
                switch (plugin.GameType)
                {
                case GameType.RedAlert:
                    switch (actionComboBox.SelectedItem)
                    {
                    case RedAlert.ActionTypes.TACTION_CREATE_TEAM:
                    case RedAlert.ActionTypes.TACTION_DESTROY_TEAM:
                    case RedAlert.ActionTypes.TACTION_REINFORCEMENTS:
                        actionValueComboBox.Visible    = true;
                        actionValueComboBox.DataSource = plugin.Map.TeamTypes.Select(t => t.Name).ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedItem", triggerAction, "Team");
                        break;

                    case RedAlert.ActionTypes.TACTION_WIN:
                    case RedAlert.ActionTypes.TACTION_LOSE:
                    case RedAlert.ActionTypes.TACTION_BEGIN_PRODUCTION:
                    case RedAlert.ActionTypes.TACTION_FIRE_SALE:
                    case RedAlert.ActionTypes.TACTION_AUTOCREATE:
                    case RedAlert.ActionTypes.TACTION_ALL_HUNT:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = new { Name = "None", Value = (long)-1 }.Yield().Concat(plugin.Map.Houses.Select(t => new { t.Type.Name, Value = (long)t.Type.ID })).ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_FORCE_TRIGGER:
                    case RedAlert.ActionTypes.TACTION_DESTROY_TRIGGER:
                        actionValueComboBox.Visible    = true;
                        actionValueComboBox.DataSource = plugin.Map.Triggers.Select(t => t.Name).ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedItem", triggerAction, "Trigger");
                        break;

                    case RedAlert.ActionTypes.TACTION_DZ:
                    case RedAlert.ActionTypes.TACTION_REVEAL_SOME:
                    case RedAlert.ActionTypes.TACTION_REVEAL_ZONE:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = new { Name = "None", Value = (long)-1 }.Yield().Concat(plugin.Map.Waypoints.Select((t, i) => new { t.Name, Value = (long)i })).ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_1_SPECIAL:
                    case RedAlert.ActionTypes.TACTION_FULL_SPECIAL:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.SpecialWeaponType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.SpecialWeaponType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_PLAY_MUSIC:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.ThemeType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.ThemeType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_PLAY_MOVIE:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.VQType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.VQType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_PLAY_SOUND:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.VocType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.VocType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_PLAY_SPEECH:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.VoxType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.VoxType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_PREFERRED_TARGET:
                        actionValueComboBox.Visible       = true;
                        actionValueComboBox.DisplayMember = "Name";
                        actionValueComboBox.ValueMember   = "Value";
                        actionValueComboBox.DataSource    = Enum.GetValues(typeof(RedAlert.ActionDataTypes.QuarryType)).Cast <int>()
                                                            .Select(v => new { Name = Enum.GetName(typeof(RedAlert.ActionDataTypes.QuarryType), v), Value = (long)v })
                                                            .ToArray();
                        actionValueComboBox.DataBindings.Add("SelectedValue", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_TEXT_TRIGGER:
                        actionNud.Visible = true;
                        actionNud.Minimum = 1;
                        actionNud.Maximum = 209;
                        actionNud.DataBindings.Add("Value", triggerAction, "Data");
                        break;

                    case RedAlert.ActionTypes.TACTION_ADD_TIMER:
                    case RedAlert.ActionTypes.TACTION_SUB_TIMER:
                    case RedAlert.ActionTypes.TACTION_SET_TIMER:
                    case RedAlert.ActionTypes.TACTION_SET_GLOBAL:
                    case RedAlert.ActionTypes.TACTION_CLEAR_GLOBAL:
                    case RedAlert.ActionTypes.TACTION_BASE_BUILDING:
                        actionNud.Visible = true;
                        actionNud.DataBindings.Add("Value", triggerAction, "Data");
                        break;

                    default:
                        break;
                    }
                    break;
                }
            }
        }
Beispiel #33
0
 private static void GamepadOnTriggerMoved(IGamepad g, Trigger t)
 {
     Console.WriteLine($"G{g.Index}> {t.Index} trigger moved: {t.Position}");
 }
Beispiel #34
0
        private void worldView_DragDrop(object sender, DragEventArgs e)
        {
            Vector2 worldPos = ScreenToWorld(e.X, e.Y);

            if (snapping)
            {
                worldPos = SnapToGrid(worldPos);
            }

            //get item
            ListViewItem item = new ListViewItem();

            if (e.Data.GetData(typeof(ListViewItem)) != null)
            {
                item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            }

            object selectedObject = null;

            switch ((string)item.Tag)
            {
            case "Light":
                if (level.Lights.Count < 8)
                {
                    Light l = new Light();
                    l.Diffuse              = Color4.White;
                    l.Ambient              = new Color4(0.1f, 0.1f, 0.1f, 1f);
                    l.Position             = new Vector4(worldPos.X, worldPos.Y, 36, 1);
                    l.ConstantAttenuation  = 1f;
                    l.LinearAttenuation    = 1f / 3000f;
                    l.QuadraticAttenuation = 1f / 40000f;
                    level.Lights.Add(l);

                    for (int i = 0; i < 8; i++)
                    {
                        bool inUse = false;
                        for (int j = 0; j < level.Lights.Count; j++)
                        {
                            if (level.Lights[j].Index == i)
                            {
                                inUse = true;
                            }
                        }
                        if (!inUse)
                        {
                            l.Index = i;
                        }
                    }
                    selectedObject = l;
                }
                else
                {
                    MessageBox.Show("To many lights. Max light count is 8.", "Light Count", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;

            case "Ball":
                Ball ball = new Ball(worldPos.X, worldPos.Y);
                level.Entities.Add(ball);
                selectedObject = ball;
                break;

            case "Block":
                Block block = new Block(worldPos.X, worldPos.Y);
                level.Entities.Add(block);
                selectedObject = block;
                break;

            case "BreakableDoor":
                BreakableDoor bdoor = new BreakableDoor(worldPos.X, worldPos.Y);
                bdoor.MaxHits = 3;
                level.Entities.Add(bdoor);
                selectedObject = bdoor;
                break;

            case "Button":
                Entities.Button button = new Entities.Button(worldPos.X, worldPos.Y);
                level.Entities.Add(button);
                selectedObject = button;
                break;

            case "Cannon":
                Cannon cannon = new Cannon(worldPos.X, worldPos.Y);
                level.Entities.Add(cannon);
                selectedObject = cannon;
                break;

            case "Door":
                Door door = new Door(worldPos.X, worldPos.Y);
                level.Entities.Add(door);
                selectedObject = door;
                break;

            /*case "LaserShooter":
             *      LaserShooter ls = new LaserShooter(worldPos.X, worldPos.Y);
             *      level.Entities.Add(ls);
             *      selectedObject = ls;
             *      break;*/
            case "Player":
                Player p = new Player(worldPos.X, worldPos.Y);
                level.Entities.Add(p);
                selectedObject = p;
                break;

            /*case "PuzzleBox":
             *      PuzzleBox pb = new PuzzleBox(worldPos.X, worldPos.Y);
             *      level.Entities.Add(pb);
             *      selectedObject = pb;
             *      break;*/
            case "SpikeWall":
                SpikeWall sw = new SpikeWall(worldPos.X, worldPos.Y);
                level.Entities.Add(sw);
                selectedObject = sw;
                break;

            /*case "Teleporter":
             *      Teleporter tp = new Teleporter(worldPos.X, worldPos.Y);
             *      level.Entities.Add(tp);
             *      selectedObject = tp;
             *      break;*/
            case "CauseAND":
                CauseAND cAnd = new CauseAND();
                level.Causes.Add(cAnd);
                selectedObject = cAnd;
                break;

            case "CauseNOT":
                CauseNOT cNot = new CauseNOT();
                level.Causes.Add(cNot);
                selectedObject = cNot;
                break;

            case "CauseOR":
                CauseOR cOr = new CauseOR();
                level.Causes.Add(cOr);
                selectedObject = cOr;
                break;

            case "CauseXOR":
                CauseXOR cXor = new CauseXOR();
                level.Causes.Add(cXor);
                selectedObject = cXor;
                break;

            case "CauseButton":
                CauseButton cBtn = new CauseButton();
                level.Causes.Add(cBtn);
                selectedObject = cBtn;
                break;

            case "CauseEntityDestruction":
                CauseEntityDestruction cEntD = new CauseEntityDestruction();
                level.Causes.Add(cEntD);
                selectedObject = cEntD;
                break;

            case "CauseLocation":
                CauseLocation cLoc = new CauseLocation();
                level.Causes.Add(cLoc);
                selectedObject = cLoc;
                break;

            case "CauseTimePassed":
                CauseTimePassed cTime = new CauseTimePassed();
                level.Causes.Add(cTime);
                selectedObject = cTime;
                break;

            case "EffectAND":
                EffectAND eAnd = new EffectAND();
                level.Effects.Add(eAnd);
                selectedObject = eAnd;
                break;

            case "EffectList":
                EffectList eList = new EffectList();
                level.Effects.Add(eList);
                selectedObject = eList;
                break;

            case "EffectDoor":
                EffectDoor eDoor = new EffectDoor();
                level.Effects.Add(eDoor);
                selectedObject = eDoor;
                break;

            case "EffectEndGame":
                EffectEndGame eEnd = new EffectEndGame();
                level.Effects.Add(eEnd);
                selectedObject = eEnd;
                break;

            case "EffectRaiseBridge":
                EffectRaiseBridge eBridge = new EffectRaiseBridge();
                level.Effects.Add(eBridge);
                selectedObject = eBridge;
                break;

            case "EffectRemoveEntity":
                EffectRemoveEntity eRemove = new EffectRemoveEntity();
                level.Effects.Add(eRemove);
                selectedObject = eRemove;
                break;

            case "EffectTriggerTimer":
                EffectTriggerTimer eTimer = new EffectTriggerTimer();
                level.Effects.Add(eTimer);
                selectedObject = eTimer;
                break;

            case "Trigger":
                Trigger t = new Trigger();
                level.Triggers.Add(t);
                selectedObject = t;
                break;
            }

            selectedItemProperties.SelectedObject = selectedObject;

            UpdateWorldTree();
        }
Beispiel #35
0
        public override void StartDungeon()
        {
            base.StartDungeon();

            mTrigger = SceneServerControl.Timer.CreateTrigger(DateTime.Now, TimeTick, 1000);
        }
Beispiel #36
0
    void RunActions(Trigger trigger)
    {
        //Vector2 force = Vector2.zero;
        float speedup;

        foreach (var action in trigger.acts)
        {
            switch (action.Key)
            {
            case "Move":
                if (IsCollidingWith("bottom") && Math.Abs(body.angularVelocity) < LevelEngine.current.max_velocity)
                {
                    speedup = Time.deltaTime * LevelEngine.current.move_speedup
                              * (action.Value["direction"] == "right" && !direction_switched ||
                                 action.Value["direction"] == "left" && direction_switched ? -1 : 1);
                    body.AddTorque(speedup, ForceMode2D.Force);
                    //force.x += speedup;
                }
                break;

            case "Dash":
                if (trigger.evt != "Loop" && dash_timeout_time == 0)
                {
                    dash_timeout_time = LevelEngine.current.dash_timeout;
                    Vector2 dir;
                    if (action.Value["direction"] == "left")
                    {
                        dir = Vector2.left;
                    }
                    else if (action.Value["direction"] == "right")
                    {
                        dir = Vector2.right;
                    }
                    else if (action.Value["direction"] == "up")
                    {
                        dir = Vector2.up;
                    }
                    else
                    {
                        dir = Vector2.down;
                    }
                    body.AddForce(dir * LevelEngine.current.dash_speed);
                }
                break;

            case "Switch direction":
                direction_switched = !direction_switched;
                break;

            case "Jump":
                if (IsCollidingWith("bottom"))
                {
                    body.AddForce(new Vector2(0, LevelEngine.current.jump_speed));
                }
                break;

            case "Toggle movement":
                if (action.Value["toggle"] == "toggle")
                {
                    can_move = !can_move;
                }
                else
                {
                    can_move = action.Value["toggle"] == "start" ? true : false;
                }
                break;
            }
        }
    }
Beispiel #37
0
        public static void ClientEvent_ATMVAL(Client player, params object[] args)
        {
            try
            {
                if (Admin.IsServerStoping)
                {
                    Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Сервер сейчас не может принять это действие", 3000);
                    return;
                }
                var    acc  = Main.Players[player];
                int    type = NAPI.Data.GetEntityData(player, "ATMTYPE");
                string data = Convert.ToString(args[0]);
                int    amount;
                if (!Int32.TryParse(data, out amount))
                {
                    return;
                }
                switch (type)
                {
                case 0:
                    Trigger.ClientEvent(player, "atmClose");
                    if (Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Bank.Change(acc.Bank, +Math.Abs(amount));
                        GameLog.Money($"player({Main.Players[player].UUID})", $"bank({acc.Bank})", Math.Abs(amount), $"atmIn");
                        Trigger.ClientEvent(player, "setbank", Bank.Accounts[acc.Bank].Balance.ToString(), "");
                    }
                    break;

                case 1:
                    if (Bank.Change(acc.Bank, -Math.Abs(amount)))
                    {
                        Wallet.Change(player, +Math.Abs(amount));
                        GameLog.Money($"bank({acc.Bank})", $"player({Main.Players[player].UUID})", Math.Abs(amount), $"atmOut");
                        Trigger.ClientEvent(player, "setbank", Bank.Accounts[acc.Bank].Balance.ToString(), "");
                    }
                    break;

                case 2:
                    var house = Houses.HouseManager.GetHouse(player, true);
                    if (house == null)
                    {
                        return;
                    }

                    var maxMoney = Convert.ToInt32(house.Price / 100 * 0.013) * 24 * 7;
                    if (Bank.Accounts[house.BankID].Balance + Math.Abs(amount) > maxMoney)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Невозможно перевести столько средств на счет дома.", 3000);
                        return;
                    }
                    if (!Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Недостаточно средств.", 3000);
                        return;
                    }
                    Bank.Change(house.BankID, +Math.Abs(amount));
                    GameLog.Money($"player({Main.Players[player].UUID})", $"bank({house.BankID})", Math.Abs(amount), $"atmHouse");
                    Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Успешный перевод.", 3000);
                    Trigger.ClientEvent(player,
                                        "atmOpen", $"[2,'{Bank.Accounts[house.BankID].Balance}/{Convert.ToInt32(house.Price / 100 * 0.013) * 24 * 7}$','Сумма внесения наличных']");
                    break;

                case 3:
                    int bid = NAPI.Data.GetEntityData(player, "ATMBIZ");

                    Business biz = BusinessManager.BizList[acc.BizIDs[bid]];

                    maxMoney = Convert.ToInt32(biz.SellPrice / 100 * 0.013) * 24 * 7;
                    if (Bank.Accounts[biz.BankID].Balance + Math.Abs(amount) > maxMoney)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Невозможно перевести столько средств на счет бизнеса.", 3000);
                        return;
                    }
                    if (!Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Недостаточно средств.", 3000);
                        return;
                    }
                    Bank.Change(biz.BankID, +Math.Abs(amount));
                    GameLog.Money($"player({Main.Players[player].UUID})", $"bank({biz.BankID})", Math.Abs(amount), $"atmBiz");
                    Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Успешный перевод.", 3000);
                    Trigger.ClientEvent(player, "atmOpen", $"[2,'{Bank.Accounts[biz.BankID].Balance}/{Convert.ToInt32(biz.SellPrice / 100 * 0.013) * 24 * 7}$','Сумма зачисления']");
                    break;

                case 4:
                    if (!Bank.Accounts.ContainsKey(amount) || amount <= 0)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Счет не найден!", 3000);
                        Trigger.ClientEvent(player, "closeatm");
                        return;
                    }
                    NAPI.Data.SetEntityData(player, "ATM2ACC", amount);
                    Trigger.ClientEvent(player,
                                        "atmOpen", "[2,0,'Сумма для перевода']");
                    NAPI.Data.SetEntityData(player, "ATMTYPE", 44);
                    break;

                case 44:
                    if (Main.Players[player].LVL < 1)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, $"Перевод денег доступен после первого уровня", 3000);
                        return;
                    }
                    if (player.HasData("NEXT_BANK_TRANSFER") && DateTime.Now < player.GetData("NEXT_BANK_TRANSFER"))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, $"Следующая транзакция будет возможна в течение минуты", 3000);
                        return;
                    }
                    int bank = NAPI.Data.GetEntityData(player, "ATM2ACC");
                    if (!Bank.Accounts.ContainsKey(bank) || bank <= 0)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Счет не найден!", 3000);
                        Trigger.ClientEvent(player, "closeatm");
                        return;
                    }
                    if (Bank.Accounts[bank].Type != 1 && Main.Players[player].AdminLVL == 0)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Счет не найден!", 3000);
                        Trigger.ClientEvent(player, "closeatm");
                        return;
                    }
                    if (acc.Bank == bank)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Операция отменена.", 3000);
                        Trigger.ClientEvent(player, "closeatm");
                        return;
                    }
                    Bank.Transfer(acc.Bank, bank, Math.Abs(amount));
                    Trigger.ClientEvent(player, "closeatm");
                    if (Main.Players[player].AdminLVL == 0)
                    {
                        player.SetData("NEXT_BANK_TRANSFER", DateTime.Now.AddMinutes(1));
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                Log.Write(e.ToString(), nLog.Type.Error);
            }
        }
Beispiel #38
0
 public QiaoShuiWinRemoval(Player p, Trigger win)
 {
     Owner      = p;
     winTrigger = win;
 }
Beispiel #39
0
 public QiaoShuiRemoval(Player p, Trigger lose)
 {
     Owner       = p;
     loseTrigger = lose;
 }
Beispiel #40
0
        /*
        ** Process an UPDATE statement.
        **
        **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
        **          \_______/ \________/     \______/       \________________/
        *            onError   pTabList      pChanges             pWhere
        */
        static void sqlite3Update(
            Parse pParse,      /* The parser context */
            SrcList pTabList,  /* The table in which we should change things */
            ExprList pChanges, /* Things to be changed */
            Expr pWhere,       /* The WHERE clause.  May be null */
            int onError        /* How to handle constraint errors */
            )
        {
            int       i, j;                 /* Loop counters */
            Table     pTab;                 /* The table to be updated */
            int       addr = 0;             /* VDBE instruction address of the start of the loop */
            WhereInfo pWInfo;               /* Information about the WHERE clause */
            Vdbe      v;                    /* The virtual database engine */
            Index     pIdx;                 /* For looping over indices */
            int       nIdx;                 /* Number of indices that need updating */
            int       iCur;                 /* VDBE Cursor number of pTab */
            sqlite3   db;                   /* The database structure */

            int[] aRegIdx = null;           /* One register assigned to each index to be updated */
            int[] aXRef   = null;           /* aXRef[i] is the index in pChanges.a[] of the
                                            ** an expression for the i-th column of the table.
                                            ** aXRef[i]==-1 if the i-th column is not changed. */
            bool        chngRowid;          /* True if the record number is being changed */
            Expr        pRowidExpr = null;  /* Expression defining the new record number */
            bool        openAll    = false; /* True if all indices need to be opened */
            AuthContext sContext;           /* The authorization context */
            NameContext sNC;                /* The name-context to resolve expressions in */
            int         iDb;                /* Database containing the table being updated */
            bool        okOnePass;          /* True for one-pass algorithm without the FIFO */
            bool        hasFK;              /* True if foreign key processing is required */

#if !SQLITE_OMIT_TRIGGER
            bool    isView;    /* True when updating a view (INSTEAD OF trigger) */
            Trigger pTrigger;  /* List of triggers on pTab, if required */
            int     tmask = 0; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
#endif
            int newmask;       /* Mask of NEW.* columns accessed by BEFORE triggers */

            /* Register Allocations */
            int regRowCount = 0;   /* A count of rows changed */
            int regOldRowid;       /* The old rowid */
            int regNewRowid;       /* The new rowid */
            int regNew;
            int regOld    = 0;
            int regRowSet = 0;            /* Rowset of rows to be updated */

            sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) );
            db       = pParse.db;
            if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */)
            {
                goto update_cleanup;
            }
            Debug.Assert(pTabList.nSrc == 1);

            /* Locate the table which we want to update.
             */
            pTab = sqlite3SrcListLookup(pParse, pTabList);
            if (pTab == null)
            {
                goto update_cleanup;
            }
            iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);

            /* Figure out if we have any triggers and if the table being
            ** updated is a view.
            */
#if !SQLITE_OMIT_TRIGGER
            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, out tmask);
            isView   = pTab.pSelect != null;
            Debug.Assert(pTrigger != null || tmask == 0);
#else
            const Trigger pTrigger = null; //# define pTrigger 0
            const int     tmask    = 0;    //# define tmask 0
#endif
#if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW
//    # undef isView
            const bool isView = false; //# define isView 0
#endif

            if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
            {
                goto update_cleanup;
            }
            if (sqlite3IsReadOnly(pParse, pTab, tmask))
            {
                goto update_cleanup;
            }
            aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol);
            //if ( aXRef == null ) goto update_cleanup;
            for (i = 0; i < pTab.nCol; i++)
            {
                aXRef[i] = -1;
            }

            /* Allocate a cursors for the main database table and for all indices.
            ** The index cursors might not be used, but if they are used they
            ** need to occur right after the database cursor.  So go ahead and
            ** allocate enough space, just in case.
            */
            pTabList.a[0].iCursor = iCur = pParse.nTab++;
            for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
            {
                pParse.nTab++;
            }

            /* Initialize the name-context */
            sNC          = new NameContext();// memset(&sNC, 0, sNC).Length;
            sNC.pParse   = pParse;
            sNC.pSrcList = pTabList;

            /* Resolve the column names in all the expressions of the
            ** of the UPDATE statement.  Also find the column index
            ** for each column to be updated in the pChanges array.  For each
            ** column to be updated, make sure we have authorization to change
            ** that column.
            */
            chngRowid = false;
            for (i = 0; i < pChanges.nExpr; i++)
            {
                if (sqlite3ResolveExprNames(sNC, ref pChanges.a[i].pExpr) != 0)
                {
                    goto update_cleanup;
                }
                for (j = 0; j < pTab.nCol; j++)
                {
                    if (pTab.aCol[j].zName.Equals(pChanges.a[i].zName, StringComparison.OrdinalIgnoreCase))
                    {
                        if (j == pTab.iPKey)
                        {
                            chngRowid  = true;
                            pRowidExpr = pChanges.a[i].pExpr;
                        }
                        aXRef[j] = i;
                        break;
                    }
                }
                if (j >= pTab.nCol)
                {
                    if (sqlite3IsRowid(pChanges.a[i].zName))
                    {
                        chngRowid  = true;
                        pRowidExpr = pChanges.a[i].pExpr;
                    }
                    else
                    {
                        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges.a[i].zName);
                        pParse.checkSchema = 1;
                        goto update_cleanup;
                    }
                }
#if !SQLITE_OMIT_AUTHORIZATION
                {
                    int rc;
                    rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName,
                                          pTab.aCol[j].zName, db.aDb[iDb].zName);
                    if (rc == SQLITE_DENY)
                    {
                        goto update_cleanup;
                    }
                    else if (rc == SQLITE_IGNORE)
                    {
                        aXRef[j] = -1;
                    }
                }
#endif
            }

            hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid ? 1 : 0) != 0;

            /* Allocate memory for the array aRegIdx[].  There is one entry in the
            ** array for each index associated with table being updated.  Fill in
            ** the value with a register number for indices that are to be used
            ** and with zero for unused indices.
            */
            for (nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++)
            {
            }
            if (nIdx > 0)
            {
                aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx);
                if (aRegIdx == null)
                {
                    goto update_cleanup;
                }
            }
            for (j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++)
            {
                int reg;
                if (hasFK || chngRowid)
                {
                    reg = ++pParse.nMem;
                }
                else
                {
                    reg = 0;
                    for (i = 0; i < pIdx.nColumn; i++)
                    {
                        if (aXRef[pIdx.aiColumn[i]] >= 0)
                        {
                            reg = ++pParse.nMem;
                            break;
                        }
                    }
                }
                aRegIdx[j] = reg;
            }

            /* Begin generating code. */
            v = sqlite3GetVdbe(pParse);
            if (v == null)
            {
                goto update_cleanup;
            }
            if (pParse.nested == 0)
            {
                sqlite3VdbeCountChanges(v);
            }
            sqlite3BeginWriteOperation(pParse, 1, iDb);

#if !SQLITE_OMIT_VIRTUALTABLE
            /* Virtual tables must be handled separately */
            if (IsVirtual(pTab))
            {
                updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
                                   pWhere, onError);
                pWhere   = null;
                pTabList = null;
                goto update_cleanup;
            }
#endif

            /* Allocate required registers. */
            regOldRowid = regNewRowid = ++pParse.nMem;
            if (pTrigger != null || hasFK)
            {
                regOld       = pParse.nMem + 1;
                pParse.nMem += pTab.nCol;
            }
            if (chngRowid || pTrigger != null || hasFK)
            {
                regNewRowid = ++pParse.nMem;
            }
            regNew       = pParse.nMem + 1;
            pParse.nMem += pTab.nCol;

            /* Start the view context. */
            if (isView)
            {
                sqlite3AuthContextPush(pParse, sContext, pTab.zName);
            }

            /* If we are trying to update a view, realize that view into
            ** a ephemeral table.
            */
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
            if (isView)
            {
                sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
            }
#endif

            /* Resolve the column names in all the expressions in the
            ** WHERE clause.
            */
            if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0)
            {
                goto update_cleanup;
            }

            /* Begin the database scan
             */
            sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
            ExprList NullOrderby = null;
            pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED);
            if (pWInfo == null)
            {
                goto update_cleanup;
            }
            okOnePass = pWInfo.okOnePass != 0;

            /* Remember the rowid of every item to be updated.
             */
            sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
            if (!okOnePass)
            {
                regRowSet = ++pParse.nMem;
                sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
            }

            /* End the database scan loop.
             */
            sqlite3WhereEnd(pWInfo);

            /* Initialize the count of updated rows
             */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
            {
                regRowCount = ++pParse.nMem;
                sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
            }

            if (!isView)
            {
                /*
                ** Open every index that needs updating.  Note that if any
                ** index could potentially invoke a REPLACE conflict resolution
                ** action, then we need to open all indices because we might need
                ** to be deleting some records.
                */
                if (!okOnePass)
                {
                    sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
                }
                if (onError == OE_Replace)
                {
                    openAll = true;
                }
                else
                {
                    openAll = false;
                    for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
                    {
                        if (pIdx.onError == OE_Replace)
                        {
                            openAll = true;
                            break;
                        }
                    }
                }
                for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
                {
                    if (openAll || aRegIdx[i] > 0)
                    {
                        KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx);
                        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb,
                                          pKey, P4_KEYINFO_HANDOFF);
                        Debug.Assert(pParse.nTab > iCur + i + 1);
                    }
                }
            }

            /* Top of the update loop */
            if (okOnePass)
            {
                int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
                addr = sqlite3VdbeAddOp0(v, OP_Goto);
                sqlite3VdbeJumpHere(v, a1);
            }
            else
            {
                addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
            }

            /* Make cursor iCur point to the record that is being updated. If
            ** this record does not exist for some reason (deleted by a trigger,
            ** for example, then jump to the next iteration of the RowSet loop.  */
            sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

            /* If the record number will change, set register regNewRowid to
            ** contain the new value. If the record number is not being modified,
            ** then regNewRowid is the same register as regOldRowid, which is
            ** already populated.  */
            Debug.Assert(chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid);
            if (chngRowid)
            {
                sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
                sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
            }

            /* If there are triggers on this table, populate an array of registers
            ** with the required old.* column data.  */
            if (hasFK || pTrigger != null)
            {
                u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
                oldmask |= sqlite3TriggerColmask(pParse,
                                                 pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError
                                                 );
                for (i = 0; i < pTab.nCol; i++)
                {
                    if (aXRef[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i))))
                    {
                        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld + i);
                    }
                    else
                    {
                        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld + i);
                    }
                }
                if (chngRowid == false)
                {
                    sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
                }
            }

            /* Populate the array of registers beginning at regNew with the new
            ** row data. This array is used to check constaints, create the new
            ** table and index records, and as the values for any new.* references
            ** made by triggers.
            **
            ** If there are one or more BEFORE triggers, then do not populate the
            ** registers associated with columns that are (a) not modified by
            ** this UPDATE statement and (b) not accessed by new.* references. The
            ** values for registers not modified by the UPDATE must be reloaded from
            ** the database after the BEFORE triggers are fired anyway (as the trigger
            ** may have modified them). So not loading those that are not going to
            ** be used eliminates some redundant opcodes.
            */
            newmask = (int)sqlite3TriggerColmask(
                pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
                );
            for (i = 0; i < pTab.nCol; i++)
            {
                if (i == pTab.iPKey)
                {
                    sqlite3VdbeAddOp2(v, OP_Null, 0, regNew + i);
                }
                else
                {
                    j = aXRef[i];
                    if (j >= 0)
                    {
                        sqlite3ExprCode(pParse, pChanges.a[j].pExpr, regNew + i);
                    }
                    else if (0 == (tmask & TRIGGER_BEFORE) || i > 31 || (newmask & (1 << i)) != 0)
                    {
                        /* This branch loads the value of a column that will not be changed
                        ** into a register. This is done if there are no BEFORE triggers, or
                        ** if there are one or more BEFORE triggers that use this value via
                        ** a new.* reference in a trigger program.
                        */
                        testcase(i == 31);
                        testcase(i == 32);
                        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
                        sqlite3ColumnDefault(v, pTab, i, regNew + i);
                    }
                }
            }

            /* Fire any BEFORE UPDATE triggers. This happens before constraints are
            ** verified. One could argue that this is wrong.
            */
            if ((tmask & TRIGGER_BEFORE) != 0)
            {
                sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab.nCol);
                sqlite3TableAffinityStr(v, pTab);
                sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
                                      TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);

                /* The row-trigger may have deleted the row being updated. In this
                ** case, jump to the next row. No updates or AFTER triggers are
                ** required. This behaviour - what happens when the row being updated
                ** is deleted or renamed by a BEFORE trigger - is left undefined in the
                ** documentation.
                */
                sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);

                /* If it did not delete it, the row-trigger may still have modified
                ** some of the columns of the row being updated. Load the values for
                ** all columns not modified by the update statement into their
                ** registers in case this has happened.
                */
                for (i = 0; i < pTab.nCol; i++)
                {
                    if (aXRef[i] < 0 && i != pTab.iPKey)
                    {
                        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i);
                        sqlite3ColumnDefault(v, pTab, i, regNew + i);
                    }
                }
            }

            if (!isView)
            {
                int j1;               /* Address of jump instruction */

                /* Do constraint checks. */
                int iDummy;
                sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
                                                aRegIdx, (chngRowid ? regOldRowid : 0), true, onError, addr, out iDummy);

                /* Do FK constraint checks. */
                if (hasFK)
                {
                    sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
                }

                /* Delete the index entries associated with the current record.  */
                j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
                sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);

                /* If changing the record number, delete the old record.  */
                if (hasFK || chngRowid)
                {
                    sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
                }
                sqlite3VdbeJumpHere(v, j1);

                if (hasFK)
                {
                    sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
                }

                /* Insert the new index entries and the new record. */
                sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false);

                /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
                ** handle rows (possibly in other tables) that refer via a foreign key
                ** to the row just updated. */
                if (hasFK)
                {
                    sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
                }
            }

            /* Increment the row counter
             */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab)
            {
                sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
            }

            sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
                                  TRIGGER_AFTER, pTab, regOldRowid, onError, addr);

            /* Repeat the above with the next record to be updated, until
            ** all record selected by the WHERE clause have been updated.
            */
            sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
            sqlite3VdbeJumpHere(v, addr);

            /* Close all tables */
            for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++)
            {
                if (openAll || aRegIdx[i] > 0)
                {
                    sqlite3VdbeAddOp2(v, OP_Close, iCur + i + 1, 0);
                }
            }
            sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);

            /* Update the sqlite_sequence table by storing the content of the
            ** maximum rowid counter values recorded while inserting into
            ** autoincrement tables.
            */
            if (pParse.nested == 0 && pParse.pTriggerTab == null)
            {
                sqlite3AutoincrementEnd(pParse);
            }

            /*
            ** Return the number of rows that were changed. If this routine is
            ** generating code because of a call to sqlite3NestedParse(), do not
            ** invoke the callback function.
            */
            if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested)
            {
                sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
                sqlite3VdbeSetNumCols(v, 1);
                sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
            }

update_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
            sqlite3AuthContextPop(sContext);
#endif
            sqlite3DbFree(db, ref aRegIdx);
            sqlite3DbFree(db, ref aXRef);
            sqlite3SrcListDelete(db, ref pTabList);
            sqlite3ExprListDelete(db, ref pChanges);
            sqlite3ExprDelete(db, ref pWhere);
            return;
        }
Beispiel #41
0
        ControlTemplate DesignButton()
        {
            // Создание объекта ControlTemplate для Button
            ControlTemplate template = new ControlTemplate(typeof(Button));
            // Создание объекта FrameworkElementFactory для Border
            FrameworkElementFactory factoryBorder = new FrameworkElementFactory(typeof(Border));

            // Назначение имени для последующих ссылок
            factoryBorder.Name = "border";
            // Задание некоторых свойств по умолчанию
            factoryBorder.SetValue(Border.BorderBrushProperty, Brushes.Gray);
            factoryBorder.SetValue(Border.BorderThicknessProperty, new Thickness(3));
            factoryBorder.SetValue(Border.BackgroundProperty, SystemColors.ControlLightBrush);

            // Создание объекта FrameworkElementFactory для ContentPresenter
            FrameworkElementFactory factoryContent = new FrameworkElementFactory(typeof(ContentPresenter));

            // Назначение имени для последующих ссылок
            factoryContent.Name = "content";
            // Привязка свойств ContentPresenter к свойствам Button
            factoryContent.SetValue(ContentPresenter.ContentProperty, new TemplateBindingExtension(Button.ContentProperty));
            // Обратите внимание: свойство Padding кнопки
            // соответствует свойству Margin содержимого!
            factoryContent.SetValue(ContentPresenter.MarginProperty, new TemplateBindingExtension(Button.PaddingProperty));
            // Назначение ContentPresenter дочерним объектом Border
            factoryBorder.AppendChild(factoryContent);
            // Border назначается корневым узлом визуального дерева
            template.VisualTree = factoryBorder;
            // Определение триггера для условия IsMouseOver=true
            Trigger trig = new Trigger();

            trig.Property = UIElement.IsMouseOverProperty;
            trig.Value    = true;
            // Связывание объекта Setter с триггером
            // для изменения свойства CornerRadius элемента Border.
            Setter set = new Setter();

            set.Property   = Border.CornerRadiusProperty;
            set.Value      = new CornerRadius(24);
            set.TargetName = "border";
            // Включение объекта Setter в коллекцию Setters триггера
            trig.Setters.Add(set);
            // Определение объекта Setter для изменения FontStyle.
            // (Для свойства кнопки задавать TargetName не нужно.)
            set          = new Setter();
            set.Property = Control.FontStyleProperty;
            set.Value    = FontStyles.Italic;
            // Добавление в коллекцию Setters того же триггера
            trig.Setters.Add(set);
            // Включение триггера в шаблон
            template.Triggers.Add(trig);
            // Определение триггера для IsPressed
            trig           = new Trigger();
            trig.Property  = Button.IsPressedProperty;
            trig.Value     = true;
            set            = new Setter();
            set.Property   = Border.BackgroundProperty;
            set.Value      = SystemColors.ControlDarkBrush;
            set.TargetName = "border";
            // Включение объекта Setter в коллекцию Setters триггера
            trig.Setters.Add(set);
            // Включение триггера в шаблон
            template.Triggers.Add(trig);
            return(template);
        }
Beispiel #42
0
        internal async Task Show(int?overlayLeft = null, int?overlayTop = null)
        {
            if (_isOverlayShow || Trigger.Disabled)
            {
                return;
            }

            HtmlElement trigger;

            if (Trigger.ChildContent != null)
            {
                trigger = await JsInvokeAsync <HtmlElement>(JSInteropConstants.GetFirstChildDomInfo, Trigger.Ref);

                // fix bug in submenu: Overlay show when OvelayTrigger is not rendered complete.
                // I try to render Overlay when OvelayTrigger’s OnAfterRender is called, but is still get negative absoluteLeft
                // This may be a bad solution, but for now I can only do it this way.
                while (trigger.AbsoluteLeft <= 0 && trigger.ClientWidth <= 0)
                {
                    await Task.Delay(50);

                    trigger = await JsInvokeAsync <HtmlElement>(JSInteropConstants.GetFirstChildDomInfo, Trigger.Ref);
                }
            }
            else //(Trigger.Unbound != null)
            {
                trigger = await JsInvokeAsync <HtmlElement>(JSInteropConstants.GetDomInfo, Trigger.Ref);
            }

            _overlayLeft = overlayLeft;
            _overlayTop  = overlayTop;

            if (_isOverlayFirstRender)
            {
                _isWaitForOverlayFirstRender = true;

                StateHasChanged();
                return;
            }

            _isOverlayShow   = true;
            _isOverlayHiding = false;

            await UpdateParentOverlayState(true);

            await AddOverlayToBody();

            HtmlElement overlayElement = await JsInvokeAsync <HtmlElement>(JSInteropConstants.GetDomInfo, Ref);

            HtmlElement containerElement = await JsInvokeAsync <HtmlElement>(JSInteropConstants.GetDomInfo, Trigger.PopupContainerSelector);

            int left = await GetOverlayLeftWithBoundaryAdjust(trigger, overlayElement, containerElement);

            int top = await GetOverlayTopWithBoundaryAdjust(trigger, overlayElement, containerElement);

            int zIndex = await JsInvokeAsync <int>(JSInteropConstants.GetMaxZIndex);

            _overlayStyle = $"z-index:{zIndex};left: {left}px;top: {top}px;{GetTransformOrigin()}";

            _overlayCls = Trigger.GetOverlayEnterClass();

            await Trigger.OnVisibleChange.InvokeAsync(true);

            StateHasChanged();

            OnShow?.Invoke();
        }
Beispiel #43
0
        public void CanReorderTriggers()
        {
            var res = api.Triggers.GetActiveTriggers().Triggers;

            Assert.AreEqual(res.Count(), 0);

            var trigger = new Trigger()
            {
                Title      = "Test Trigger1",
                Active     = true,
                Conditions = new Conditions()
                {
                    All = new List <All>()
                    {
                        new All()
                        {
                            Field = "status", Operator = "is", Value = "open"
                        }
                    }, Any = new List <All>()
                },
                Actions = new List <Action>()
                {
                    new Action()
                    {
                        Field = "group_id", Value = "20402842"
                    }
                },
                Position = 5000
            };

            var trigger2 = new Trigger()
            {
                Title      = "Test Trigger2",
                Active     = true,
                Conditions = new Conditions()
                {
                    All = new List <All>()
                    {
                        new All()
                        {
                            Field = "status", Operator = "is", Value = "open"
                        }
                    }, Any = new List <All>()
                },
                Actions = new List <Action>()
                {
                    new Action()
                    {
                        Field = "group_id", Value = "20402842"
                    }
                },
                Position = 6000
            };

            var res2 = api.Triggers.CreateTrigger(trigger);
            var res3 = api.Triggers.CreateTrigger(trigger2);

            List <long> ids = new List <long>()
            {
                res3.Trigger.Id.Value, res2.Trigger.Id.Value
            };

            Assert.True(api.Triggers.ReorderTriggers(ids));

            res = api.Triggers.GetActiveTriggers().Triggers;

            Assert.AreEqual(res[0].Id.Value, res3.Trigger.Id.Value);

            Assert.True(api.Triggers.DeleteTrigger(res2.Trigger.Id.Value));
            Assert.True(api.Triggers.DeleteTrigger(res3.Trigger.Id.Value));
        }
Beispiel #44
0
        public static void ClientEvent_ATM(Client player, params object[] args)
        {
            try
            {
                if (Admin.IsServerStoping)
                {
                    Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Сервер сейчас не может принять это действие", 3000);
                    return;
                }
                int    act   = Convert.ToInt32(args[0]);
                string data1 = Convert.ToString(args[1]);
                var    acc   = Main.Players[player];
                int    amount;
                if (!Int32.TryParse(data1, out amount))
                {
                    return;
                }
                Log.Debug($"{player.Name} : {data1}");
                switch (act)
                {
                case 0:     //put money
                    if (Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Bank.Change(acc.Bank, amount);
                        GameLog.Money($"player({Main.Players[player].UUID})", $"bank({acc.Bank})", Math.Abs(amount), $"atmIn");
                        Trigger.ClientEvent(player, "setbank", Bank.Accounts[acc.Bank].Balance.ToString(), "");
                    }
                    break;

                case 1:     //take money
                    if (Bank.Change(acc.Bank, -Math.Abs(amount)))
                    {
                        Wallet.Change(player, amount);
                        GameLog.Money($"bank({acc.Bank})", $"player({Main.Players[player].UUID})", Math.Abs(amount), $"atmOut");
                        Trigger.ClientEvent(player, "setbank", Bank.Accounts[acc.Bank].Balance.ToString(), "");
                    }
                    break;

                case 2:     //put house tax
                    var house = Houses.HouseManager.GetHouse(player, true);
                    if (house == null)
                    {
                        return;
                    }

                    var maxMoney = Convert.ToInt32(house.Price / 100 * 0.013) * 24 * 7;
                    if (Bank.Accounts[house.BankID].Balance + Math.Abs(amount) > maxMoney)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Невозможно перевести столько средств на счет дома.", 3000);
                        return;
                    }
                    if (!Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Недостаточно средств.", 3000);
                        return;
                    }
                    Bank.Change(house.BankID, Math.Abs(amount));
                    GameLog.Money($"player({Main.Players[player].UUID})", $"bank({house.BankID})", Math.Abs(amount), $"atmHouse");
                    Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Успешный перевод.", 3000);
                    break;

                case 3:     //put biz tax
                    var check = NAPI.Data.GetEntityData(player, "bizcheck");
                    if (check == null)
                    {
                        return;
                    }
                    if (acc.BizIDs.Count != check)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Возникла ошибка! Попробуйте еще раз.", 3000);
                        return;
                    }
                    int bid = 0;
                    if (!Int32.TryParse(Convert.ToString(args[2]), out bid))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Возникла ошибка! Попробуйте еще раз.", 3000);
                        return;
                    }

                    Business biz = BusinessManager.BizList[acc.BizIDs[bid]];

                    maxMoney = Convert.ToInt32(biz.SellPrice / 100 * 0.01) * 24 * 7;
                    if (Bank.Accounts[biz.BankID].Balance + Math.Abs(amount) > maxMoney)
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Невозможно перевести столько средств на счет бизнеса.", 3000);
                        return;
                    }
                    if (!Wallet.Change(player, -Math.Abs(amount)))
                    {
                        Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Недостаточно средств.", 3000);
                        return;
                    }
                    Bank.Change(biz.BankID, Math.Abs(amount));
                    GameLog.Money($"player({Main.Players[player].UUID})", $"bank({biz.BankID})", Math.Abs(amount), $"atmBiz");
                    Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, "Успешный перевод.", 3000);
                    break;

                case 4:     //transfer to
                    int num = 0;
                    if (!Int32.TryParse(Convert.ToString(args[2]), out num))
                    {
                        return;
                    }
                    Bank.Transfer(acc.Bank, num, +Math.Abs(amount));
                    break;
                }
            }
            catch (Exception e) { Log.Write("atm: " + e.Message, nLog.Type.Error); }
        }
Beispiel #45
0
        public static void ClientEvent_ATMCB(Client player, params object[] args)
        {
            try
            {
                var acc   = Main.Players[player];
                int type  = Convert.ToInt32(args[0]);
                int index = Convert.ToInt32(args[1]);
                if (index == -1)
                {
                    Trigger.ClientEvent(player, "closeatm");
                    return;
                }
                switch (type)
                {
                case 1:
                    switch (index)
                    {
                    case 0:
                        Trigger.ClientEvent(player,
                                            "atmOpen", "[2,0,'Сумма внесения наличных']");
                        NAPI.Data.SetEntityData(player, "ATMTYPE", index);
                        break;

                    case 1:
                        Trigger.ClientEvent(player,
                                            "atmOpen", "[2,0,'Сумма для снятия']");
                        NAPI.Data.SetEntityData(player, "ATMTYPE", index);
                        break;

                    case 2:
                        if (Houses.HouseManager.GetHouse(player, true) == null)
                        {
                            Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "У вас нет дома!", 3000);
                            return;
                        }
                        var house = Houses.HouseManager.GetHouse(player, true);
                        Trigger.ClientEvent(player,
                                            "atmOpen", $"[2,'{Bank.Accounts[house.BankID].Balance}/{Convert.ToInt32(house.Price / 100 * 0.013) * 24 * 7}$','Сумма внесения наличных']");
                        Trigger.ClientEvent(player, "setatm", "Дом", $"Дом #{house.ID}", Bank.Accounts[house.BankID].Balance, "");
                        NAPI.Data.SetEntityData(player, "ATMTYPE", index);
                        break;

                    case 3:
                        AtmBizGen(player);
                        NAPI.Data.SetEntityData(player, "ATMTYPE", index);
                        break;

                    case 4:
                        Trigger.ClientEvent(player,
                                            "atmOpen", "[2,0,'Счет зачисления']");
                        NAPI.Data.SetEntityData(player, "ATMTYPE", index);
                        break;
                    }
                    break;

                case 2:
                    Trigger.ClientEvent(player, "atmOpen", "[1,0,0]");
                    Trigger.ClientEvent(player, "setatm", acc.Bank, player.Name, Bank.Accounts[acc.Bank].Balance, "");
                    break;

                case 3:
                    if (index == -1)
                    {
                        Trigger.ClientEvent(player, "atmOpen", "[1,0,0]");
                        Trigger.ClientEvent(player, "setatm", acc.Bank, player.Name, Bank.Accounts[acc.Bank].Balance, "");
                        return;
                    }
                    Business biz = BusinessManager.BizList[acc.BizIDs[index]];
                    NAPI.Data.SetEntityData(player, "ATMBIZ", index);
                    Trigger.ClientEvent(player, "atmOpen", $"[2,'{Bank.Accounts[biz.BankID].Balance}/{Convert.ToInt32(biz.SellPrice / 100 * 0.013) * 24 * 7}$','Сумма зачисления']");
                    Trigger.ClientEvent(player, "setatm",
                                        "Бизнес",
                                        BusinessManager.BusinessTypeNames[biz.Type],
                                        Bank.Accounts[biz.BankID].Balance, "");
                    break;
                }
            }
            catch (Exception e) { Log.Write("atmCB: " + e.Message, nLog.Type.Error); }
        }
        static void testClone(SBase s)
        {
            string ename = s.getElementName();
            SBase  c     = s.clone();

            if (c is Compartment)
            {
                Compartment x = (s as Compartment).clone(); c = x;
            }
            else if (c is CompartmentType)
            {
                CompartmentType x = (s as CompartmentType).clone(); c = x;
            }
            else if (c is Constraint)
            {
                Constraint x = (s as Constraint).clone(); c = x;
            }
            else if (c is Delay)
            {
                Delay x = (s as Delay).clone(); c = x;
            }
            else if (c is Event)
            {
                Event x = (s as Event).clone(); c = x;
            }
            else if (c is EventAssignment)
            {
                EventAssignment x = (s as EventAssignment).clone(); c = x;
            }
            else if (c is FunctionDefinition)
            {
                FunctionDefinition x = (s as FunctionDefinition).clone(); c = x;
            }
            else if (c is InitialAssignment)
            {
                InitialAssignment x = (s as InitialAssignment).clone(); c = x;
            }
            else if (c is KineticLaw)
            {
                KineticLaw x = (s as KineticLaw).clone(); c = x;
            }
            // currently return type of ListOf::clone() is SBase
            else if (c is ListOf)
            {
                SBase x = (s as ListOf).clone(); c = x;
            }
            else if (c is Model)
            {
                Model x = (s as Model).clone(); c = x;
            }
            else if (c is Parameter)
            {
                Parameter x = (s as Parameter).clone(); c = x;
            }
            else if (c is Reaction)
            {
                Reaction x = (s as Reaction).clone(); c = x;
            }
            else if (c is AlgebraicRule)
            {
                AlgebraicRule x = (s as AlgebraicRule).clone(); c = x;
            }
            else if (c is AssignmentRule)
            {
                AssignmentRule x = (s as AssignmentRule).clone(); c = x;
            }
            else if (c is RateRule)
            {
                RateRule x = (s as RateRule).clone(); c = x;
            }
            else if (c is SBMLDocument)
            {
                SBMLDocument x = (s as SBMLDocument).clone(); c = x;
            }
            else if (c is Species)
            {
                Species x = (s as Species).clone(); c = x;
            }
            else if (c is SpeciesReference)
            {
                SpeciesReference x = (s as SpeciesReference).clone(); c = x;
            }
            else if (c is SpeciesType)
            {
                SpeciesType x = (s as SpeciesType).clone(); c = x;
            }
            else if (c is SpeciesReference)
            {
                SpeciesReference x = (s as SpeciesReference).clone(); c = x;
            }
            else if (c is StoichiometryMath)
            {
                StoichiometryMath x = (s as StoichiometryMath).clone(); c = x;
            }
            else if (c is Trigger)
            {
                Trigger x = (s as Trigger).clone(); c = x;
            }
            else if (c is Unit)
            {
                Unit x = (s as Unit).clone(); c = x;
            }
            else if (c is UnitDefinition)
            {
                UnitDefinition x = (s as UnitDefinition).clone(); c = x;
            }
            else if (c is ListOfCompartmentTypes)
            {
                ListOfCompartmentTypes x = (s as ListOfCompartmentTypes).clone(); c = x;
            }
            else if (c is ListOfCompartments)
            {
                ListOfCompartments x = (s as ListOfCompartments).clone(); c = x;
            }
            else if (c is ListOfConstraints)
            {
                ListOfConstraints x = (s as ListOfConstraints).clone(); c = x;
            }
            else if (c is ListOfEventAssignments)
            {
                ListOfEventAssignments x = (s as ListOfEventAssignments).clone(); c = x;
            }
            else if (c is ListOfEvents)
            {
                ListOfEvents x = (s as ListOfEvents).clone(); c = x;
            }
            else if (c is ListOfFunctionDefinitions)
            {
                ListOfFunctionDefinitions x = (s as ListOfFunctionDefinitions).clone(); c = x;
            }
            else if (c is ListOfInitialAssignments)
            {
                ListOfInitialAssignments x = (s as ListOfInitialAssignments).clone(); c = x;
            }
            else if (c is ListOfParameters)
            {
                ListOfParameters x = (s as ListOfParameters).clone(); c = x;
            }
            else if (c is ListOfReactions)
            {
                ListOfReactions x = (s as ListOfReactions).clone(); c = x;
            }
            else if (c is ListOfRules)
            {
                ListOfRules x = (s as ListOfRules).clone(); c = x;
            }
            else if (c is ListOfSpecies)
            {
                ListOfSpecies x = (s as ListOfSpecies).clone(); c = x;
            }
            else if (c is ListOfSpeciesReferences)
            {
                ListOfSpeciesReferences x = (s as ListOfSpeciesReferences).clone(); c = x;
            }
            else if (c is ListOfSpeciesTypes)
            {
                ListOfSpeciesTypes x = (s as ListOfSpeciesTypes).clone(); c = x;
            }
            else if (c is ListOfUnitDefinitions)
            {
                ListOfUnitDefinitions x = (s as ListOfUnitDefinitions).clone(); c = x;
            }
            else if (c is ListOfUnits)
            {
                ListOfUnits x = (s as ListOfUnits).clone(); c = x;
            }
            else
            {
                ERR("[testClone] Error: (" + ename + ") : clone() failed.");
                return;
            }

            if (c == null)
            {
                ERR("[testClone] Error: (" + ename + ") : clone() failed.");
                return;
            }

            string enameClone = c.getElementName();

            if (ename == enameClone)
            {
                //Console.Out.WriteLine("[testClone] OK: (" + ename + ") clone(" + enameClone + ") : type match.");
                OK();
            }
            else
            {
                ERR("[testClone] Error: (" + ename + ") clone(" + enameClone + ") : type mismatch.");
            }
        }
Beispiel #47
0
        /// <summary>
        /// Returns the full schema of the database including tables, indexes, foreign keys, etc.
        /// </summary>
        /// <remarks>
        /// It's very slow for large databases
        /// </remarks>
        public static DataBaseSchema Load(DataBase database, string schemaProvider)
        {
            DataBaseSchema schema = new DataBaseSchema();
            DatabaseSchema schemaReader;

            using (var dbReader = new DatabaseSchemaReader.DatabaseReader(database.ConnectionString, schemaProvider))
            {
                dbReader.AllTables();
                dbReader.AllViews();

                try
                {
                    dbReader.AllStoredProcedures();
                }
                catch { }

                try
                {
                    dbReader.AllUsers();
                }
                catch { }

                schemaReader = dbReader.DatabaseSchema;
            }

            foreach (DatabaseTable dbt in schemaReader.Tables)
            {
                if (dbt.PrimaryKeyColumn == null)
                {
                    continue;
                }

                dbt.PrimaryKeyColumn.AddIdentity();

                var table = new Table()
                {
                    Name              = dbt.Name,
                    DataBase          = schema,
                    IdentityIncrement = dbt.PrimaryKeyColumn.IdentityDefinition.IdentityIncrement,
                    IdentitySeed      = dbt.PrimaryKeyColumn.IdentityDefinition.IdentitySeed,
                };

                schema.Tables.Add(table);
            }

            foreach (DatabaseTable dbt in schemaReader.Tables)
            {
                if (dbt.PrimaryKeyColumn == null)
                {
                    continue;
                }

                var table = schema[dbt.Name];

                foreach (DatabaseColumn dbc in dbt.Columns)
                {
                    Column column = new Column()
                    {
                        Name               = dbc.Name,
                        Table              = table,
                        Description        = dbc.Description,
                        IsNullable         = dbc.Nullable,
                        IsAutoNumber       = dbc.IsAutoNumber,
                        ComputedDefinition = dbc.ComputedDefinition,
                        DefaultValue       = dbc.DefaultValue,
                        IsPrimaryKey       = dbc.IsPrimaryKey,
                        Length             = (uint?)dbc.Length,
                        Ordinal            = dbc.Ordinal,
                        Precision          = dbc.Precision,
                        Scale              = dbc.Scale,
                    };


                    if (dbc.DataType != null)
                    {
                        column.DbType = DbTypeMapper.Parse(dbc.DataType.GetNetType());
                    }
                    else
                    {
                        if (dbc.DbDataType.StartsWith("varchar"))
                        {
                            column.DbType = DbType.AnsiString;
                        }
                        else if (dbc.DbDataType.StartsWith("int"))
                        {
                            column.DbType = DbType.Int32;
                        }
                        else if (dbc.DbDataType.StartsWith("decimal"))
                        {
                            column.DbType = DbType.Decimal;
                        }
                        else if (dbc.DbDataType.StartsWith("datetime"))
                        {
                            column.DbType = DbType.DateTime;
                        }
                        else if (dbc.DbDataType.StartsWith("money"))
                        {
                            column.DbType = DbType.Currency;
                        }
                        else if (dbc.DbDataType.StartsWith("char"))
                        {
                            column.DbType = DbType.AnsiStringFixedLength;
                        }
                        else if (dbc.DbDataType.StartsWith("text"))
                        {
                            column.DbType = DbType.AnsiString;
                        }
                    }

                    table.Columns.Add(column);
                }

                foreach (DatabaseIndex dbi in dbt.Indexes)
                {
                    Index index = new Index()
                    {
                        Name      = dbi.Name,
                        Table     = table,
                        Direction = SortDirection.Ascending,
                        Unique    = dbi.IsUnique,
                    };

                    foreach (DatabaseColumn dbc in dbi.Columns)
                    {
                        index.Columns.Add(table[dbc.Name]);
                    }

                    table.Indexes.Add(index);
                }

                foreach (DatabaseTrigger dbtr in dbt.Triggers)
                {
                    DataBaseOperation operation = DataBaseOperation.Insert;
                    Enum.TryParse <DataBaseOperation>(dbtr.TriggerEvent, true, out operation);

                    Trigger trigger = new Trigger()
                    {
                        TriggerBody  = dbtr.TriggerBody,
                        TriggerEvent = operation,
                        Table        = table,
                    };

                    table.Triggers.Add(trigger);
                }

                foreach (DatabaseConstraint dbcons in dbt.CheckConstraints)
                {
                    if (dbcons.ConstraintType == ConstraintType.Check)
                    {
                        CheckConstraint constraint = new CheckConstraint()
                        {
                            Expression = dbcons.Expression,
                            Table      = table,
                        };

                        table.CheckConstraints.Add(constraint);
                    }
                    else if (dbcons.ConstraintType == ConstraintType.ForeignKey)
                    {
                        ForeignKey foreignKey = new ForeignKey()
                        {
                            Name         = dbcons.Name,
                            DeleteAction = schema.ParseConstraintAction(dbcons.DeleteRule),
                            UpdateAction = schema.ParseConstraintAction(dbcons.UpdateRule),
                            RemoteTable  = schema[dbcons.RefersToTable],
                            Table        = table,
                        };

                        var referencedColumns = dbcons.ReferencedColumns(schemaReader).ToArray();
                        for (int i = 0; i < dbcons.Columns.Count; i++)
                        {
                            foreignKey.Columns.Add(new Tuple <Column, Column>(table[dbcons.Columns[i]], foreignKey.RemoteTable[referencedColumns[i]]));
                        }

                        table.ForeignKeys.Add(foreignKey);
                    }
                }
            }

            foreach (DatabaseView dbv in schemaReader.Views)
            {
                View view = new View()
                {
                    Name        = dbv.Name,
                    Command     = dbv.Sql,
                    Description = dbv.Description,
                    DataBase    = schema,
                };

                schema.Views.Add(view);
            }

            foreach (DatabaseUser dbu in schemaReader.Users)
            {
                User user = new User()
                {
                    Name     = dbu.Name,
                    DataBase = schema,
                };

                schema.Users.Add(user);
            }

            return(schema);
        }
Beispiel #48
0
        /// <summary>
        /// 更新会重复执行的定时任务。
        /// <see cref="https://docs.jiguang.cn/jpush/server/push/rest_api_push_schedule/#schedule_2"/>
        /// </summary>
        /// <param name="scheduleId">任务 ID</param>
        /// <param name="name">任务名称,为 null 表示不更新。</param>
        /// <param name="enabled">是否可用,为 null 表示不更新。</param>
        /// <param name="trigger">触发器对象,为 null 表示不更新。</param>
        /// <param name="pushPayload">推送内容,为 null 表示不更新。</param>
        public HttpResponse UpdatePeriodicalScheduleTask(string scheduleId, string name, bool?enabled, Trigger trigger, PushPayload pushPayload)
        {
            Task <HttpResponse> task = Task.Run(() => UpdatePeriodicalScheduleTaskAsync(scheduleId, name, enabled, trigger, pushPayload));

            task.Wait();
            return(task.Result);
        }
Beispiel #49
0
        /// <summary>
        /// 创建会在一段时间内重复执行的定期任务。
        /// <see cref="https://docs.jiguang.cn/jpush/server/push/rest_api_push_schedule/#_4"/>
        /// </summary>
        /// <param name="name">表示 schedule 任务的名字,由 schedule-api 在用户成功创建 schedule 任务后返回,不得超过 255 字节,由汉字、字母、数字、下划线组成。</param>
        /// <param name="pushPayload">推送对象</param>
        /// <param name="trigger">触发器</param>
        public HttpResponse CreatePeriodicalScheduleTask(string name, PushPayload pushPayload, Trigger trigger)
        {
            Task <HttpResponse> task = Task.Run(() => CreatePeriodicalScheduleTaskAsync(name, pushPayload, trigger));

            task.Wait();
            return(task.Result);
        }
Beispiel #50
0
        public override Style SelectStyle(object item,
                                          DependencyObject container)
        {
            Trigger trigger = new Trigger();

            trigger.Property = ListBoxItem.IsFocusedProperty;
            trigger.Value    = false;

            Style st = new Style();

            st.TargetType = typeof(ListBoxItem);

            Setter marginSetter = new Setter();

            marginSetter.Property = ListBoxItem.MarginProperty;
            marginSetter.Value    = new Thickness(0, 2, 0, 2);

            Setter backGroundSetter = new Setter();

            backGroundSetter.Property = ListBoxItem.BackgroundProperty;

            Setter focusVisualSetter = new Setter();

            focusVisualSetter.Property = ListBoxItem.FocusVisualStyleProperty;
            focusVisualSetter.Value    = null;

            ListBox listBox =
                ItemsControl.ItemsControlFromItemContainer(container)
                as ListBox;
            int index =
                listBox.ItemContainerGenerator.IndexFromContainer(container);

            Brush brush = new SolidColorBrush(Colors.Black);

            brush.Opacity = 0.20;

            backGroundSetter.Value = brush;

            st.Resources.Add(SystemColors.HighlightBrushKey, brush);
            st.Resources.Add(SystemColors.ControlBrushKey, brush);
            st.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, brush);

            /*
             * if (index % 2 == 0)
             * {
             *
             *
             *
             * }
             * else
             * {
             *  Brush brush = new SolidColorBrush(Colors.DarkGray);
             *  brush.Opacity = 0.50;
             *
             *  backGroundSetter.Value = brush;
             *
             *  st.Resources.Add(SystemColors.HighlightBrushKey, brush);
             *  st.Resources.Add(SystemColors.ControlBrushKey, brush);
             * }
             * */
            trigger.Setters.Add(backGroundSetter);

            st.Triggers.Add(trigger);

            st.Setters.Add(backGroundSetter);
            st.Setters.Add(focusVisualSetter);
            st.Setters.Add(marginSetter);

            return(st);
        }
Beispiel #51
0
 /// <summary>
 /// Sets the default triggers for that action.
 /// </summary>
 protected override void SetDefaultTriggers()
 {
     SupportedTriggers = new Trigger[1] {
         AddHiddenComponent <EventTrigger>()
     };
 }
Beispiel #52
0
 public void AddTrigger(Trigger trigger)
 {
     triggers.Add(trigger);
 }
Beispiel #53
0
        /// <summary>
        /// <see cref="CreatePeriodicalScheduleTask(string, PushPayload, Trigger)"/>
        /// </summary>
        public async Task <HttpResponse> CreatePeriodicalScheduleTaskAsync(string name, PushPayload pushPayload, Trigger trigger)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (pushPayload == null)
            {
                throw new ArgumentNullException(nameof(pushPayload));
            }

            if (trigger == null)
            {
                throw new ArgumentNullException(nameof(trigger));
            }

            JObject requestJson = new JObject
            {
                ["name"]    = name,
                ["enabled"] = true,
                ["push"]    = JObject.FromObject(pushPayload, jsonSerializer),
                ["trigger"] = new JObject()
                {
                    ["periodical"] = JObject.FromObject(trigger)
                }
            };

            return(await CreateScheduleTaskAsync(requestJson.ToString()).ConfigureAwait(false));
        }
Beispiel #54
0
 public void RemoveTrigger(Trigger trigger)
 {
     triggers.Remove(trigger);
 }
Beispiel #55
0
 public async Task <ICollection <TriggerRequirement> > GetTriggerRequirementsAsync(Trigger trigger)
 {
     VerifyManagementPermission();
     return(await _triggerRepository.GetTriggerRequirmentsAsync(trigger));
 }
Beispiel #56
0
 public OilLinesPart(PartSaveInfo inPartSaveInfo, GameObject inPart, GameObject inParent, Trigger inPartTrigger, Vector3 inPartPosition, Quaternion inPartRotation) : base(inPartSaveInfo, inPart, inParent, inPartTrigger, inPartPosition, inPartRotation)
 {
 }
Beispiel #57
0
 protected virtual bool IsContainTrigger(TriggerType triggerType)
 {
     return(Trigger.Contains(triggerType));
 }
Beispiel #58
0
        private void PactTree_Loaded(object sender, EventArgs e)
        {
            tree1.AlternationCount = 2;

            Style Containerstyle = new Style();

            Containerstyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, System.Windows.HorizontalAlignment.Stretch));
            Containerstyle.Setters.Add(new Setter(VerticalContentAlignmentProperty, System.Windows.VerticalAlignment.Center));
            Containerstyle.Setters.Add(new Setter(ListViewItem.HeightProperty, RowHeight));


            Trigger t1 = new Trigger();

            t1.Property = ItemsControl.AlternationIndexProperty;
            t1.Value    = 0;
            t1.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(AlternateBackground1)));

            Trigger t3 = new Trigger();

            t3.Property = ItemsControl.AlternationIndexProperty;
            t3.Value    = 1;
            t3.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(AlternateBackground2)));


            Trigger t2 = new Trigger();

            t2.Property = TreeListItem.IsSelectedProperty;
            t2.Value    = true;
            t2.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(SelectedItemColor)));


            Containerstyle.Triggers.Add(t1);
            Containerstyle.Triggers.Add(t3);
            Containerstyle.Triggers.Add(t2);

            tree1.ItemContainerStyle = Containerstyle;

            if (CMenu != null && Command != null)
            {
                ContextMenu menu = new ContextMenu();
                foreach (var item in CMenu)
                {
                    MenuItem CmenuItem = new MenuItem();
                    CmenuItem.Command          = Command;
                    CmenuItem.Header           = item;
                    CmenuItem.CommandParameter = item;
                    //CmenuItem.Icon = new Image() { Source="" };


                    menu.Items.Add(CmenuItem);
                }

                tree1.ContextMenu = menu;
            }

            cmbViews.ItemsSource       = Dataset.Tables[0].AsDataView();
            cmbViews.DisplayMemberPath = "ViewName";
            cmbViews.SelectedValuePath = "GridViewID";

            cmbViews.SelectedItem = cmbViews.Items[0];
        }
        public void Show(Form p, string lname, Icon icon, System.Drawing.Size size, System.Drawing.Point pos, string caption, Entry[] e, Object t)
        {
            logicalname = lname; // passed back to caller via trigger
            entries     = e;
            callertag   = t;     // passed back to caller via trigger

            ThemeableForms theme = ThemeableFormsInstance.Instance;

            FormBorderStyle = FormBorderStyle.FixedDialog;

            if (theme.WindowsFrame)
            {
                size.Height += 50;
            }

            Size = size;

            if (pos.X == -999)
            {
                StartPosition = FormStartPosition.CenterScreen;
            }
            else
            {
                Location      = pos;
                StartPosition = FormStartPosition.Manual;
            }

            Panel outer = new Panel()
            {
                Dock = DockStyle.Fill, BorderStyle = BorderStyle.FixedSingle
            };

            outer.MouseDown += FormMouseDown;

            Controls.Add(outer);

            this.Text = caption;

            Label textLabel = new Label()
            {
                Left = 4, Top = 8, Width = Width - 50, Text = caption
            };

            textLabel.MouseDown += FormMouseDown;

            if (!theme.WindowsFrame)
            {
                outer.Controls.Add(textLabel);
            }

            ToolTip tt = new ToolTip();

            tt.ShowAlways = true;
            for (int i = 0; i < entries.Length; i++)
            {
                Entry   ent = entries[i];
                Control c   = (Control)Activator.CreateInstance(ent.controltype);
                ent.control = c;
                c.Size      = ent.size;
                c.Location  = ent.pos;
                if (!(c is ExtendedControls.ComboBoxCustom))        // everything but get text
                {
                    c.Text = ent.text;
                }
                c.Tag = ent;     // point control tag at ent structure
                outer.Controls.Add(c);
                if (ent.tooltip != null)
                {
                    tt.SetToolTip(c, ent.tooltip);
                }

                if (c is ExtendedControls.ButtonExt)
                {
                    ExtendedControls.ButtonExt b = c as ExtendedControls.ButtonExt;
                    b.Click += (sender, ev) =>
                    {
                        Entry en = (Entry)(((Control)sender).Tag);
                        Trigger?.Invoke(logicalname, en.name, callertag);       // pass back the logical name of dialog, the name of the control, the caller tag
                    };
                }

                if (c is ExtendedControls.TextBoxBorder)
                {
                    ExtendedControls.TextBoxBorder tb = c as ExtendedControls.TextBoxBorder;
                    tb.Multiline = tb.WordWrap = ent.textboxmultiline;
                }

                if (c is ExtendedControls.CheckBoxCustom)
                {
                    ExtendedControls.CheckBoxCustom cb = c as ExtendedControls.CheckBoxCustom;
                    cb.Checked = ent.checkboxchecked;
                    cb.Click  += (sender, ev) =>
                    {
                        Entry en = (Entry)(((Control)sender).Tag);
                        Trigger?.Invoke(logicalname, en.name, callertag);       // pass back the logical name of dialog, the name of the control, the caller tag
                    };
                }

                if (c is ExtendedControls.ComboBoxCustom)
                {
                    ExtendedControls.ComboBoxCustom cb = c as ExtendedControls.ComboBoxCustom;
                    cb.Items.AddRange(ent.comboboxitems.Split(','));
                    if (cb.Items.Contains(ent.text))
                    {
                        cb.SelectedItem = ent.text;
                    }
                    cb.SelectedIndexChanged += (sender, ev) =>
                    {
                        Control ctr = (Control)sender;
                        if (ctr.Enabled)
                        {
                            Entry en = (Entry)(ctr.Tag);
                            Trigger?.Invoke(logicalname, en.name, callertag);       // pass back the logical name of dialog, the name of the control, the caller tag
                        }
                    };
                }
            }

            ShowInTaskbar = false;

            this.Icon = icon;

            theme.ApplyToForm(this, System.Drawing.SystemFonts.DefaultFont);

            Show(p);
        }
Beispiel #60
0
 public ShopManagerChanged(User dismissed, Shop entity, Trigger trigger, Guid userId)
     : base(entity, trigger, userId)
 {
     Dismissed = dismissed;
 }