Пример #1
0
        /// <summary>
        /// Base Constructor
        /// </summary>
        /// <param name="manager">ScreenManager</param>
        public TabControl(BaseScreenComponent manager)
            : base(manager)
        {
            Pages = new ItemCollection<TabPage>();
            Pages.OnInsert += OnInsert;
            Pages.OnRemove += OnRemove;

            tabControlGrid = new Grid(manager)
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };
            tabControlGrid.Columns.Add(new ColumnDefinition() {ResizeMode = ResizeMode.Parts, Width = 1});
            tabControlGrid.Rows.Add(new RowDefinition() {ResizeMode = ResizeMode.Auto});
            tabControlGrid.Rows.Add(new RowDefinition() {ResizeMode = ResizeMode.Parts, Height =  1});
            Content = tabControlGrid;

            tabListStack = new StackPanel(manager);
            tabListStack.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabListStack.Orientation = Orientation.Horizontal;
            tabListStack.Background = TabListBackground;
            tabControlGrid.AddControl(tabListStack, 0, 0);

            tabPage = new ContentControl(manager);
            tabPage.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabPage.VerticalAlignment = VerticalAlignment.Stretch;
            tabPage.Background = TabPageBackground;
            tabControlGrid.AddControl(tabPage, 0, 1);

            ApplySkin(typeof(TabControl));
        }
 public void ExoticCoverage()
 {
     var r = new Mock<IItemReader>(MockBehavior.Strict);
     var collection = new ItemCollection(r.Object);
     IEnumerable enumerable = collection;
     enumerable.GetEnumerator().Should().Not.Be.Null();
 }
Пример #3
0
        public void AddItem()
        {
            var collection = new ItemCollection();
            collection.Add(_itemFactory.Build(ItemCode.LightFrigate, 1));

            Assert.That(collection.Count, Is.EqualTo(1));
        }
Пример #4
0
        /// <summary>
        /// Base Constructor
        /// </summary>
        /// <param name="manager">ScreenManager</param>
        public TabControl(IScreenManager manager)
            : base(manager)
        {
            Manager = manager;

            Pages = new ItemCollection<TabPage>();
            Pages.OnInsert += OnInsert;
            Pages.OnRemove += OnRemove;

            tabControlStack = new StackPanel(manager);
            tabControlStack.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabControlStack.VerticalAlignment = VerticalAlignment.Stretch;
            Content = tabControlStack;

            tabListStack = new StackPanel(manager);
            tabListStack.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabListStack.Orientation = Orientation.Horizontal;
            tabListStack.Background = TabListBackground;
            tabControlStack.Controls.Add(tabListStack);

            tabPage = new ContentControl(manager);
            tabPage.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabPage.VerticalAlignment = VerticalAlignment.Stretch;
            tabPage.Margin = new Border(0, 10, 0, 10);
            tabPage.Background = TabPageBackground;
            tabControlStack.Controls.Add(tabPage);
            tabPage.Margin = new Border(0, -50, 0, 0);

            ApplySkin(typeof(TabControl));
        }
Пример #5
0
 /// <summary>
 /// Deserialization constructor for root category only.
 /// </summary>
 /// <param name="src">Source Serializable Market Group</param>
 private MarketGroup(SerializableMarketGroup src)
 {
     ID = src.ID;
     Name = src.Name;
     SubGroups = new MarketGroupCollection(this, src.SubGroups);
     Items = new ItemCollection(this, src.Items);
 }
		public override void Initialize (OptionsDialog dialog, object dataObject)
		{
			base.Initialize (dialog, dataObject);

			config = (SolutionRunConfigInfo)dataObject;

			store = new ListStore (selectedField, projectNameField, projectField, runConfigField, projectRunConfigsField);
			listView = new ListView (store);

			var col1 = new ListViewColumn (GettextCatalog.GetString ("Solution Item"));
			var cb = new CheckBoxCellView (selectedField);
			cb.Toggled += SelectionChanged;
			cb.Editable = true;
			col1.Views.Add (cb);
			col1.Views.Add (new TextCellView (projectNameField));
			listView.Columns.Add (col1);

			var configSelView = new ComboBoxCellView (runConfigField);
			configSelView.Editable = true;
			configSelView.ItemsField = projectRunConfigsField;
			var col2 = new ListViewColumn (GettextCatalog.GetString ("Run Configuration"), configSelView);
			listView.Columns.Add (col2);

			foreach (var it in config.Solution.GetAllSolutionItems ().Where (si => si.SupportsExecute ()).OrderBy (si => si.Name)) {
				var row = store.AddRow ();
				var si = config.EditedConfig.Items.FirstOrDefault (i => i.SolutionItem == it);
				var sc = si?.RunConfiguration?.Name ?? it.GetDefaultRunConfiguration ()?.Name;
				var configs = new ItemCollection ();
				foreach (var pc in it.GetRunConfigurations ())
					configs.Add (pc.Name);
				store.SetValues (row, selectedField, si != null, projectNameField, it.Name, projectField, it, runConfigField, sc, projectRunConfigsField, configs);
			}
		}
        internal FunctionImportMappingNonComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<List<FunctionImportStructuralTypeMapping>> structuralTypeMappingsList,
            ItemCollection itemCollection)
            : base(functionImport, targetFunction)
        {
            //Contract.Requires(structuralTypeMappingsList != null);
            //Contract.Requires(itemCollection != null);
            Debug.Assert(!functionImport.IsComposableAttribute, "!functionImport.IsComposableAttribute");
            Debug.Assert(!targetFunction.IsComposableAttribute, "!targetFunction.IsComposableAttribute");

            if (structuralTypeMappingsList.Count == 0)
            {
                ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    new[]
                        {
                            new FunctionImportStructuralTypeMappingKB(new List<FunctionImportStructuralTypeMapping>(), itemCollection)
                        });
                noExplicitResultMappings = true;
            }
            else
            {
                Debug.Assert(functionImport.ReturnParameters.Count == structuralTypeMappingsList.Count);
                ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    structuralTypeMappingsList
                        .Select(
                            (structuralTypeMappings) => new FunctionImportStructuralTypeMappingKB(
                                                            structuralTypeMappings,
                                                            itemCollection))
                        .ToArray());
                noExplicitResultMappings = false;
            }
        }
        internal FunctionImportMappingNonComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<List<FunctionImportStructuralTypeMapping>> structuralTypeMappingsList,
            ItemCollection itemCollection)
            : base(functionImport, targetFunction)
        {
            EntityUtil.CheckArgumentNull(structuralTypeMappingsList, "structuralTypeMappingsList");
            EntityUtil.CheckArgumentNull(itemCollection, "itemCollection");
            Debug.Assert(!functionImport.IsComposableAttribute, "!functionImport.IsComposableAttribute");
            Debug.Assert(!targetFunction.IsComposableAttribute, "!targetFunction.IsComposableAttribute");

            if (structuralTypeMappingsList.Count == 0)
            {
                this.ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    new FunctionImportStructuralTypeMappingKB[] { 
                        new FunctionImportStructuralTypeMappingKB(new List<FunctionImportStructuralTypeMapping>(), itemCollection) });
                this.noExplicitResultMappings = true;
            }
            else
            {
                Debug.Assert(functionImport.ReturnParameters.Count == structuralTypeMappingsList.Count);
                this.ResultMappings = new OM.ReadOnlyCollection<FunctionImportStructuralTypeMappingKB>(
                    EntityUtil.CheckArgumentNull(structuralTypeMappingsList, "structuralTypeMappingsList")
                        .Select((structuralTypeMappings) => new FunctionImportStructuralTypeMappingKB(
                            EntityUtil.CheckArgumentNull(structuralTypeMappings, "structuralTypeMappings"),
                            itemCollection))
                        .ToArray());
                this.noExplicitResultMappings = false;
            }
        }
Пример #9
0
        public ListViewCombos()
        {
            ListView list = new ListView ();
            var indexField = new DataField<int> ();

            var indexField2 = new DataField<int> ();
            var itemsField = new DataField<ItemCollection> ();

            ListStore store = new ListStore (indexField, indexField2, itemsField);
            list.DataSource = store;
            list.GridLinesVisible = GridLines.Horizontal;

            var comboCellView = new ComboBoxCellView { Editable = true, SelectedIndexField = indexField };
            comboCellView.Items.Add (1, "one");
            comboCellView.Items.Add (2, "two");
            comboCellView.Items.Add (3, "three");

            list.Columns.Add (new ListViewColumn ("List 1", comboCellView));

            var comboCellView2 = new ComboBoxCellView { Editable = true, SelectedIndexField = indexField2, ItemsField = itemsField };
            list.Columns.Add (new ListViewColumn ("List 2", comboCellView2));

            int p = 0;
            for (int n = 0; n < 10; n++) {
                var r = store.AddRow ();
                store.SetValue (r, indexField, n % 3);
                var col = new ItemCollection ();
                for (int i = 0; i < 3; i++) {
                    col.Add (p, "p" + p);
                    p++;
                }
                store.SetValues (r, indexField2, n % 3, itemsField, col);
            }
            PackStart (list, true);
        }
 public ItemCollection GetValues()
 {
     ItemCollection sizes = new ItemCollection();
     sizes.Add(Smile.INNERBRACE,"Inner");
     sizes.Add(Smile.OUTERBRACE, "Outer");
     return sizes;
 }
Пример #11
0
        public void ContainsItemWhenMore()
        {
            var collection = new ItemCollection {Item(quantity:5)};

            Assert.IsTrue(collection.Contains(Item(quantity:5)));
            Assert.IsTrue(collection.Contains(Item(quantity:4)));
        }
Пример #12
0
        public void ContainsItem()
        {
            var item = Item();
            var collection = new ItemCollection {item};

            Assert.IsTrue(collection.Contains(item));
        }
Пример #13
0
 /// <summary>
 /// Deserialization constructor for root category only
 /// </summary>
 /// <param name="src">Source Serializable Market Group</param>
 public MarketGroup(SerializableMarketGroup src)
 {
     m_id = src.ID;
     m_name = src.Name;
     m_subCategories = new MarketGroupCollection(this, src.SubGroups);
     m_items = new ItemCollection(this, src.Items);
 }
Пример #14
0
    public Catalog(Database db,
			string name,
			string table,
			string shortDescription,
			string longDescription,
			string image,
			int weight)
    {
        this.database = db;
        this.name   = name;
        this.table  = table;
        this.itemCollection = new ItemCollection (db, table, name);
        itemCollection.OnChanged += ItemCollectionChanged;

        this.shortDescription = shortDescription;
        this.longDescription = longDescription;
        this.weight = weight;

        this.image = new Gtk.Image();
        try {
            this.image.FromPixbuf = Pixbuf.LoadFromResource (image);
        }
        catch {
            this.image = null;
        }
    }
 public ToolboxItemsTab(ItemCollection items)
 {
     this._items = items;
     this.Text = "Toolbox Items";
     this.AllowDelete = false;
     this.Owner = items.Owner;
 }
 public ItemCollection GetValues()
 {
     ItemCollection sizes = new ItemCollection();
     for(var i = 1; i < 33; i++){
     sizes.Add(""+i);
     }
     return sizes;
 }
Пример #17
0
        public void CannotRemoveMoreThanWhatWeHave()
        {
            var collection = new ItemCollection {Item(quantity:5)};
            Assert.That(collection.Remove(Item(quantity:6)), Is.False);

            Assert.That(collection.Count, Is.EqualTo(1));
            Assert.That(collection.ItemCount, Is.EqualTo(5));
        }
Пример #18
0
        public void Clear()
        {
            var item = Item();
            var collection = new ItemCollection {item};
            collection.Clear();

            Assert.That(collection, Is.Empty);
        }
 /// <summary>
 /// Gets all (concrete) entity types implied by this type mapping.
 /// </summary>
 internal IEnumerable<EntityType> GetMappedEntityTypes(ItemCollection itemCollection)
 {
     const bool includeAbstractTypes = false;
     return this.EntityTypes.Concat(
         this.IsOfTypeEntityTypes.SelectMany(entityType =>
             MetadataHelper.GetTypeAndSubtypesOf(entityType, itemCollection, includeAbstractTypes)
             .Cast<EntityType>()));
 }
Пример #20
0
        public void AddItemOfSameType()
        {
            var collection = new ItemCollection();
            collection.Add(Item());
            collection.Add(Item(quantity:2));

            Assert.That(collection.ItemCount, Is.EqualTo(3));
        }
Пример #21
0
 public EntityMinecartChest (TypedEntity e)
     : base(e)
 {
     EntityMinecartChest e2 = e as EntityMinecartChest;
     if (e2 != null) {
         _items = e2._items.Copy();
     }
 }
Пример #22
0
        public Form()
        {
            items = new ItemCollection();
            materials = new MaterialCollection();
            blocks = new BlockCollection(items, materials);

            InitializeComponent();
        }
	    public ProtobuildModule ()
	    {
            shadowSolutions = new Dictionary<string, Solution> ();
			Packages = new ProtobuildPackages(this);
			Submodules = new ItemCollection<ProtobuildSubmodule>();
			Definitions = new ItemCollection<IProtobuildDefinition>();
			Initialize(this);
        }
Пример #24
0
        public Parser(byte[] source)
        {
            if (source == null || source.Length <= 0) {
                return;
            }
            this.source = source;

            items = new ItemCollection();
            // преобразуем данные в текст
            string sourceString = GetSourceAsString();

            // при запросе
            // первая строка содержит метод запроса, путь и версию HTTP протокола
            string httpInfo = sourceString.Substring(0, sourceString.IndexOf("\r\n"));
            var myReg = new Regex(@"(?<method>.+)\s+(?<path>.+)\s+HTTP/(?<version>[\d\.]+)", RegexOptions.Multiline);
            if (myReg.IsMatch(httpInfo)) {
                Match m = myReg.Match(httpInfo);
                if (m.Groups["method"].Value.ToUpper() == "POST") {
                    method = MethodsList.POST;
                } else if (m.Groups["method"].Value.ToUpper() == "CONNECT") {
                    method = MethodsList.CONNECT;
                } else {
                    method = MethodsList.GET;
                }
                // или можно определить метод вот так
                // _Method = (MethodsList)Enum.Parse(typeof(MethodsList), m.Groups["method"].Value.ToUpper());
                // но надежней всеже использовать условие

                path = m.Groups["path"].Value;
                httpVersion = m.Groups["version"].Value;
            } else {
                // при ответе
                // первая строка содержит код состояния
                myReg = new Regex(@"HTTP/(?<version>[\d\.]+)\s+(?<status>\d+)\s*(?<msg>.*)", RegexOptions.Multiline);
                Match m = myReg.Match(httpInfo);
                int.TryParse(m.Groups["status"].Value, out statusCode);
                statusMessage = m.Groups["msg"].Value;
                httpVersion = m.Groups["version"].Value;
            }

            // выделяем заголовки (до первых двух переводов строк)
            headersTail = sourceString.IndexOf("\r\n\r\n");
            if (headersTail != -1) {
                // хвост найден, отделяем заголовки
                sourceString = sourceString.Substring(sourceString.IndexOf("\r\n") + 2, headersTail - sourceString.IndexOf("\r\n") - 2);
            }

            // парсим заголовки и заносим их в коллекцию
            myReg = new Regex(@"^(?<key>[^\x3A]+)\:\s{1}(?<value>.+)$", RegexOptions.Multiline);
            MatchCollection mc = myReg.Matches(sourceString);
            foreach (Match mm in mc) {
                string key = mm.Groups["key"].Value;
                if (!items.ContainsKey(key)) {
                    // если указанного заголовка нет в коллекции, добавляем его
                    items.AddItem(key, mm.Groups["value"].Value.Trim("\r\n ".ToCharArray()));
                }
            }
        }
Пример #25
0
		public ItemCollection GetValues()
		{
			var items = new ItemCollection();

			foreach (var s in Enumerator.GetNames<ProxyTypes>())
				items.Add(s);

			return items;
		}
Пример #26
0
        public ItemCollection GetValues()
        {
            var items = new ItemCollection();

            for (int waveInDevice = 0; waveInDevice < WaveIn.DeviceCount; waveInDevice++)
                items.Add(waveInDevice, WaveIn.GetCapabilities(waveInDevice).ProductName);

            return items;
        }
		public ProtobuildSubmodule (ProtobuildModuleInfo latestModuleInfo, ProtobuildModuleInfo submodule, SolutionFolder rootFolder)
        {
            parentModule = latestModuleInfo;
            currentModule = submodule;
			RootFolder = rootFolder;
			Packages = new ProtobuildPackages(this);
			Definitions = new ItemCollection<IProtobuildDefinition>();
			Submodules = new ItemCollection<ProtobuildSubmodule>();
		}
Пример #28
0
        protected Structure(ILocation orbiting, Corporation owner)
            : base(orbiting)
        {
            Owner = owner;

            this.ships = new ObjectCollection<Ship>(this);
            this.personnel = new ObjectCollection<Agent>(this);
            this.stores = new ItemCollection<IItem>();
        }
Пример #29
0
		public void Test_FindInsertionPoint_empty_list()
		{
			var items = new ItemCollection<Foo>();

			var comparison = new Comparison<Foo>((x, y) => string.CompareOrdinal(x.Name, y.Name));

			// insertion point is always zero
			Assert.AreEqual(0, items.FindInsertionPoint(new Foo("a"), comparison));
			Assert.AreEqual(0, items.FindInsertionPoint(new Foo("d"), comparison));
		}
Пример #30
0
        public void AddSubItemWithLocation()
        {
            var collection = new ItemCollection(_owner);
            var hangar = new ItemCollection(collection, location:_manufactory);

            hangar.Add(_itemFactory.Build(ItemCode.LightFrigate, 1));

            var item = hangar.First();
            Assert.That(item.Location, Is.EqualTo(_manufactory));
        }
 public void RemoveCollection(ItemCollection ic)
 {
     NestedCollectionList.Remove(ic);
     ic.ParentCollection = null;
 }
 public void RemoveCollection(ItemCollection e)
 {
     CollectionList.Remove(e);
     e.ParentContainer = null;
 }
Пример #33
0
 public Base()
 {
     Items = new ItemCollection();
 }
Пример #34
0
        void Update()
        {
            // Automatically update weapons from inventory when PlayerEntity available
            if (playerEntity != null)
            {
                UpdateHands();
            }
            else
            {
                playerEntity = GameManager.Instance.PlayerEntity;
            }

            // Reset variables if there isn't an attack ongoing
            if (!IsWeaponAttacking())
            {
                // If an attack with a bow just finished, set cooldown
                if (ScreenWeapon.WeaponType == WeaponTypes.Bow && isAttacking)
                {
                    cooldownTime = Time.time + FormulaHelper.GetBowCooldownTime(playerEntity);
                }

                isAttacking        = false;
                isDamageFinished   = false;
                isBowSoundFinished = false;
            }

            // Do nothing while weapon cooldown. Used for bow.
            if (Time.time < cooldownTime)
            {
                return;
            }

            // Do nothing if player paralyzed or is climbing
            if (GameManager.Instance.PlayerEntity.IsParalyzed || GameManager.Instance.ClimbingMotor.IsClimbing)
            {
                ShowWeapons(false);
                return;
            }

            bool doToggleSheath = false;

            // Hide weapons and do nothing if spell is ready or cast animation in progress
            if (GameManager.Instance.PlayerEffectManager)
            {
                if (GameManager.Instance.PlayerEffectManager.HasReadySpell || GameManager.Instance.PlayerSpellCasting.IsPlayingAnim)
                {
                    if (!isAttacking && InputManager.Instance.ActionStarted(InputManager.Actions.ReadyWeapon))
                    {
                        GameManager.Instance.PlayerEffectManager.AbortReadySpell();

                        //if currently unsheathed, then sheath it, so we can give the effect of unsheathing it again
                        if (!Sheathed)
                        {
                            ToggleSheath();
                        }

                        doToggleSheath = true;
                    }
                    else
                    {
                        ShowWeapons(false);
                        return;
                    }
                }
            }

            // Toggle weapon sheath
            if (doToggleSheath || (!isAttacking && InputManager.Instance.ActionStarted(InputManager.Actions.ReadyWeapon)))
            {
                ToggleSheath();
            }

            // Toggle weapon hand
            if (!isAttacking && InputManager.Instance.ActionComplete(InputManager.Actions.SwitchHand))
            {
                ToggleHand();
            }

            // Do nothing if weapon isn't done equipping
            if ((usingRightHand && EquipCountdownRightHand != 0) ||
                (!usingRightHand && EquipCountdownLeftHand != 0))
            {
                ShowWeapons(false);
                return;
            }

            // Do nothing if weapons sheathed
            if (Sheathed)
            {
                ShowWeapons(false);
                return;
            }
            else
            {
                ShowWeapons(true);
            }

            // Get if bow is equipped
            bool bowEquipped = (ScreenWeapon && ScreenWeapon.WeaponType == WeaponTypes.Bow);

            // Handle beginning a new attack
            if (!isAttacking)
            {
                if (!DaggerfallUnity.Settings.ClickToAttack || bowEquipped)
                {
                    // Reset tracking if user not holding down 'SwingWeapon' button and no attack in progress
                    if (!InputManager.Instance.HasAction(InputManager.Actions.SwingWeapon))
                    {
                        lastAttackHand = Hand.None;
                        _gesture.Clear();
                        return;
                    }
                }
                else
                {
                    // Player must click to attack
                    if (InputManager.Instance.ActionStarted(InputManager.Actions.SwingWeapon))
                    {
                        isClickAttack = true;
                    }
                    else
                    {
                        _gesture.Clear();
                        return;
                    }
                }
            }

            var attackDirection = MouseDirections.None;

            if (!isAttacking)
            {
                if (bowEquipped)
                {
                    // Ensure attack button was released before starting the next attack
                    if (lastAttackHand == Hand.None)
                    {
                        attackDirection = DaggerfallUnity.Settings.BowDrawback ? MouseDirections.Up : MouseDirections.Down; // Force attack without tracking a swing for Bow
                    }
                }
                else if (isClickAttack)
                {
                    attackDirection = (MouseDirections)UnityEngine.Random.Range((int)MouseDirections.Left, (int)MouseDirections.DownRight + 1);
                    isClickAttack   = false;
                }
                else
                {
                    attackDirection = TrackMouseAttack(); // Track swing direction for other weapons
                }
            }
            if (isAttacking && bowEquipped && DaggerfallUnity.Settings.BowDrawback && ScreenWeapon.GetCurrentFrame() == 3)
            {
                if (InputManager.Instance.HasAction(InputManager.Actions.ActivateCenterObject) || ScreenWeapon.GetAnimTime() > MaxBowHeldDrawnSeconds)
                {   // Un-draw the bow without releasing an arrow.
                    ScreenWeapon.ChangeWeaponState(WeaponStates.Idle);
                }
                else if (!InputManager.Instance.HasAction(InputManager.Actions.SwingWeapon))
                {   // Release arrow. Debug.Log("Release arrow!");
                    attackDirection = MouseDirections.Down;
                }
            }

            // Start attack if one has been initiated
            if (attackDirection != MouseDirections.None)
            {
                ExecuteAttacks(attackDirection);
                isAttacking = true;
            }

            // Stop here if no attack is happening
            if (!isAttacking)
            {
                return;
            }

            if (!isBowSoundFinished && ScreenWeapon.WeaponType == WeaponTypes.Bow && ScreenWeapon.GetCurrentFrame() == 4)
            {
                ScreenWeapon.PlaySwingSound();
                isBowSoundFinished = true;

                // Remove arrow
                ItemCollection      playerItems = playerEntity.Items;
                DaggerfallUnityItem arrow       = playerItems.GetItem(ItemGroups.Weapons, (int)Weapons.Arrow);
                playerItems.RemoveOne(arrow);
            }
            else if (!isDamageFinished && ScreenWeapon.GetCurrentFrame() == ScreenWeapon.GetHitFrame())
            {
                // Racial override can suppress optional attack voice
                RacialOverrideEffect racialOverride = GameManager.Instance.PlayerEffectManager.GetRacialOverrideEffect();
                bool suppressCombatVoices           = racialOverride != null && racialOverride.SuppressOptionalCombatVoices;

                // Chance to play attack voice
                if (DaggerfallUnity.Settings.CombatVoices && !suppressCombatVoices && ScreenWeapon.WeaponType != WeaponTypes.Bow && Dice100.SuccessRoll(20))
                {
                    ScreenWeapon.PlayAttackVoice();
                }

                // Transfer damage.
                bool hitEnemy = false;

                // Non-bow weapons
                if (ScreenWeapon.WeaponType != WeaponTypes.Bow)
                {
                    MeleeDamage(ScreenWeapon, out hitEnemy);
                }
                // Bow weapons
                else
                {
                    DaggerfallMissile missile = Instantiate(ArrowMissilePrefab);
                    if (missile)
                    {
                        missile.Caster      = GameManager.Instance.PlayerEntityBehaviour;
                        missile.TargetType  = TargetTypes.SingleTargetAtRange;
                        missile.ElementType = ElementTypes.None;
                        missile.IsArrow     = true;

                        lastBowUsed = usingRightHand ? currentRightHandWeapon : currentLeftHandWeapon;;
                    }
                }

                // Fatigue loss
                playerEntity.DecreaseFatigue(swingWeaponFatigueLoss);

                // Play swing sound if attack didn't hit an enemy.
                if (!hitEnemy && ScreenWeapon.WeaponType != WeaponTypes.Bow)
                {
                    ScreenWeapon.PlaySwingSound();
                }
                else
                {
                    // Tally skills
                    if (ScreenWeapon.WeaponType == WeaponTypes.Melee || ScreenWeapon.WeaponType == WeaponTypes.Werecreature)
                    {
                        playerEntity.TallySkill(DFCareer.Skills.HandToHand, 1);
                    }
                    else if (usingRightHand && (currentRightHandWeapon != null))
                    {
                        playerEntity.TallySkill(currentRightHandWeapon.GetWeaponSkillID(), 1);
                    }
                    else if (currentLeftHandWeapon != null)
                    {
                        playerEntity.TallySkill(currentLeftHandWeapon.GetWeaponSkillID(), 1);
                    }

                    playerEntity.TallySkill(DFCareer.Skills.CriticalStrike, 1);
                }
                isDamageFinished = true;
            }
        }
Пример #35
0
        private void ToolBar_RunButton_OnLeftMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (clearDebugWindowOnRun)
            {
                debugTextBox.Clear();
            }

            ((Rectangle)sender).Fill = new SolidColorBrush(Color.FromArgb((int)((20f / 100f) * 255), 0, 0, 0));

            Grid           selectedShaderSetGrid = ((Grid)shaderSetTabControl.SelectedContent);
            TabControl     conTabCntl            = (TabControl)selectedShaderSetGrid.Children[0];
            ItemCollection iCol = conTabCntl.Items;

            TabItem vertexShaderTabItem   = ((TabItem)iCol[0]);
            TabItem fragmentShaderTabItem = ((TabItem)iCol[1]);

            RichTextBox vertexLineNumberBox   = ((RichTextBox)((Grid)vertexShaderTabItem.Content).Children[0]);
            RichTextBox fragmentLineNumberBox = ((RichTextBox)((Grid)fragmentShaderTabItem.Content).Children[0]);

            string CvertexShaderSaveLocation   = vertexShaderTabItem.Header.ToString();
            string CfragmentShaderSaveLocation = fragmentShaderTabItem.Header.ToString();

            if (CvertexShaderSaveLocation != string.Empty && CfragmentShaderSaveLocation != string.Empty &&
                CvertexShaderSaveLocation != "Vertex Shader" && CfragmentShaderSaveLocation != "Fragment Shader")
            {
                process = new Process();
                process.StartInfo.FileName               = @"ShaderTool.exe";
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardInput  = true;
                process.StartInfo.RedirectStandardOutput = true;
                string vertexLocation   = "\"" + vertexShaderSaveLocation + "\"";
                string fragmentLocation = "\"" + fragmentShaderSaveLocation + "\"";
                process.StartInfo.Arguments = vertexShaderSaveLocation + " " + fragmentShaderSaveLocation;
                process.Start();
                StringBuilder completeLog = new StringBuilder();
                while (!process.StandardOutput.EndOfStream)
                {
                    string line = process.StandardOutput.ReadLine();
                    completeLog.Append(line + Environment.NewLine);
                }
                completeLog       = completeLog.Replace(Environment.NewLine + Environment.NewLine, " ");
                debugTextBox.Text = completeLog.ToString();
                ErrorData[] errors            = ProcessConsoleString(completeLog.ToString()).ToArray();
                List <int>  vertexErrorLine   = new List <int>();
                List <int>  fragmentErrorLine = new List <int>();
                foreach (ErrorData edata in errors)
                {
                    if (edata.shaderType == TextEditorTypeAndScrollHelper.ShaderType.VERTEX)
                    {
                        vertexErrorLine.Add(edata.lineNumber);
                    }
                    if (edata.shaderType == TextEditorTypeAndScrollHelper.ShaderType.FRAGMENT)
                    {
                        fragmentErrorLine.Add(edata.lineNumber);
                    }
                }
                if (vertexErrorLine.Count > 0)
                {
                    lineNumberLinks.Add(new LineNumberErrorLink(vertexLineNumberBox, vertexErrorLine));
                    SetUpLineErrorDisplay(vertexLineNumberBox, vertexErrorLine);
                }
                if (fragmentErrorLine.Count > 0)
                {
                    lineNumberLinks.Add(new LineNumberErrorLink(fragmentLineNumberBox, fragmentErrorLine));
                    SetUpLineErrorDisplay(fragmentLineNumberBox, fragmentErrorLine);
                }
            }
            else
            {
                SavedFileModalWindow("Cannot Run Shaders", "Save all shaders in shader set to file, Then Run", "OK");
            }
        }
Пример #36
0
        private void FileSave_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();

            dialog.Filter = FilterTxt + "|" +
                            FilterJson + "|" +
                            FilterXml + "|" +
                            FilterSoap + "|" +
                            FilterBinary;

            dialog.FilterIndex = 1;

            bool?dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }

                // get content from UI control
                string content = "";

                // determine which format the user want to save as
                if (dialog.FilterIndex == 1)
                {
                    // write as txt
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    List <TodoTask>        items  = new List <TodoTask>();
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }

                    foreach (var item in items)
                    {
                        writer.WriteLine(item.Description);
                    }

                    /* writer.WriteLine(DateTime.Now);   // write last saved
                     * writer.Write(content);            // write content */
                    content = writer.ToString();      // assign assembled content

                    writer.Dispose();                 // release writer
                }
                else if (dialog.FilterIndex == 2)
                {
                    System.IO.StringWriter       writer = new System.IO.StringWriter();
                    System.Collections.ArrayList list   = new System.Collections.ArrayList();
                    ItemCollection items = this.TodoTaskListView.Items;
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }



                    // write as JSON
                    // create object to serialize


                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }
                    Models.TodoTask document = new Models.TodoTask(content);
                    // serialize type (Models.Document) to JSON string
                    string json = Newtonsoft
                                  .Json
                                  .JsonConvert
                                  .SerializeObject(document);
                    // set content to JSON result
                    content = json;                   // assign JSON string to content
                }

                else if (dialog.FilterIndex == 3)
                {
                    // write as XML
                    // create object to serialize
                    List <TodoTask> list  = new List <TodoTask>();
                    ItemCollection  items = this.TodoTaskListView.Items;

                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }

                    // create serializer
                    System.Xml.Serialization.XmlSerializer serializer =
                        new System.Xml.Serialization.XmlSerializer(typeof(List <ToDoApp.Wpf.Models.TodoTask>));
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, list);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);   // reset stream to start

                    // read content from stream
                    System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                    content = reader.ReadToEnd(); // assign XML string to content

                    reader.Dispose();             // dispose the reader
                    stream.Dispose();             // dispose the stream
                }
                else if (dialog.FilterIndex == 4)
                {
                    // write as SOAP
                    // note: have to add a reference to a global assembly (dll) to use in project
                    //create object to serialize

                    // todo
                    System.Collections.ArrayList list = new System.Collections.ArrayList();
                    ItemCollection items = this.TodoTaskListView.Items;

                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }



                    // create serializer
                    System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                        new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, list);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);   // reset stream to start

                    // read content from stream
                    System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                    content = reader.ReadToEnd(); // assign SOAP string to content

                    reader.Dispose();             // dispose the reader
                    stream.Dispose();             // dispose the stream
                }
                else // implies this is last one (binary)
                {
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    List <TodoTask>        items  = new List <TodoTask>();
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }

                    foreach (var item in items)
                    {
                        writer.WriteLine(item.Description);
                    }

                    // write as binary
                    // create object to serialize
                    Models.TodoTask document = new Models.TodoTask(content);
                    // create serializer
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
                        new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, document);

                    stream.Seek(0, System.IO.SeekOrigin.Begin);         // reset stream to start
                    // reading and writing binary data directly as string has issues, try not to do it
                    content = Convert.ToBase64String(stream.ToArray()); // assign base64 to content

                    stream.Dispose();                                   // dispose the stream
                }

                // write content to file
                System.IO.File.WriteAllText(filePath, content);

                /* string path = "output.txt";
                 * if (System.IO.File.Exists(path))
                 * {
                 *   File.Delete(path); //deletes the old file, creating a new list
                 *
                 *   System.IO.FileStream fileStream = System.IO.File.Open(
                 *   path,
                 *   System.IO.FileMode.Append,
                 *   System.IO.FileAccess.Write,
                 *   System.IO.FileShare.None);
                 *   System.IO.StreamWriter writer = new System.IO.StreamWriter(fileStream);
                 *
                 *   foreach (var item in TodoTaskListView.Items)
                 *   {
                 *       TodoTask listitem = item as TodoTask;
                 *       writer.WriteLine(listitem.Description);
                 *   }
                 *
                 *   writer.Close();
                 *   fileStream.Close();
                 * }
                 * else
                 * {
                 *   System.IO.StreamWriter writer = new System.IO.StreamWriter(path);
                 *
                 *   foreach (var item in TodoTaskListView.Items)
                 *   {
                 *       TodoTask listitem = item as TodoTask;
                 *       writer.WriteLine(listitem.Description);
                 *       //
                 *   }
                 *
                 *   writer.Close();
                 * }*/
            }
        }
Пример #37
0
 /// <summary>
 /// 检查是否已经注册
 /// </summary>
 /// <param name="componentAppId"></param>
 /// <returns></returns>
 public new static bool CheckRegistered(string componentAppId)
 {
     return(ItemCollection.CheckExisted(componentAppId));
 }
        //자식의 범위값 체크;
        private bool checkRangeofChild(ItemCollection item, float min, float max)
        {
            bool  isError      = false; //결과
            int   index        = 0;     //인덱스
            float bound        = min;   //경계 값을 저장
            bool  includeBound = false; //경계 값을 포함하는 여부를 저장

            //빨간색 해지 및 개수 계산
            foreach (NumericTreeViewItem child in item)
            {
                child.Foreground = Brushes.Black;
            }


            //에러 체크 시작
            foreach (NumericTreeViewItem child in item)
            {
                //처음 부분
                if (index == 0)
                {
                    if (child.min != min)
                    {
                        isError          = true;
                        child.Foreground = Brushes.Red;     //처음 값이 최소값이 아님
                    }
                    else if ((child.Parent != null) && (child.includeMin != (child.Parent as NumericTreeViewItem).includeMin))
                    {
                        isError          = true;
                        child.Foreground = Brushes.Red;     //최소값의 포함 여부가 부모와 다름
                    }
                }

                //가운데 부분과 마지막 부분
                else if ((child.min != bound) || (child.includeMin == includeBound))
                {
                    isError          = true;
                    child.Foreground = Brushes.Red;       //바운드를 벗어남, 빠지는 부분이 있음
                }

                //마지막 부분만 추가 체크
                if (index == item.Count - 1)
                {
                    if (child.max != max)
                    {
                        isError          = true;
                        child.Foreground = Brushes.Red;     //마지막 값이 최대값이 아님
                    }
                    else if ((child.Parent != null) && (child.includeMax != (child.Parent as NumericTreeViewItem).includeMax))
                    {
                        isError          = true;
                        child.Foreground = Brushes.Red;     //최대값 포함 여부가 부모와 다름
                    }
                }

                //개수가 0개라면 의미가 없음
                if (child.count == 0)
                {
                    isError          = true;
                    child.Foreground = Brushes.Blue;
                }

                //recursive
                else if (child.Items.Count > 0)
                {
                    checkRangeofChild(child.Items, child.min, child.max);
                }


                bound        = child.max;
                includeBound = child.includeMax;
                index++;
            }

            return(isError);
        }
Пример #39
0
 public MenuItemFilter(ItemCollection items)
 {
     _Items = items;
 }
 /// <summary>
 /// Gets the entity, complex, or enum types for which code should be generated from the given item collection.
 /// Any types for which an ExternalTypeName annotation has been applied in the conceptual model
 /// metadata (CSDL) are filtered out of the returned list.
 /// </summary>
 /// <typeparam name="T">The type of item to return.</typeparam>
 /// <param name="itemCollection">The item collection to look in.</param>
 /// <returns>The items to generate.</returns>
 public IEnumerable <T> GetItemsToGenerate <T>(ItemCollection itemCollection) where T : GlobalItem
 {
     return(itemCollection.GetItems <T>().Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)));
 }
Пример #41
0
 /// <summary>
 /// Returns a list of patch objects that are not ready to be written to a patch file
 /// </summary>
 /// <param name="patchList">The list of patches to check</param>
 /// <returns>A new list of patches that are not valid to save, or an empty list of all patches are valid</returns>
 /// <seealso cref="IsValidForSave"/>
 public static List <Patch> GetInvalidPatchesForSave(ItemCollection patchList)
 {
     //https://stackoverflow.com/questions/471595/casting-an-item-collection-from-a-listbox-to-a-generic-list
     return(GetInvalidPatchesForSave(patchList.Cast <Patch>().ToList()));
 }
Пример #42
0
        public static void CustomArmorService(IUserInterfaceWindow window)
        {
            Debug.Log("Custom Armor service.");

            PlayerEntity   playerEntity = GameManager.Instance.PlayerEntity;
            ItemCollection armorItems   = new ItemCollection();
            Array          armorTypes   = DaggerfallUnity.Instance.ItemHelper.GetEnumArray(ItemGroups.Armor);

            foreach (ArmorMaterialTypes material in customArmorMaterials)
            {
                if (playerEntity.Level < 10 ||
                    (playerEntity.Level < 12 && material >= ArmorMaterialTypes.Adamantium) ||
                    (playerEntity.Level < 15 && material >= ArmorMaterialTypes.Orcish) ||
                    (playerEntity.Level < 18 && material >= ArmorMaterialTypes.Daedric))
                {
                    break;
                }

                for (int i = 0; i < armorTypes.Length; i++)
                {
                    Armor        armorType    = (Armor)armorTypes.GetValue(i);
                    ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(ItemGroups.Armor, i);
                    int          vs           = 0;
                    int          vf           = 0;
                    switch (armorType)
                    {
                    case Armor.Cuirass:
                    case Armor.Left_Pauldron:
                    case Armor.Right_Pauldron:
                        vs = 1;
                        vf = 3;
                        break;

                    case Armor.Greaves:
                        vs = 2;
                        vf = 5;
                        break;

                    case Armor.Gauntlets:
                    case Armor.Boots:
                        vs = 1;
                        vf = 1;
                        break;

                    case Armor.Helm:
                        vs = 1;
                        vf = itemTemplate.variants - 1;
                        break;

                    default:
                        continue;
                    }
                    for (int v = vs; v <= vf; v++)
                    {
                        armorItems.AddItem(ItemBuilder.CreateArmor(playerEntity.Gender, playerEntity.Race, armorType, material, v));
                    }
                }
            }

            DaggerfallTradeWindow tradeWindow = (DaggerfallTradeWindow)
                                                UIWindowFactory.GetInstanceWithArgs(UIWindowType.Trade, new object[] { DaggerfallUI.UIManager, null, DaggerfallTradeWindow.WindowModes.Buy, null });

            tradeWindow.MerchantItems = armorItems;
            DaggerfallUI.UIManager.PushWindow(tradeWindow);
        }
        private static void InitializeContextMenuItem(XmlElement menuItemElement, ItemCollection itemCollection, MainWindow window, Func <string, ImageSource> getImage)
        {
            try
            {
                if (menuItemElement.Name.EqualsIgnoreCase("separator"))
                {
                    itemCollection.Add(new Separator());
                    return;
                }

                if (!menuItemElement.Name.EqualsIgnoreCase("item"))
                {
                    Assert.IsTrue(false, "The element is not supported: {0}".FormatWith(menuItemElement.OuterXml));
                }

                // create handler
                var mainWindowButton = (IMainWindowButton)Plugin.CreateInstance(menuItemElement);

                // create Context Menu Item
                var menuItem = new System.Windows.Controls.MenuItem
                {
                    Header = menuItemElement.GetNonEmptyAttribute("header"),
                    Icon   = new Image
                    {
                        Source = getImage(menuItemElement.GetNonEmptyAttribute("image")),
                        Width  = 16,
                        Height = 16
                    },
                    IsEnabled = mainWindowButton == null || mainWindowButton.IsEnabled(window, SelectedInstance),
                    Tag       = mainWindowButton
                };

                if (mainWindowButton != null)
                {
                    menuItem.Click += (obj, e) =>
                    {
                        try
                        {
                            if (mainWindowButton.IsEnabled(MainWindow.Instance, SelectedInstance))
                            {
                                mainWindowButton.OnClick(MainWindow.Instance, SelectedInstance);
                                MainWindowHelper.RefreshInstances();
                            }
                        }
                        catch (Exception ex)
                        {
                            WindowHelper.HandleError(ex.Message, true);
                        }
                    };

                    SetIsEnabledProperty(menuItem, mainWindowButton);
                }

                foreach (var childElement in menuItemElement.ChildNodes.OfType <XmlElement>())
                {
                    InitializeContextMenuItem(childElement, menuItem.Items, window, getImage);
                }

                itemCollection.Add(menuItem);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Plugin Menu Item caused an exception");
            }
        }
Пример #44
0
 public Item()
 {
     Children = new ItemCollection();
 }
Пример #45
0
 private void ClearCollection(string vlaue)
 {
     ItemCollection.Clear();
 }
Пример #46
0
        protected void AddMenuItemIntoMenu(ConnectionPointContainer container,
                                           ItemCollection menuItemCollection,
                                           PluginConfigItem theItem,
                                           PluginMenuPath thePath,
                                           IList <PluginMenuItemPart> thePaths, ExecutePluginCallback callback)
        {
            if (thePaths.Count < 1)
            {
                return;
            }

            PluginMenuItemPart         firstPart  = thePaths[0];
            PluginMenuPartStruct       menuStruct = GetMenuItemIndex(firstPart, menuItemCollection);
            IList <PluginMenuItemPart> otherParts = GetLeavesMenuItemParts(thePaths);

            if (!menuStruct.IsCreate)
            {
                AddMenuItemIntoMenu(container,
                                    (menuItemCollection[menuStruct.Index] as MenuItem).Items,
                                    theItem,
                                    thePath,
                                    otherParts, callback);
            }
            else
            {
                if (firstPart.TextStyle.Text.Trim() == "-")
                {
                    menuItemCollection.Insert(menuStruct.Index, new Separator());
                    return;
                }

                MenuItem theMenuItem = new MenuItem()
                {
                    Header = firstPart.TextStyle.Text
                };

                CreateMenuEndItem(firstPart, theMenuItem, GetImageList(container, thePath.MenuImageIndex));
                menuItemCollection.Insert(menuStruct.Index, theMenuItem);

                if (thePaths.Count > 1)
                {
                    AddMenuItemIntoMenu(container, theMenuItem.Items, theItem, thePath, otherParts, callback);
                }
                else
                {
                    theMenuItem.Name = theItem.Url;
                    theMenuItem.Tag  = new object[] { theItem, callback };
                    string[] behaviors = theItem.Behavior.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string action in behaviors)
                    {
                        PluginConfigItemBehaviorMode theBehavior = (PluginConfigItemBehaviorMode)Enum.Parse(typeof(PluginConfigItemBehaviorMode), action, true);
                        switch (theBehavior)
                        {
                        case PluginConfigItemBehaviorMode.Click:
                            theMenuItem.Click -= TheMenuItem_Click;
                            theMenuItem.Click += TheMenuItem_Click;
                            break;

                        case PluginConfigItemBehaviorMode.MouseOver:
                            theMenuItem.MouseMove -= TheMenuItem_MouseMove;
                            theMenuItem.MouseMove += TheMenuItem_MouseMove;
                            break;
                        }
                    }
                    return;
                }
            }
        }
        public override IOperation Apply()
        {
            ResultCollection results = ResultsParameter.ActualValue;

            List <IScope> scopes = new List <IScope>()
            {
                ExecutionContext.Scope
            };

            for (int i = 0; i < DepthParameter.Value.Value; i++)
            {
                scopes = scopes.Select(x => (IEnumerable <IScope>)x.SubScopes).Aggregate((a, b) => a.Concat(b)).ToList();
            }

            ItemCollection <StringValue> collectedValues = CollectedValuesParameter.Value;

            foreach (StringValue collected in collectedValues)
            {
                //collect the values of the successful offspring
                Dictionary <String, int> counts = new Dictionary <String, int>();
                for (int i = 0; i < scopes.Count; i++)
                {
                    IScope child = scopes[i];
                    string successfulOffspringFlag = SuccessfulOffspringFlagParameter.Value.Value;
                    if (child.Variables.ContainsKey(collected.Value) &&
                        child.Variables.ContainsKey(successfulOffspringFlag) &&
                        (child.Variables[successfulOffspringFlag].Value is BoolValue) &&
                        (child.Variables[successfulOffspringFlag].Value as BoolValue).Value)
                    {
                        String key = child.Variables[collected.Value].Value.ToString();

                        if (!counts.ContainsKey(key))
                        {
                            counts.Add(key, 1);
                        }
                        else
                        {
                            counts[key]++;
                        }
                    }
                }

                if (counts.Count > 0)
                {
                    //create a data table containing the collected values
                    ResultCollection successfulOffspringAnalysis;

                    if (SuccessfulOffspringAnalysisParameter.ActualValue == null)
                    {
                        successfulOffspringAnalysis = new ResultCollection();
                        SuccessfulOffspringAnalysisParameter.ActualValue = successfulOffspringAnalysis;
                    }
                    else
                    {
                        successfulOffspringAnalysis = SuccessfulOffspringAnalysisParameter.ActualValue;
                    }

                    string resultKey = "SuccessfulOffspringAnalyzer Results";
                    if (!results.ContainsKey(resultKey))
                    {
                        results.Add(new Result(resultKey, successfulOffspringAnalysis));
                    }
                    else
                    {
                        results[resultKey].Value = successfulOffspringAnalysis;
                    }

                    DataTable successProgressAnalysis;
                    if (!successfulOffspringAnalysis.ContainsKey(collected.Value))
                    {
                        successProgressAnalysis      = new DataTable();
                        successProgressAnalysis.Name = collected.Value;
                        successfulOffspringAnalysis.Add(new Result(collected.Value, successProgressAnalysis));
                    }
                    else
                    {
                        successProgressAnalysis = successfulOffspringAnalysis[collected.Value].Value as DataTable;
                    }

                    int successfulCount = 0;
                    foreach (string key in counts.Keys)
                    {
                        successfulCount += counts[key];
                    }

                    foreach (String value in counts.Keys)
                    {
                        DataRow row;
                        if (!successProgressAnalysis.Rows.ContainsKey(value))
                        {
                            row = new DataRow(value);
                            int iterations = GenerationsParameter.ActualValue.Value;

                            //fill up all values seen the first time
                            for (int i = 1; i < iterations; i++)
                            {
                                row.Values.Add(0);
                            }

                            successProgressAnalysis.Rows.Add(row);
                        }
                        else
                        {
                            row = successProgressAnalysis.Rows[value];
                        }

                        row.Values.Add(counts[value] / (double)successfulCount);
                    }

                    //fill up all values that are not present in the current generation
                    foreach (DataRow row in successProgressAnalysis.Rows)
                    {
                        if (!counts.ContainsKey(row.Name))
                        {
                            row.Values.Add(0);
                        }
                    }
                }
            }

            return(base.Apply());
        }
Пример #48
0
        protected PluginMenuPartStruct GetMenuItemIndex(PluginMenuItemPart theMenuItemPart, ItemCollection nodes)
        {
            PluginMenuPartStruct theMenuItem = new PluginMenuPartStruct();
            int    index         = 0;
            string menuItemIndex = GetMenuItemIndex(theMenuItemPart.Locate);
            PluginMenuItemLocateType menuItemLocationType = (PluginMenuItemLocateType)(
                Enum.Parse(typeof(PluginMenuItemLocateType),
                           GetMenuItemLocator(theMenuItemPart.Locate),
                           true
                           )
                );

            theMenuItem.IsCreate = menuItemLocationType == PluginMenuItemLocateType.Create;

            if (int.TryParse(menuItemIndex, out index))
            {
                theMenuItem.Index = PluginMenuItemPartLocator.GetMenuLocatorIndex(menuItemLocationType, index, nodes.Count);
            }
            else if (menuItemIndex.Length == 0)
            {
                theMenuItem.Index = nodes.Count;
            }
            else
            {
                int realIndex = GetMenuItemIndexById(nodes, menuItemIndex);
                theMenuItem.Index = PluginMenuItemPartLocator.GetMenuLocatorIndex(
                    menuItemLocationType,
                    realIndex,
                    nodes.Count
                    );
                // Make only support ID
                if (menuItemLocationType == PluginMenuItemLocateType.Make)
                {
                    if (realIndex >= 0 && realIndex < nodes.Count)
                    {
                        theMenuItem.IsCreate = false;
                    }
                    else
                    {
                        theMenuItem.IsCreate = true;
                    }
                }
            }
            theMenuItem.Exist = theMenuItem.Index < nodes.Count &&
                                theMenuItem.Index >= 0;
            return(theMenuItem);
        }
Пример #49
0
        private void FileOpen_Click(object sender, RoutedEventArgs e)
        {
            //old code that worked with defaul file path
            //string path = "output.txt";

            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.Filter = FilterTxt + "|" +
                            FilterJson + "|" +
                            FilterXml + "|" +
                            FilterSoap + "|" +
                            FilterBinary;

            dialog.FilterIndex = 1;
            bool?dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;

                if (System.IO.File.Exists(filePath))
                {
                    string content = string.Empty;

                    if (dialog.FilterIndex == 1)
                    {
                        System.IO.StringWriter writer = new System.IO.StringWriter();

                        ItemCollection items = this.TodoTaskListView.Items;
                        foreach (var item in items)
                        {
                            TodoTask todoTask = item as TodoTask;

                            writer.Write(todoTask.LastSaved);
                            writer.Write(todoTask.IsComplete);
                            writer.Write(todoTask.Description);
                        }
                        content = writer.ToString();
                        writer.Dispose();
                    }


                    else if (dialog.FilterIndex == 2)
                    {
                        // read as JSON
                        string json = content;
                        // deserialize to expected type (Models.Document)
                        object jsonObject = Newtonsoft.Json
                                            .JsonConvert
                                            .DeserializeObject(json, typeof(Models.TodoTask));
                        // cast and assign JSON object to expected type (Models.Document)
                        Models.TodoTask items = (Models.TodoTask)jsonObject;
                        // assign content from deserialized Models.Document
                        content = items.Content;
                    }


                    else if (dialog.FilterIndex == 3)
                    {
                        // read as XML for type of Models.Document
                        System.Xml.Serialization.XmlSerializer serializer =
                            new System.Xml.Serialization.XmlSerializer(typeof(Models.TodoTask));

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
#pragma warning disable CA5369 // Use XmlReader For Deserialize
                        object xmlObject = serializer.Deserialize(stream);
#pragma warning restore CA5369 // Use XmlReader For Deserialize
                               // cast and assign XML object to actual type object
                        Models.TodoTask items = (Models.TodoTask)xmlObject;

                        content = items.Content;
                        stream.Dispose();   // release the resources
                    }


                    else if (dialog.FilterIndex == 4)
                    {
                        // read as soap
                        System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
                        object soapObject = serializer.Deserialize(stream);
                        // cast and assign SOAP object to actual type object
                        Models.TodoTask document = (Models.TodoTask)soapObject;
                        // read content
                        content = document.Content;

                        stream.Dispose();   // release the resources
                    }


                    else if (dialog.FilterIndex == 5)
                    {
                        // read as binary
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                        // reading and writing binary data directly as string has issues, try not to do it
                        byte[] buffer = Convert.FromBase64String(content);
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to object
                        object binaryObject = serializer.Deserialize(stream);
                        // assign binary object to actual type object
                        Models.TodoTask items = (Models.TodoTask)binaryObject;
                        // read the content
                        content = items.Content;
                        stream.Dispose();   // release the resources
                    }
                    else // imply this is any file
                    {
                        // read as is
                    }

                    // assign content to UI control
                    // ~~~~~~~ UserText.Text = content; ~~~~~~~~~~~~~~~~~~~

                    //old code that worked with defaul file path

                    /*if (System.IO.File.Exists(path))
                     * {
                     *  System.IO.FileStream fileStream = System.IO.File.Open(
                     *  path,
                     *  System.IO.FileMode.Open,
                     *  System.IO.FileAccess.Read,
                     *  System.IO.FileShare.None);
                     *  System.IO.StreamReader reader = new System.IO.StreamReader(fileStream);
                     *  while (reader.EndOfStream == false)
                     *  {
                     *      string line = reader.ReadLine();
                     *      TodoTask item = new TodoTask();
                     *      item.Description = line;
                     *      TodoTaskListView.Items.Add(item);
                     *  }
                     *  reader.Close();
                     *  fileStream.Close();
                     * }*/

                    //below is part of the save file code

                    /*System.IO.StringWriter writer = new System.IO.StringWriter();
                     * List<TodoTask> items = new List<TodoTask>();
                     * foreach (var item in this.TodoTaskListView.Items)
                     * {
                     *  items.Add(item as TodoTask);
                     * }
                     *
                     * foreach (var item in items)
                     * {
                     *  writer.WriteLine(item.Description);
                     * }*/
                }
            }
        }
Пример #50
0
        /**
         * Evento que controla el movimiento de las piezas
         *
         */
        void miKinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            canvasEsqueleto.Children.Clear();
            Skeleton[] esqueletos = null;

            using (SkeletonFrame frameEsqueleto = e.OpenSkeletonFrame())
            {
                if (frameEsqueleto != null)
                {
                    esqueletos = new Skeleton[frameEsqueleto.SkeletonArrayLength];
                    frameEsqueleto.CopySkeletonDataTo(esqueletos);
                }
            }

            if (esqueletos == null)
            {
                return;
            }

            foreach (Skeleton esqueleto in esqueletos)
            {
                if (esqueleto.TrackingState == SkeletonTrackingState.Tracked)
                {
                    Joint HandLeft = esqueleto.Joints[JointType.HandLeft];

                    ColorImagePoint j1P = miKinect.CoordinateMapper.MapSkeletonPointToColorPoint(HandLeft.Position, ColorImageFormat.RgbResolution1280x960Fps12);
                    //cursor actualizado
                    this.Cursor.Margin = new Thickness(j1P.X, j1P.Y, 0.0, 0.0);
                    ItemCollection it = this.container.Items;
                    //Comprueba que la pieza que se puede coger sea la primera
                    if (piece == null || piece.Equals(peana.firstPiece()) || piece.Equals(peana1.firstPiece()) || piece.Equals(peana2.firstPiece()))
                    {
                        //Por el if si no tiene una pieza en el cursor si la tiene por el else
                        if (take == false)
                        {
                            piece = this.isTaken(it, j1P);
                        }
                        else
                        {//carga la imagen de mano
                            this.loadPicture("/imagenes/take.jpg");
                            //actualiza cursor
                            this.Cursor.Margin = new Thickness(j1P.X, j1P.Y, 0.0, 0.0);
                            //actualiza posicion de la pieza
                            piece.Margin = new Thickness(j1P.X, j1P.Y, 0.0, 0.0);

                            //Comprueba que la pieza que  la posicion anterior sea la misma que la actual
                            if (j1P.X == this.j1P_ant.X && j1P.Y == this.j1P_ant.Y)
                            {
                                contLeave++;
                                //Cuando llega a 30 suelta la pieza
                                if (this.contLeave == 30)
                                {
                                    this.loadPicture("/Imagenes/arrow.png");
                                    //Mira si la pieza esta correctmente colocada
                                    this.isOkPosition(piece);

                                    piece     = null;
                                    contLeave = 0;
                                    take      = false;
                                }
                            }
                            j1P_ant = j1P;
                        }
                    }
                    else
                    {
                        piece     = null;
                        contLeave = 0;
                        take      = false;
                    }
                }
            }
        }
Пример #51
0
 public static T FindCollectionItem <T>(this ItemCollection collection, Func <T, bool> predicate)
 {
     try { return((from T item in collection select item).FirstOrDefault(predicate)); }
     catch { return(default); }
 /// <summary>
 /// True if this entity type participates in any relationships where the other end has an OnDelete
 /// cascade delete defined, or if it is the dependent in any identifying relationships
 /// </summary>
 private bool ContainsCascadeDeleteAssociation(ItemCollection itemCollection, EntityType entity)
 {
     return(itemCollection.GetItems <AssociationType>().Where(a =>
                                                              ((RefType)a.AssociationEndMembers[0].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[1]) ||
                                                              ((RefType)a.AssociationEndMembers[1].TypeUsage.EdmType).ElementType == entity && IsCascadeDeletePrincipal(a.AssociationEndMembers[0])).Any());
 }
Пример #53
0
        private static bool OnMobileIncoming(ref byte[] packet, ref int length)
        {
            bool useNewIncoming = Engine.ClientVersion == null || Engine.ClientVersion >= new Version(7, 0, 33, 1);

            PacketReader reader = new PacketReader(packet, length, false);

            int            serial    = reader.ReadInt32();
            ItemCollection container = new ItemCollection(serial);

            Mobile mobile = serial == Engine.Player?.Serial ? Engine.Player : Engine.GetOrCreateMobile(serial);

            mobile.ID = reader.ReadInt16();
            mobile.X  = reader.ReadInt16();
            mobile.Y  = reader.ReadInt16();
            mobile.Z  = reader.ReadSByte();
            //TODO Removed & 0x07 to not strip running flag, think of better solution
            mobile.Direction = (Direction)reader.ReadByte();
            mobile.Hue       = reader.ReadUInt16();
            mobile.Status    = (MobileStatus)reader.ReadByte();
            mobile.Notoriety = (Notoriety)reader.ReadByte();

            for ( ;;)
            {
                int itemSerial = reader.ReadInt32();

                if (itemSerial == 0)
                {
                    break;
                }

                Item item = Engine.GetOrCreateItem(itemSerial);
                item.Owner = serial;
                item.ID    = reader.ReadUInt16();
                item.Layer = (Layer)reader.ReadByte();

                if (useNewIncoming)
                {
                    item.Hue = reader.ReadUInt16();
                }
                else
                {
                    if ((item.ID & 0x8000) != 0)
                    {
                        item.ID ^= 0x8000;
                        item.Hue = reader.ReadUInt16();
                    }
                }

                container.Add(item);
            }

            mobile.Equipment.Clear();
            mobile.Equipment.Add(container.GetItems());

            foreach (Item item in container.GetItems())
            {
                mobile.SetLayer(item.Layer, item.Serial);
            }

            try
            {
                if (Options.CurrentOptions.RehueFriends &&
                    Options.CurrentOptions.Friends.Any(e => e.Serial == serial))
                {
                    MobileIncoming newPacket =
                        new MobileIncoming(mobile, container, Options.CurrentOptions.RehueFriendsHue);

                    packet = newPacket.ToArray();
                    length = packet.Length;

                    return(false);
                }
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.ToString());
            }

            if (!Engine.RehueList.CheckMobileIncoming(mobile, container))
            {
                return(false);
            }

            Engine.IncomingQueue.Enqueue(new Packet(packet, length));
            return(true);
        }
        /// <summary>
        /// True when player owns a horse
        /// </summary>
        /// <returns></returns>
        public bool HasHorse()
        {
            ItemCollection inventory = GameManager.Instance.PlayerEntity.Items;

            return(inventory.Contains(ItemGroups.Transportation, (int)Transportation.Horse));
        }
Пример #55
0
 public void UpdateCollection(ItemCollection collection)
 {
 }
 public void AddCollection(ItemCollection e)
 {
     CollectionList.Add(e);
     e.ParentContainer = this;
 }
Пример #57
0
        protected override void Setup()
        {
            // What transport options does the player have?
            ItemCollection inventory = GameManager.Instance.PlayerEntity.Items;
            bool           hasHorse  = GameManager.Instance.TransportManager.HasHorse();
            bool           hasCart   = GameManager.Instance.TransportManager.HasCart();
            bool           hasShip   = GameManager.Instance.TransportManager.ShipAvailiable();

            // Load all textures
            LoadTextures();

            // Create interface panel
            mainPanel.HorizontalAlignment = HorizontalAlignment.Center;
            mainPanel.VerticalAlignment   = VerticalAlignment.Middle;
            mainPanel.BackgroundTexture   = baseTexture;
            mainPanel.Position            = new Vector2(0, 50);
            mainPanel.Size = baseSize;
            DFSize disabledTextureSize = new DFSize(122, 36);

            // Foot button
            footButton = DaggerfallUI.AddButton(footButtonRect, mainPanel);
            footButton.OnMouseClick    += FootButton_OnMouseClick;
            footButton.Hotkey           = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.TransportFoot);
            footButton.OnKeyboardEvent += FootButton_OnKeyboardEvent;

            // Horse button
            horseButton = DaggerfallUI.AddButton(horseButtonRect, mainPanel);
            if (hasHorse)
            {
                horseButton.OnMouseClick    += HorseButton_OnMouseClick;
                horseButton.Hotkey           = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.TransportHorse);
                horseButton.OnKeyboardEvent += HorseButton_OnKeyboardEvent;
            }
            else
            {
                horseButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, horseDisabledRect, disabledTextureSize);
            }
            // Cart button
            cartButton = DaggerfallUI.AddButton(cartButtonRect, mainPanel);
            if (hasCart)
            {
                cartButton.OnMouseClick    += CartButton_OnMouseClick;
                cartButton.Hotkey           = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.TransportCart);
                cartButton.OnKeyboardEvent += CartButton_OnKeyboardEvent;
            }
            else
            {
                cartButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, cartDisabledRect, disabledTextureSize);
            }
            // Ship button
            shipButton = DaggerfallUI.AddButton(shipButtonRect, mainPanel);
            if (hasShip)
            {
                shipButton.OnMouseClick    += ShipButton_OnMouseClick;
                shipButton.Hotkey           = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.TransportShip);
                shipButton.OnKeyboardEvent += ShipButton_OnKeyboardEvent;
            }
            else
            {
                shipButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, shipDisabledRect, disabledTextureSize);
            }

            // Exit button
            exitButton = DaggerfallUI.AddButton(exitButtonRect, mainPanel);
            exitButton.OnMouseClick    += ExitButton_OnMouseClick;
            exitButton.Hotkey           = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.TransportExit);
            exitButton.OnKeyboardEvent += ExitButton_OnKeyboardEvent;

            NativePanel.Components.Add(mainPanel);

            // Store toggle closed binding for this window
            toggleClosedBinding = InputManager.Instance.GetBinding(InputManager.Actions.Transport);
        }
Пример #58
0
 void RemoveAnItem(ListItemViewModel item) => ItemCollection.Remove(item);
        private static ItemCollection ParseComplexType_SequenceChoice(XmlTextReader X)
        {
            bool           done        = false;
            ItemCollection RetVal      = null;
            string         elementName = X.LocalName;
            DText          p           = new DText();

            p.ATTRMARK = ":";

            if (X.LocalName == "choice")
            {
                RetVal = new Choice();
            }
            else
            {
                RetVal = new Sequence();
            }

            if (X.HasAttributes)
            {
                for (int i = 0; i < X.AttributeCount; i++)
                {
                    X.MoveToAttribute(i);
                    switch (X.LocalName)
                    {
                    case "minOccurs":
                        RetVal.MinOccurs = X.Value;
                        break;

                    case "maxOccurs":
                        RetVal.MaxOccurs = X.Value;
                        break;
                    }
                }
                X.MoveToElement();
            }
            X.Read();


            do
            {
                switch (X.NodeType)
                {
                case XmlNodeType.Element:
                    switch (X.LocalName)
                    {
                    case "group":
                        if (X.HasAttributes)
                        {
                            for (int i = 0; i < X.AttributeCount; i++)
                            {
                                X.MoveToAttribute(i);
                                switch (X.LocalName)
                                {
                                case "ref":
                                    string sample = X.Value;
                                    break;
                                }
                            }
                            X.MoveToElement();
                        }
                        break;

                    case "sequence":
                    case "choice":
                        RetVal.AddCollection(ParseComplexType_SequenceChoice(X));
                        break;

                    case "element":
                        RetVal.AddContentItem(new Element());
                        if (X.HasAttributes)
                        {
                            for (int i = 0; i < X.AttributeCount; i++)
                            {
                                X.MoveToAttribute(i);
                                switch (X.LocalName)
                                {
                                case "name":
                                    RetVal.CurrentItem.Name = X.Value;
                                    break;

                                case "type":
                                    p[0] = X.Value;
                                    if (p.DCOUNT() == 1)
                                    {
                                        RetVal.CurrentItem.Type   = X.Value;
                                        RetVal.CurrentItem.TypeNS = X.LookupNamespace("");
                                    }
                                    else
                                    {
                                        RetVal.CurrentItem.Type   = p[2];
                                        RetVal.CurrentItem.TypeNS = X.LookupNamespace(p[1]);
                                    }
                                    break;

                                case "minOccurs":
                                    RetVal.CurrentItem.MinOccurs = X.Value;
                                    break;

                                case "maxOccurs":
                                    RetVal.CurrentItem.MaxOccurs = X.Value;
                                    break;
                                }
                            }
                            X.MoveToElement();
                        }
                        break;

                    case "attribute":
                        break;
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (X.LocalName == elementName)
                    {
                        done = true;
                    }
                    break;

                case XmlNodeType.Text:
                    break;
                }
            }while(!done && X.Read());

            return(RetVal);
        }
 public void AddCollection(ItemCollection ic)
 {
     NestedCollectionList.Add(ic);
     ic.ParentCollection = this;
 }