コード例 #1
0
        public override ITimeSpaceValueSet GetEngineValues(ExchangeItem exchangeItem)
        {
            // Handle the flow output item, quantity.Caption="Flow", elementSet.Caption="Branch:[index]:Flow"
            IQuantity quantity = exchangeItem.ValueDefinition as IQuantity;

            if (quantity == null)
            {
                throw new ArgumentException("Can only accept quantity as valuedefinition", "exchangeItem");
            }

            double[] values;
            Char[]   separator = new char[] { ':' };

            if (quantity.Caption == "Flow")
            {
                int index = Convert.ToInt32((exchangeItem.SpatialDefinition.Caption.Split(separator))[1]);
                values    = new double[1];
                values[0] = _simpleRiverEngine.GetFlow(index);
            }
            else
            {
                throw new ArgumentException("Unknown Quantity/elementSet combination in GetValues", "exchangeItem");
            }

            return(new TimeSpaceValueSet <double>(values));
        }
コード例 #2
0
        protected virtual Exception PublishItemAdd(Item item, List <string> workingSets, string sourceSystem, Dictionary <string, object> signalProperties)
        {
            SignalFeederEx signalFeederEx = WorkingSetPublisher.CreateGroupSignalFeeder(item.Session);
            Participant    valueOrDefault = item.GetValueOrDefault <Participant>(InternalSchema.Sender, null);

            if (valueOrDefault == null || string.IsNullOrEmpty(valueOrDefault.EmailAddress))
            {
                WorkingSetPublisher.Tracer.TraceDebug <string>((long)this.GetHashCode(), "WorkingSetPublisher::PublishItemAdd. Item missing Sender property. Item={0}", item.InternalObjectId.ToString());
                return(new CorruptDataException(new LocalizedString("Missing Sender property")));
            }
            Item   item2            = new Item(valueOrDefault.EmailAddress, sourceSystem);
            string itemWorkingSetId = WorkingSetPublisher.GetItemWorkingSetId(item);
            Item   item3            = new ExchangeItem(itemWorkingSetId, sourceSystem, false, item);

            if (signalProperties != null)
            {
                foreach (string text in signalProperties.Keys)
                {
                    item3.SetProperty(text, signalProperties[text]);
                }
            }
            Action action = new Action("Authored", DateTime.UtcNow, WorkingSetPublisherConfiguration.ModernGroupsItemAddWeight, item3, sourceSystem);

            signalFeederEx.Put(item2, action, workingSets);
            return(null);
        }
コード例 #3
0
        private static ExchangeItem GetPlatformExchangeFromConfig(ExchangeElement configElement)
        {
            var item = new ExchangeItem()
            {
                Name = configElement.Name, PrefetchCount = configElement.PrefetchCount, Type = configElement.Type, Out = new List <OutMessage>(), In = new List <InMessage>()
            };

            foreach (var outEl in configElement.Out.Cast <OutgoingElement>())
            {
                var outItem = new OutMessage()
                {
                    Key = outEl.Key, Name = outEl.Name, Persist = outEl.Persist, Timeout = outEl.Timeout
                };
                item.Out.Add(outItem);
            }
            foreach (var inElement in configElement.In.Cast <IncomingElement>())
            {
                var inItem = new InMessage()
                {
                    Key = inElement.Key, Name = inElement.Name, Type = inElement.Type, React = inElement.React
                };
                item.In.Add(inItem);
            }

            return(item);
        }
コード例 #4
0
        public void Init()
        {
            exchangeItem          = new ExchangeItem();
            exchangeItem.Quantity = new Quantity("Q");
            ElementSet elementSet = new ElementSet();

            elementSet.ID           = "ES";
            exchangeItem.ElementSet = elementSet;
        }
コード例 #5
0
ファイル: ExchangeEvent.cs プロジェクト: lunice/bgo
    public void Exchange()
    {
        ExchangeItem from = new ExchangeItem {
            Id = 3, Name = "crystal_1"
        };
        ExchangeItem to = new ExchangeItem {
            Id = 2, Name = "gold_10"
        };
        int count = 1;

        OnExchange(from, to, count);
    }
コード例 #6
0
ファイル: ExchangeEvent.cs プロジェクト: lunice/bgo
    public static void OnExchange(ExchangeItem from, ExchangeItem to, int count)
    {
        var main = MAIN.getMain;

        var exchange = new ExchangeApiRequest();

        exchange.Sid  = main.sessionID;
        exchange.Cnt  = count;
        exchange.From = from;
        exchange.To   = to;
        main.network.ApiRequest(Api.CmdName.Exchange, JsonUtility.ToJson(exchange));
    }
コード例 #7
0
    private ExchangeItem parseCurrencyDetail(XmlElement currencyNode)
    {
        ExchangeItem result = new ExchangeItem();

        System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-US", true);

        result.CurrencyCode = currencyNode.Attributes["Kod"].InnerText;

        foreach (XmlElement nodeItem in currencyNode.ChildNodes)
        {
            switch (nodeItem.Name)
            {
            case "Unit":
                result.Unit = Int32.Parse(nodeItem.InnerText);
                break;

            case "Isim":
                result.CurrencyNameTR = nodeItem.InnerText;
                break;

            case "CurrencyName":
                result.CurrencyName = nodeItem.InnerText;
                break;

            case "ForexBuying":
                result.ForexBuying = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;

            case "ForexSelling":
                result.ForexSelling = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;

            case "BanknoteBuying":
                result.BanknoteBuying = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;

            case "BanknoteSelling":
                result.BanknoteSelling = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;

            case "CrossRateUSD":
                result.CrossRateUSD = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;

            case "CrossRateOther":
                result.CrossRateOther = string.IsNullOrWhiteSpace(nodeItem.InnerText) ? 0 : Decimal.Parse(nodeItem.InnerText, culInfo);
                break;
            }
        }

        return(result);
    }
コード例 #8
0
ファイル: RiverModelLC.cs プロジェクト: muguangyuze/OpenMI
        public override ITimeSpaceValueSet GetEngineValues(ExchangeItem exchangeItem)
        {
            if (exchangeItem is EngineInputItem)
            {
                // Input item, provide current internal values for this item
                // NOT supported by this computational core
                throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
            }

            ITimeSpaceValueSet values = GetOutputValuesFromComputationalCore(exchangeItem);

            return(values);
        }
コード例 #9
0
ファイル: GWModelLC.cs プロジェクト: muguangyuze/OpenMI
        public override ITimeSpaceValueSet GetEngineValues(ExchangeItem exchangeItem)
        {
            List <double> values = new List <double>();

            if (exchangeItem is EngineInputItem)
            {
                // Input item, provide current input values
                if (exchangeItem == _storageInput)
                {
                    for (int i = 0; i < _storage.Length; i++)
                    {
                        values.Add(_storage[i]);
                    }
                }
                else if (exchangeItem == _firstElementStorageInput)
                {
                    values.Add(_storage[0]);
                }
                else
                {
                    throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
                }
            }
            else if (exchangeItem is EngineOutputItem)
            {
                // Output item, provide computed values
                if (exchangeItem == _storageOutput)
                {
                    for (int i = 0; i < _storage.Length; i++)
                    {
                        values.Add(_storage[i]);
                    }
                }
                else if (exchangeItem == _firstElementStorageOutput)
                {
                    values.Add(_storage[0]);
                }
                else
                {
                    throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
                }
            }
            else
            {
                throw new Exception("Should be EngineInputItem or EngineOutputItem");
            }
            return(new ValueSet(new List <IList> {
                values
            }));
        }
コード例 #10
0
        private GameObject createItem(string id, int count, GameObject itemPrefab)
        {
            GameObject   gameObject   = UnityEngine.Object.Instantiate(itemPrefab, ScrollContent);
            ExchangeItem exchangeItem = new ExchangeItem();

            exchangeItem.CollectibleType       = id;
            exchangeItem.QuantityEarned        = count;
            exchangeItem.CollectibleDefinition = Service.Get <CollectibleDefinitionService>().Get(id);
            ExchangeItem exchangeItem2            = exchangeItem;
            ExchangeScreenInventoryItem component = gameObject.GetComponent <ExchangeScreenInventoryItem>();

            component.ExchangeItem = exchangeItem2;
            items.Add(component);
            return(gameObject);
        }
コード例 #11
0
ファイル: RiverModelLC.cs プロジェクト: muguangyuze/OpenMI
        private ITimeSpaceValueSet GetOutputValuesFromComputationalCore(ExchangeItem exchangeItem)
        {
            var separator = new[] { ':' };

            string[] elementSetCaptionSubStrings = exchangeItem.SpatialDefinition.Caption.Split(separator);

            List <double> values = new List <double>();

            // Output item, provide computed values
            if (exchangeItem.Id.Equals("WholeRiver:Flow"))
            {
                for (int i = 0; i < _flow.Length; i++)
                {
                    values.Add(_flow[i]);
                }
            }
            else if (exchangeItem.Id.Equals("WholeRiver:Leakage"))
            {
                for (int i = 0; i < _leakage.Length; i++)
                {
                    values.Add(_leakage[i]);
                }
            }
            else if (elementSetCaptionSubStrings[0] == "Branch")
            {
                int branchIndex = Convert.ToInt32(elementSetCaptionSubStrings[1]);
                if (exchangeItem.ValueDefinition.Caption.Equals("Flow"))
                {
                    values.Add(_flow[branchIndex]);
                }
                else if (exchangeItem.ValueDefinition.Caption.Equals("Leakage"))
                {
                    values.Add(_leakage[branchIndex]);
                }
                else
                {
                    throw new Exception("Quantity Caption not recognized in GetValues method");
                }
            }
            else
            {
                throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
            }

            return(new ValueSet(new List <IList> {
                values
            }));
        }
コード例 #12
0
    private void AccessExchangeLogic(ExchangeItem exchangeItem)
    {
        RestrictionInput.StartLoad(RestrictionInput.LoadType.LARGE_IMAGE_MASK_ON);
        APIRequestTask task = ClassSingleton <ExchangeWebAPI> .Instance.AccessEventExchangeLogicAPI(exchangeItem.exchangeDetailId, exchangeItem.numCounter);

        base.StartCoroutine(task.Run(delegate
        {
            RestrictionInput.EndLoad();
            if (string.IsNullOrEmpty(ClassSingleton <ExchangeWebAPI> .Instance.exchangeErrorCode))
            {
                this.OpenExchangedItemModalMessage(exchangeItem);
            }
            else
            {
                this.ExchangeErrorPopup();
            }
        }, null, null));
    }
コード例 #13
0
    private void OpenExchangedItemModalMessage(ExchangeItem exchangeItem)
    {
        MasterDataMng.AssetCategory assetCategory = (MasterDataMng.AssetCategory) int.Parse(exchangeItem.exchangeItemData.assetCategoryId);
        switch (assetCategory)
        {
        case MasterDataMng.AssetCategory.DIGI_STONE:
            DataMng.Instance().RespDataUS_PlayerInfo.playerInfo.point -= int.Parse(this.consumeNum);
            break;

        default:
            if (assetCategory == MasterDataMng.AssetCategory.MEAT)
            {
                int num = int.Parse(DataMng.Instance().RespDataUS_PlayerInfo.playerInfo.meatNum) - int.Parse(this.consumeNum);
                DataMng.Instance().RespDataUS_PlayerInfo.playerInfo.meatNum = num.ToString();
            }
            break;

        case MasterDataMng.AssetCategory.TIP:
        {
            int num2 = int.Parse(DataMng.Instance().RespDataUS_PlayerInfo.playerInfo.gamemoney) - int.Parse(this.consumeNum);
            DataMng.Instance().RespDataUS_PlayerInfo.playerInfo.gamemoney = num2.ToString();
            break;
        }

        case MasterDataMng.AssetCategory.ITEM:
        {
            GameWebAPI.RespDataMA_GetItemM.ItemM itemM = MasterDataMng.Instance().RespDataMA_ItemM.GetItemM(exchangeItem.exchangeItemData.assetValue);
            if (itemM != null && int.Parse(itemM.itemId) == 2)
            {
                Singleton <UserDataMng> .Instance.UpdateUserItemNum(2, -int.Parse(this.consumeNum));
            }
            break;
        }
        }
        int              num3 = int.Parse(exchangeItem.exchangeDetailNum, NumberStyles.AllowThousands);
        string           exchangeDetailName = exchangeItem.exchangeDetailName;
        string           arg              = StringFormat.Cluster(num3 * exchangeItem.numCounter);
        string           info             = string.Format(StringMaster.GetString("ExchangeSuccessInfo"), exchangeDetailName, arg);
        CMD_ModalMessage cmd_ModalMessage = GUIMain.ShowCommonDialog(new Action <int>(this.RunReExchangeInfoLogicAPI), "CMD_ModalMessage", null) as CMD_ModalMessage;

        cmd_ModalMessage.Title = StringMaster.GetString("ExchangeSuccessTitle");
        cmd_ModalMessage.Info  = info;
        GUIPlayerStatus.RefreshParams_S(true);
    }
コード例 #14
0
    public Vector3 AllBuild(int listItemCount, out List <ExchangeItem> itemList)
    {
        base.InitBuild();
        this.partsCount = listItemCount;
        int num = this.partsCount / this.PARTS_CT_MN;

        if (this.partsCount % this.PARTS_CT_MN > 0)
        {
            num++;
        }
        Vector3 position = new Vector3(0f, 0f, 0f);

        itemList = new List <ExchangeItem>();
        if (base.selectCollider != null)
        {
            GUISelectPanelBSPartsUD.PanelBuildData panelBuildData = base.CalcBuildData(this.PARTS_CT_MN, num, 1f, 1f);
            float num2   = panelBuildData.startY;
            float startX = panelBuildData.startX;
            int   num3   = 0;
            for (int i = 0; i < this.partsCount; i++)
            {
                GameObject   gameObject = base.AddBuildPart();
                ExchangeItem component  = gameObject.GetComponent <ExchangeItem>();
                if (component != null)
                {
                    float x = startX + panelBuildData.pitchW * (float)(num3 % this.PARTS_CT_MN);
                    component.SetOriginalPos(new Vector3(x, num2, -5f));
                    if (num3 == 0)
                    {
                        position = component.transform.position;
                    }
                    itemList.Add(component);
                }
                num3++;
                if (num3 % this.PARTS_CT_MN == 0)
                {
                    num2 -= panelBuildData.pitchH;
                }
            }
            base.height = panelBuildData.lenH;
            base.InitMinMaxLocation(-1, 0f);
        }
        return(position);
    }
コード例 #15
0
        public void Equals()
        {
            ExchangeItem exchangeItem = new ExchangeItem();

            exchangeItem.Quantity = new Quantity("Q");
            ElementSet elementSet = new ElementSet();

            elementSet.ID           = "ES";
            exchangeItem.ElementSet = elementSet;

            Assert.IsTrue(exchangeItem.Equals(this.exchangeItem));

            exchangeItem.Quantity = new Quantity("Q1");
            Assert.IsFalse(exchangeItem.Equals(this.exchangeItem));
            exchangeItem.Quantity = new Quantity("Q");
            elementSet.ID         = "ES2";

            Assert.IsFalse(exchangeItem.Equals(this.exchangeItem));
            Assert.IsFalse(exchangeItem.Equals(null));
            Assert.IsFalse(exchangeItem.Equals("string"));
        }
コード例 #16
0
        private void GeneratePartyRecycleMat()
        {
            int index = 0;

            foreach (KeyValuePair <int, double> keyValue in m_RecyclyMat)
            {
                int val = (int)keyValue.Value;
                if (val > 0)
                {
                    ItemItem item = Global.gApp.gGameData.ItemData.Get(keyValue.Key);
                    CampRecycleUi_ExchangeItem exchangeItem = ExchangeItem.GetInstance();
                    exchangeItem.transform.SetSiblingIndex(keyValue.Key);
                    exchangeItem.gameObject.SetActive(true);
                    exchangeItem.Icon.image.sprite = Resources.Load(item.image_grow, typeof(Sprite)) as Sprite;
                    exchangeItem.Count.text.text   = val.ToString();
                    index++;
                    if (index == 4)
                    {
                        break;
                    }
                }
            }
        }
コード例 #17
0
 public abstract ITimeSpaceValueSet GetEngineValues(ExchangeItem exchangeItem);
コード例 #18
0
 private void CalculateExchangeFund(ExchangeItem selectedExchange)
 {
     throw new NotImplementedException();
 }
コード例 #19
0
ファイル: TestEngine.cs プロジェクト: muguangyuze/OpenMI
 public override ITimeSpaceValueSet GetEngineValues(ExchangeItem exchangeItem)
 {
     double[] values = GetValues(exchangeItem.ValueDefinition.Caption, exchangeItem.SpatialDefinition.Caption);
     return(new TimeSpaceValueSet <double>(values));
 }
コード例 #20
0
    private void OnPushedButton(ExchangeItem exchangeItem)
    {
        int num = 0;

        foreach (string a in this.itemDictionary.Keys)
        {
            string assetCategoryId = exchangeItem.exchangeItemData.assetCategoryId;
            string assetValue      = exchangeItem.exchangeItemData.assetValue;
            string text            = assetCategoryId + assetValue;
            if (this.itemDictionary.ContainsKey(text) && a == text && this.itemDictionary[text] == assetValue)
            {
                break;
            }
            num++;
        }
        string text2 = this.exchangeConsumeItemName[num];

        this.consumeNum = (int.Parse(exchangeItem.exchangeConsumeNum) * exchangeItem.numCounter).ToString();
        string text3 = (this.exchangeConsumeItemInfo == null) ? string.Empty : this.exchangeConsumeItemInfo.unitName;

        MasterDataMng.AssetCategory assetCategory = (MasterDataMng.AssetCategory) int.Parse(exchangeItem.exchangeItemData.assetCategoryId);
        CMD_ClearingHouse.IconType  iconType      = CMD_ClearingHouse.IconType.NON;
        switch (assetCategory)
        {
        case MasterDataMng.AssetCategory.MONSTER:
            text3    = StringMaster.GetString("ConsumeUnitMonster");
            iconType = CMD_ClearingHouse.IconType.NON;
            break;

        case MasterDataMng.AssetCategory.DIGI_STONE:
            iconType = CMD_ClearingHouse.IconType.SPRITE;
            break;

        case MasterDataMng.AssetCategory.LINK_POINT:
            text3    = string.Empty;
            iconType = CMD_ClearingHouse.IconType.SPRITE;
            break;

        case MasterDataMng.AssetCategory.TIP:
            text3    = string.Empty;
            iconType = CMD_ClearingHouse.IconType.SPRITE;
            break;

        case MasterDataMng.AssetCategory.ITEM:
            iconType = CMD_ClearingHouse.IconType.TEXTURE;
            break;

        case MasterDataMng.AssetCategory.GATHA_TICKET:
            text3    = StringMaster.GetString("ConsumeUnitTicket");
            iconType = CMD_ClearingHouse.IconType.NON;
            break;

        case MasterDataMng.AssetCategory.MEAT:
            iconType = CMD_ClearingHouse.IconType.SPRITE;
            break;

        case MasterDataMng.AssetCategory.SOUL:
            text3    = StringMaster.GetString("ConsumeUnitPlugin");
            iconType = CMD_ClearingHouse.IconType.TEXTURE;
            break;

        case MasterDataMng.AssetCategory.DUNGEON_TICKET:
            text3    = StringMaster.GetString("ConsumeUnitTicket");
            iconType = CMD_ClearingHouse.IconType.TEXTURE;
            break;
        }
        string exchangeDetailName = exchangeItem.exchangeDetailName;
        string info = string.Format(StringMaster.GetString("ExchangeConfirmInfo"), new object[]
        {
            text2,
            this.consumeNum,
            text3,
            exchangeDetailName
        });
        CMD_ChangePOP cd = GUIMain.ShowCommonDialog(null, "CMD_ChangePOP", null) as CMD_ChangePOP;

        cd.Title = StringMaster.GetString("ExchangeConfirmTitle");
        cd.Info  = info;
        cd.SetPoint(exchangeItem.exchangeItemData.count, int.Parse(this.consumeNum));
        if (iconType == CMD_ClearingHouse.IconType.SPRITE)
        {
            cd.SetSpriteIcon(this.exchangeItemPathList[num]);
        }
        else if (iconType == CMD_ClearingHouse.IconType.TEXTURE)
        {
            cd.SetTextureIcon(this.exchangeItemPathList[num]);
        }
        cd.OnPushedYesAction = delegate()
        {
            cd.ClosePanel(true);
            this.AccessExchangeLogic(exchangeItem);
        };
    }
コード例 #21
0
ファイル: FillEngine.cs プロジェクト: xhqiao89/HydroDesktop
        public override IValueSet GetEngineValues(ExchangeItem exchangeItem)
        {
            //--- give output items ---

            IList values = new List <string>();

            if (exchangeItem is EngineInputItem)
            {
                // Input item, provide current input values
                if (exchangeItem == _InputItem)
                {
                    values.Add(_Inpath);

                    //determine outpath
                    string[] inpath = _Inpath.Split('/');
                    int      l      = inpath[inpath.Length].Length;
                    _Outpath  = _Inpath.Remove(inpath.Length - l);
                    _Outpath += exchangeItem.Id + "_Fill";
                }
                else
                {
                    throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
                }
            }
            else if (exchangeItem is EngineOutputItem)
            {
                // Output item, provide computed values
                if (exchangeItem == _OutputItem)
                {
                    //if (_Outpath == null)
                    //{
                    //if no values exist, then run perform time step to calculate them
                    ICollection <EngineOutputItem> outputs = new Collection <EngineOutputItem>();
                    outputs.Add(_outputExchangeItems[0]);
                    this.PerformTimestep(outputs);

                    if (_Outpath != null)
                    {
                        values.Add(_Outpath);
                    }
                    else
                    {
                        //if output path is still null, try updating inputs
                        _inputExchangeItems[0].Update();
                        //this.ProcessActiveInputItems();
                        this.PerformTimestep(outputs);
                    }

                    if (_Outpath == null)
                    {
                        values.Add(null);
                    }
                    else
                    {
                        values.Add(_Outpath);
                    }

                    //}
                    //else
                    //{
                    //    values.Add(_Outpath);
                    //}
                }
                else
                {
                    throw new ArgumentException("Unknown Exchange Item Id: \"" + exchangeItem.Id + "\"", "exchangeItem");
                }
            }
            else
            {
                throw new Exception("Should be EngineInputItem or EngineOutputItem");
            }
            //clear output
            this._Outpath = null;
            return(new ValueSet(new List <IList> {
                values
            }));
        }
コード例 #22
0
    void InitializeGame()
    {
        materials[0]  = HouseMaterial;
        materials[1]  = MineMaterial;
        materials[2]  = RefineryMaterial;
        materials[3]  = ForestMaterial;
        materials[4]  = LumbermillMaterial;
        materials[5]  = WorkshopMaterial;
        materials[6]  = FarmMaterial;
        materials[7]  = MillMaterial;
        materials[8]  = AnimalFarmMaterial;
        materials[9]  = SlaughterhouseMaterial;
        materials[10] = FoodFactoryMaterial;
        materials[11] = ShopMaterial;

        EntityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        #region Archetype declaration
        ComponentType[] genericLocationComponents = new ComponentType[]
        {
            typeof(LocationTagComponent),
            typeof(IdComponent),

            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(RenderBounds),

            typeof(Translation),
            typeof(Rotation),
            typeof(Scale),
            typeof(SizeComponent),

            typeof(LocationInfoComponent),

            typeof(NeedsInventoryComponent),
            typeof(NeedsStartingResourcesTagComponent),
            typeof(BuyerComponent),
            typeof(SellerComponent),
            typeof(ManufacturerComponent),
            typeof(WorkplaceInfoComponent),
        };
        LocationArchetype = EntityManager.CreateArchetype(genericLocationComponents);


        UnitArchetype = EntityManager.CreateArchetype(
            typeof(UnitTagComponent),
            typeof(IdComponent),
            typeof(NeedsInventoryComponent),

            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(RenderBounds),

            typeof(Translation),
            typeof(Rotation),
            typeof(Scale),

            typeof(ParentLocationComponent),
            typeof(MovementTargetComponent),
            typeof(RadialComponent),
            typeof(HungerComponent),
            typeof(SpeedComponent),
            typeof(NeedsAndDutiesComponent),
            typeof(SpecializationComponent)
            );

        VacancyArchetype = EntityManager.CreateArchetype(
            typeof(VacancyTagComponent),
            typeof(IdComponent),

            typeof(ParentLocationComponent),
            typeof(WeekScheduleComponent),
            typeof(PaymentComponent),
            typeof(RelatedUnitComponent),
            typeof(VacancyTypeComponent)
            );
        #endregion

        locationLists = new NativeList <Entity> [LocationTypesAmount];
        for (int i = 0; i < LocationTypesAmount; i++)
        {
            locationLists[i] = new NativeList <Entity>(Allocator.Persistent);
        }


        #region Location generation
        var numbersAmounts = new int[12];
        numbersAmounts[(int)LocationType.LivingHouse]    = HousesCount;
        numbersAmounts[(int)LocationType.Store]          = StoresCount;
        numbersAmounts[(int)LocationType.Mine]           = MineCount;
        numbersAmounts[(int)LocationType.Refinery]       = RefineryCount;
        numbersAmounts[(int)LocationType.Forest]         = ForestCount;
        numbersAmounts[(int)LocationType.Lumbermill]     = LumbermillCount;
        numbersAmounts[(int)LocationType.Workshop]       = WorkshopCount;
        numbersAmounts[(int)LocationType.Farm]           = FarmCount;
        numbersAmounts[(int)LocationType.Mill]           = MillCount;
        numbersAmounts[(int)LocationType.AnimalFarm]     = AnimalFarmCount;
        numbersAmounts[(int)LocationType.Slaughterhouse] = SlaughterhouseCount;
        numbersAmounts[(int)LocationType.FoodFactory]    = FoodFactoryCount;
        int[,] grid;
        if (ShowcaseGrid)
        {
            grid = ShowcaseMatrix();
        }
        else if (Autosize)
        {
            grid = GenerateSquareMatrixWithAutoSize(numbersAmounts);
        }
        else
        {
            grid = GenerateMatrix(numbersAmounts, Width, Height);
        }
        CreateLocationsGrid(grid);

        var allLocations = new NativeList <Entity>(Allocator.Persistent);
        for (int i = 0; i < locationLists.Length; i++)
        {
            for (int j = 0; j < locationLists[i].Length; j++)
            {
                allLocations.Add(locationLists[i][j]);
            }
        }

        foreach (var location in allLocations)
        {
            EntityManager.AddBuffer <ExchangeRecipeBufferElement>(location);
        }

        foreach (var mine in locationLists[(int)LocationType.Mine])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("tools", 1) };
            var results = new ExchangeItem[] { new ExchangeItem("ore", 3) };
            mine.Manufactures(sources, results, "ore", 3);

            mine.Buys("tools");
            mine.Sells("ore", 5, 6);
        }
        foreach (var refinery in locationLists[(int)LocationType.Refinery])
        {
            var sources = new ExchangeItem[] {
                new ExchangeItem("ore", 1),
                new ExchangeItem("tools", 1)
            };
            var results = new ExchangeItem[] { new ExchangeItem("metal", 2) };
            refinery.Manufactures(sources, results, "metal", 2);

            refinery.Buys("tools");
            refinery.Buys("ore");
            refinery.Sells("metal", 7, 8);
        }
        foreach (var forest in locationLists[(int)LocationType.Forest])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("tools", 1) };
            var results = new ExchangeItem[] { new ExchangeItem("logs", 3) };
            forest.Manufactures(sources, results, "logs", 3);

            forest.Buys("tools");
            forest.Sells("logs", 5, 6);
        }
        foreach (var lumbermill in locationLists[(int)LocationType.Lumbermill])
        {
            var sources = new ExchangeItem[] {
                new ExchangeItem("logs", 1),
                new ExchangeItem("tools", 1)
            };
            var results = new ExchangeItem[] { new ExchangeItem("wood", 2) };
            lumbermill.Manufactures(sources, results, "wood", 2);

            lumbermill.Buys("tools");
            lumbermill.Buys("logs");
            lumbermill.Sells("wood", 7, 8);
        }
        foreach (var workshop in locationLists[(int)LocationType.Workshop])
        {
            var sources = new ExchangeItem[] {
                new ExchangeItem("metal", 1),
                new ExchangeItem("wood", 1)
            };
            var results = new ExchangeItem[] { new ExchangeItem("tools", 5) };
            workshop.Manufactures(sources, results, "tools", 5);

            workshop.Buys("metal");
            workshop.Buys("wood");
            workshop.Sells("tools", 9, 10);
        }
        foreach (var farm in locationLists[(int)LocationType.Farm])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("tools", 1) };
            var results = new ExchangeItem[] {
                new ExchangeItem("veggies", 1),
                new ExchangeItem("grain", 1)
            };
            farm.Manufactures(sources, results, "grain", 1);

            farm.Buys("tools");
            farm.Sells("veggies", 6, 7);
            farm.Sells("grain", 6, 7);
        }
        foreach (var mill in locationLists[(int)LocationType.Mill])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("grain", 1) };
            var results = new ExchangeItem[] { new ExchangeItem("animalFeed", 1) };
            mill.Manufactures(sources, results, "animalFeed", 1);

            mill.Buys("grain");
            mill.Sells("animalFeed", 8, 9);
        }
        foreach (var animalFarm in locationLists[(int)LocationType.AnimalFarm])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("animalFeed", 1) };
            var results = new ExchangeItem[] { new ExchangeItem("livestock", 1) };
            animalFarm.Manufactures(sources, results, "livestock", 1);

            animalFarm.Buys("animalFeed");
            animalFarm.Sells("livestock", 10, 11);
        }
        foreach (var slaughterhouse in locationLists[(int)LocationType.Slaughterhouse])
        {
            var sources = new ExchangeItem[] { new ExchangeItem("livestock", 1) };
            var results = new ExchangeItem[] { new ExchangeItem("meat", 1) };
            slaughterhouse.Manufactures(sources, results, "meat", 1);

            slaughterhouse.Buys("livestock");
            slaughterhouse.Sells("meat", 12, 13);
        }
        foreach (var foodFactory in locationLists[(int)LocationType.FoodFactory])
        {
            var sources = new ExchangeItem[] {
                new ExchangeItem("meat", 1),
                new ExchangeItem("veggies", 1)
            };
            var results = new ExchangeItem[] { new ExchangeItem("rawFood", 3) };
            foodFactory.Manufactures(sources, results, "rawFood", 3);

            foodFactory.Buys("meat");
            foodFactory.Buys("veggies");
            foodFactory.Sells("rawFood", 21, 22);
        }
        foreach (var store in locationLists[(int)LocationType.Store])
        {
            store.Buys("rawFood");
            store.Sells("rawFood", 23, 24);
        }

        for (int i = (int)LocationType.Mine; i <= (int)LocationType.Store; i++)
        {
            foreach (var buyer in locationLists[i])
            {
                var buyerComponent = EntityManager.GetComponentData <BuyerComponent>(buyer);
                for (int j = 0; j < buyerComponent.BoughtResources.Length; j++)
                {
                    var boughtResource = buyerComponent.BoughtResources[j];
                    var sellers        = new NativeList <Entity>(Allocator.Temp);
                    var sellersHashes  = new List <int>();
                    foreach (var seller in allLocations)
                    {
                        if (!EntityManager.HasComponent <SellerComponent>(seller))
                        {
                            continue;
                        }
                        var sellerComponent = EntityManager.GetComponentData <SellerComponent>(seller);
                        var soldResources   = sellerComponent.SoldResources;
                        foreach (var soldResource in soldResources)
                        {
                            if (soldResource.ResourceName == boughtResource.ResourceName && EntityManager.GetComponentData <LocationInfoComponent>(seller).Type != LocationType.Store)
                            {
                                sellers.Add(seller);
                                sellersHashes.Add(soldResource.RecipeHash);
                            }
                        }
                    }
                    if (sellers.Length == 0)
                    {
                        continue;
                    }
                    var partnerNumber = UnityEngine.Random.Range(0, sellers.Length);
                    var partner       = sellers[partnerNumber];
                    var partnerHash   = sellersHashes[partnerNumber];
                    var recipes       = EntityManager.GetBuffer <ExchangeRecipeBufferElement>(partner);
                    var recipe        = recipes.GetRecipe(partnerHash);
                    buyerComponent.BoughtResources[j] = new BoughtResource()
                    {
                        ResourceName = boughtResource.ResourceName,
                        OrderSize    = 20,
                        ReserveSize  = 100,
                        Provider     = partner,
                        RecipeHash   = recipe.Hash
                    };
                    sellers.Dispose();
                }
                EntityManager.SetComponentData(buyer, buyerComponent);
            }
        }
        allLocations.Dispose();
        #endregion

        vacancies = new NativeList <Entity>(Allocator.Persistent);
        for (int i = (int)LocationType.Mine; i <= (int)LocationType.FoodFactory; i++)
        {
            foreach (var workplace in locationLists[i])
            {
                int amount = EntityManager.GetComponentData <WorkplaceInfoComponent>(workplace).VacanciesAmount;
                CreateVacancies(workplace, amount);
            }
        }

        Units = new NativeList <Entity>(Allocator.Persistent);
        CreateUnits(UnitsCount);

        #region Static entity
        StaticEntity = EntityManager.CreateEntity(typeof(StaticComponent), typeof(TimeUniqueComponent));
        EntityManager.SetComponentData(StaticEntity, new StaticComponent {
            SimulationSpeed = SimulationSpeed, SpacingMultiplier = SpacingMultiplier, UnitsCount = UnitsCount
        });
        EntityManager.SetComponentData(StaticEntity, new TimeUniqueComponent {
            Day = 1, Seconds = 0
        });
        var locationBuffer = EntityManager.AddBuffer <StoreBufferElement>(StaticEntity);
        for (int i = 0; i < locationLists[(int)LocationType.Store].Length; i++)
        {
            locationBuffer.Add(new StoreBufferElement {
                Location = locationLists[(int)LocationType.Store][i]
            });
        }
        var vacancyBuffer = EntityManager.AddBuffer <VacancyInfoBufferElement>(StaticEntity);
        for (int i = 0; i < vacancies.Length; i++)
        {
            var  vacancy  = vacancies[i];
            var  employee = EntityManager.GetComponentData <RelatedUnitComponent>(vacancy).Entity;
            bool isFree   = employee == default;
            vacancyBuffer.Add(new VacancyInfoBufferElement {
                Vacancy = vacancy, IsFree = isFree, Employee = employee
            });
        }
        #endregion

        vacancies.Dispose();

        StatTrackers.Add(CreateSatietyTracker("Unit satiety", true, true, true, Units));
        StatTrackers.Add(CreateResourceStatTracker("Unit", "money", true, true, true, Units));
        StatTrackers.Add(CreateResourceStatTracker("Mine", "ore", false, false, true, locationLists[(int)LocationType.Mine]));
        StatTrackers.Add(CreateResourceStatTracker("Refinery", "metal", false, false, true, locationLists[(int)LocationType.Refinery]));
        StatTrackers.Add(CreateResourceStatTracker("Forest", "logs", false, false, true, locationLists[(int)LocationType.Forest]));
        StatTrackers.Add(CreateResourceStatTracker("Lumbermill", "wood", false, false, true, locationLists[(int)LocationType.Lumbermill]));
        StatTrackers.Add(CreateResourceStatTracker("Workshop", "tools", false, false, true, locationLists[(int)LocationType.Workshop]));
        StatTrackers.Add(CreateResourceStatTracker("Farm", "veggies", false, false, true, locationLists[(int)LocationType.Farm]));
        StatTrackers.Add(CreateResourceStatTracker("Farm", "grain", false, false, true, locationLists[(int)LocationType.Farm]));
        StatTrackers.Add(CreateResourceStatTracker("Mill", "animalFeed", false, false, true, locationLists[(int)LocationType.Mill]));
        StatTrackers.Add(CreateResourceStatTracker("Animal Farm", "livestock", false, false, true, locationLists[(int)LocationType.AnimalFarm]));
        StatTrackers.Add(CreateResourceStatTracker("Slaughterhouse", "meat", false, false, true, locationLists[(int)LocationType.Slaughterhouse]));
        StatTrackers.Add(CreateResourceStatTracker("Food factory", "rawFood", false, false, true, locationLists[(int)LocationType.FoodFactory]));
        StatTrackers.Add(CreateResourceStatTracker("Store", "money", false, false, true, locationLists[(int)LocationType.Store]));

        Units.Dispose();

        for (int i = 0; i < locationLists.Length; i++)
        {
            locationLists[i].Dispose();
        }

        GetComponent <UiManager>().started = true;
    }
コード例 #23
0
        /// <inheritdoc cref="IExchangeGrabService.GetList(ExchangeFilter)"/>
        public ServiceResult <IList <Exchange> > GetList(ExchangeFilter filter)
        {
            var method = MethodBase.GetCurrentMethod();
            var result = new ServiceResult <IList <Exchange> >();

            result.InnerResult = new List <Exchange>();
            if (!filter.Date.HasValue)
            {
                filter.Date = DateTime.Now;
            }

            var queryStartDate = filter.Date.Value.AddDays(-10).Date.ToString("yyyy/MM/dd");
            var queryEndDate   = filter.Date.Value.Date.ToString("yyyy/MM/dd");

            var client  = new RestClient("https://www.taifex.com.tw/cht/3/dailyFXRate");
            var request = new RestRequest(Method.POST);

            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", $"queryStartDate={queryStartDate.UrlEncode()}&queryEndDate={queryEndDate.UrlEncode()}", "application/x-www-form-urlencoded", ParameterType.RequestBody);
            var response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(response.Content);
                _logger.LogTrace(response.Content);
                var count = 0;
                foreach (var row in doc.DocumentNode.SelectNodes("//*[contains(@class, \"table_c\")]/tbody/tr"))
                {
                    count++;
                    if (count == 1)
                    {
                        continue;
                    }

                    // 日期 美元/新台幣 人民幣/新台幣 歐元/美元 美元/日幣 英鎊/美元 澳幣/美元 美元/港幣 美元/人民幣 美元/南非幣 紐幣/美元
                    var items = row.SelectNodes("td");
                    if (items.Count > 0 &&
                        !string.IsNullOrEmpty(items[(int)ExchangeProps.Date].InnerText) &&
                        !string.IsNullOrWhiteSpace(Regex.Unescape(items[(int)ExchangeProps.UsdTwd].InnerText.Replace("-", string.Empty))))
                    {
                        var item = new Exchange()
                        {
                            Date = DateTime.Parse(items[(int)ExchangeProps.Date].InnerText),
                            Data = new List <ExchangeItem>(),
                        };

                        for (var i = (int)ExchangeProps.UsdTwd; i < (int)ExchangeProps.End; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(Regex.Unescape(items[i].InnerText.Replace("-", string.Empty))))
                            {
                                var value   = decimal.Parse(Regex.Unescape(items[i].InnerText));
                                var subItem = new ExchangeItem()
                                {
                                    Id    = ((ExchangeProps)i).ExtGetDescription(),
                                    Value = value
                                };

                                if (subItem.Value > 0)
                                {
                                    item.Data.Add(subItem);
                                }
                            }
                        }

                        if (item.Data.Count > 0)
                        {
                            result.InnerResult.Add(item);
                        }
                    }
                }
            }
            else
            {
                _logger.LogError(result.InnerException, $"{method.Name} raise exception in RESTSharp");
            }

            result.IsSuccess = true;
            return(result);
        }
コード例 #24
0
        private static void CreateConsumers(IDependencyResolver resolver, IAdvancedBus advancedBus, ExchangeItem exchangeItem)
        {
            if (exchangeItem.RabbitExchange == null)
            {
                throw new ArgumentException("rabbit exchange is null`");
            }

            foreach (var income in exchangeItem.In)
            {
                var queue = advancedBus.QueueDeclare(string.Format("{0}.{1}", exchangeItem.Name, income.Key));
                advancedBus.Bind(exchangeItem.RabbitExchange, queue, income.Key);

                var messageType = ReflectionHelper.ResolveType(income.Type);

                if (messageType == null)
                {
                    throw new Exception("no such message type");
                }

                Type consType     = ReflectionHelper.ResolveType(income.React);
                var  consumer     = resolver.Resolve(consType);
                var  endpointInfo = EndpointInfoFactory.Create(advancedBus, exchangeItem.RabbitExchange, income.Name, income.Key);

                var handlerReg = GetHandlerRegistration(endpointInfo, consumer, messageType);


                IList <object> consumeInvokeParams = new List <object>();
                consumeInvokeParams.Add(queue);

                var action = ConsumeWrapperProvider.GetConsumeActionWrapper(handlerReg, resolver);
                consumeInvokeParams.Add(action);

                if (!ConsumerActions.TryAdd(consumer.GetType(), action))
                {
                    Logger.Warn("can't add consumer handler for {0}", consumer.GetType().ToString());
                }

                Action <IConsumerConfiguration> consConf = configuration => configuration.WithPrefetchCount(exchangeItem.PrefetchCount);
                consumeInvokeParams.Add(consConf);

                //NOTE: Such ugly shit to get generic overloaded method
                var sbConsume = typeof(IAdvancedBus).GetMethods().Where(x => x.Name == "Consume").Select(m => new
                {
                    Method = m,
                    Params = m.GetParameters(),
                    Args   = m.GetGenericArguments()
                }).Where(x => x.Params.Length == 3 && x.Args.Length == 0 &&
                         x.Params[1].ParameterType.Name == action.GetType().Name)
                                .Select(x => x.Method)
                                .First();
                sbConsume.Invoke(advancedBus, consumeInvokeParams.ToArray());
            }
        }
    // 接收WebRPC回傳
    void OnWebRpcResponse(OperationResponse operationResponse)
    {
        if (operationResponse.ReturnCode != 0)
        {
            Debug.Log("WebRPC 操作失敗. Response: " + operationResponse.ToStringFull());
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
            return;
        }
        WebRpcResponse webRpcResponse = new WebRpcResponse(operationResponse);

        if (webRpcResponse.ReturnCode != 0)
        {
            Debug.Log("WebRPC '" + webRpcResponse.Name + "發生問題. Error: " + webRpcResponse.ReturnCode + " Message: " + webRpcResponse.DebugMessage);
            return;
        }
        Dictionary <string, object> parameters = webRpcResponse.Parameters;

        foreach (KeyValuePair <string, object> pair in parameters)
        {
            countObject++;
            if (countObject == parameters.Count)
            {
                tempReturnValue += string.Format(@"""{0}"" : ""{1}""", pair.Key, pair.Value);
            }
            else
            {
                tempReturnValue += string.Format(@"""{0}"" : ""{1}""", pair.Key, pair.Value) + ", ";
            }
        }
        //判斷事件
        if ((string)parameters["callnumber"] == "1")
        {
            contractStatus = JsonUtility.FromJson <ContractStatus>("{" + tempReturnValue + "}");
        }
        else if ((string)parameters["callnumber"] == "2")
        {
            listenEvent_New = JsonUtility.FromJson <ListenEvent_New>("{" + tempReturnValue + "}");
            waitMessage     = false;
            listenStatus    = "finished";
        }
        else if ((string)parameters["callnumber"] == "3")
        {
            allowance       = JsonUtility.FromJson <Allowance>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
            CheckBalanceOf();
        }
        else if ((string)parameters["callnumber"] == "4")
        {
            balanceOf       = JsonUtility.FromJson <BalanceOf>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "5")
        {
            giveApprove     = JsonUtility.FromJson <GiveApprove>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "6")
        {
            twoPointDeal    = JsonUtility.FromJson <TwoPointDeal>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "7")
        {
            putExchange     = JsonUtility.FromJson <PutExchange>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "8")
        {
            lookExchange_Self = JsonUtility.FromJson <LookExchange_Self>("{" + tempReturnValue + "}");
            transformStatus   = "finished";
            waitProcess       = "";
            listenStatus      = "finished";
            ChangbuttonOnOrOff(true);
            CheckBalanceOf();
        }
        else if ((string)parameters["callnumber"] == "9")
        {
            lookExchange_Other = JsonUtility.FromJson <LookExchange_Other>("{" + tempReturnValue + "}");
            transformStatus    = "finished";
            waitProcess        = "";
            listenStatus       = "finished";
            ChangbuttonOnOrOff(true);
            StartLookExchange_Self();
        }
        else if ((string)parameters["callnumber"] == "10")
        {
            exchangeStatus  = JsonUtility.FromJson <ExchangeStatus>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "11")
        {
            cancelExchange  = JsonUtility.FromJson <CancelExchange>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "12")
        {
            exchangeItem    = JsonUtility.FromJson <ExchangeItem>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "13")
        {
            buyLottery      = JsonUtility.FromJson <BuyLottery>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
        }
        else if ((string)parameters["callnumber"] == "14")
        {
            lookLottery     = JsonUtility.FromJson <LookLottery>("{" + tempReturnValue + "}");
            transformStatus = "finished";
            waitProcess     = "";
            listenStatus    = "finished";
            ChangbuttonOnOrOff(true);
            CheckBalanceOf();
        }
        //清空暫存內容
        countObject     = 0;
        tempReturnValue = "";
    }
コード例 #26
0
ファイル: JobCraftSkill.cs プロジェクト: XaferDev/Crystal
        public void MoveCraftItem(Network.WorldClient client, string packet)
        {
            string data     = packet.Substring(4);
            char   typeMove = packet[3];

            string[] itemsInfos = data.Split('|');

            int itemID   = int.Parse(itemsInfos[0]);
            int quantity = int.Parse(itemsInfos[1]);

            if (quantity <= 0)
            {
                return;
            }

            if (this.Items.Count > this.BaseSkill.GetJobCraftMax())
            {
                return;
            }

            var item = client.Character.Items.GetItem(itemID);

            switch (typeMove)
            {
            case '+':
                ExchangeItem exchangedItem = null;
                if (HaveOneOfThisItem(client, item))
                {
                    exchangedItem = GetOneOfThisItem(client, item);
                    if (exchangedItem != null)
                    {
                        exchangedItem.Add(quantity);
                    }
                }
                else
                {
                    if (quantity <= item.Quantity)
                    {
                        exchangedItem = new ExchangeItem(item, quantity);
                        this.Items.Add(exchangedItem);
                    }
                }
                client.Send("EMKO+" + exchangedItem.WItem.ID + "|" + exchangedItem.Quantity);
                break;

            case '-':
                if (HaveOneOfThisItem(client, item))
                {
                    var removedItem = GetOneOfThisItem(client, item);
                    if (removedItem != null)
                    {
                        if (removedItem.Remove(quantity))
                        {
                            client.Send("EMKO-" + removedItem.WItem.ID);
                            this.Items.Remove(removedItem);
                        }
                        else
                        {
                            client.Send("EMKO+" + removedItem.WItem.ID + "|" + removedItem.Quantity);
                        }
                    }
                }
                break;
            }
        }
コード例 #27
0
        public static ExchangeMailboxAuditGroupRecord CreateMailboxGroupRecord(MailboxSession mailboxSession, MailboxAuditOperations operation, COWSettings settings, LogonType effectiveLogonType, bool externalAccess, StoreSession destinationSession, StoreObjectId destinationFolderId, StoreObjectId[] itemIds, GroupOperationResult result, IDictionary <StoreObjectId, FolderAuditInfo> folders, IDictionary <StoreObjectId, ItemAuditInfo> items, IDictionary <StoreObjectId, FolderAuditInfo> parentFolders)
        {
            Util.ThrowOnNullArgument(settings, "settings");
            ExchangeMailboxAuditGroupRecord exchangeMailboxAuditGroupRecord = new ExchangeMailboxAuditGroupRecord();

            AuditRecordFactory.Fill(exchangeMailboxAuditGroupRecord, mailboxSession, operation, (result == null) ? OperationResult.Failed : result.OperationResult, effectiveLogonType, externalAccess);
            if (settings.CurrentFolderId != null)
            {
                exchangeMailboxAuditGroupRecord.Folder    = (exchangeMailboxAuditGroupRecord.Folder ?? new ExchangeFolder());
                exchangeMailboxAuditGroupRecord.Folder.Id = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    settings.CurrentFolderId
                });
                FolderAuditInfo folderAuditInfo;
                parentFolders.TryGetValue(settings.CurrentFolderId, out folderAuditInfo);
                exchangeMailboxAuditGroupRecord.Folder.PathName = ((folderAuditInfo != null) ? folderAuditInfo.PathName : AuditRecordFactory.GetCurrentFolderPathName(mailboxSession, settings));
            }
            bool flag = destinationSession != null && mailboxSession != destinationSession;

            exchangeMailboxAuditGroupRecord.CrossMailboxOperation = new bool?(flag);
            MailboxSession mailboxSession2 = mailboxSession;

            if (flag && destinationSession is MailboxSession)
            {
                mailboxSession2 = (destinationSession as MailboxSession);
                exchangeMailboxAuditGroupRecord.DestMailboxGuid     = new Guid?(mailboxSession2.MailboxOwner.MailboxInfo.MailboxGuid);
                exchangeMailboxAuditGroupRecord.DestMailboxOwnerUPN = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    mailboxSession2.MailboxOwner.MailboxInfo.PrimarySmtpAddress
                });
                if (mailboxSession2.MailboxOwner.Sid != null)
                {
                    exchangeMailboxAuditGroupRecord.DestMailboxOwnerSid = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                    {
                        mailboxSession2.MailboxOwner.Sid
                    });
                    if (mailboxSession2.MailboxOwner.MasterAccountSid != null)
                    {
                        exchangeMailboxAuditGroupRecord.DestMailboxOwnerMasterAccountSid = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                        {
                            mailboxSession2.MailboxOwner.MasterAccountSid
                        });
                    }
                }
            }
            if (destinationFolderId != null)
            {
                exchangeMailboxAuditGroupRecord.DestFolder    = (exchangeMailboxAuditGroupRecord.DestFolder ?? new ExchangeFolder());
                exchangeMailboxAuditGroupRecord.DestFolder.Id = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    destinationFolderId
                });
                string    text = null;
                Exception ex   = null;
                try
                {
                    using (Folder folder = Folder.Bind(mailboxSession2, destinationFolderId, new PropertyDefinition[]
                    {
                        FolderSchema.FolderPathName
                    }))
                    {
                        if (folder != null)
                        {
                            text = (folder.TryGetProperty(FolderSchema.FolderPathName) as string);
                            if (text != null)
                            {
                                text = text.Replace(COWSettings.StoreIdSeparator, '\\');
                            }
                        }
                    }
                }
                catch (StorageTransientException ex2)
                {
                    ex = ex2;
                }
                catch (StoragePermanentException ex3)
                {
                    ex = ex3;
                }
                if (ex != null)
                {
                    ExTraceGlobals.SessionTracer.TraceError <StoreObjectId, Exception>((long)mailboxSession.GetHashCode(), "[GroupOperationAuditEventRecordAdapter::ToString] failed to get FolderPathName property of destination folder {0}. Exception: {1}", destinationFolderId, ex);
                }
                if (text != null)
                {
                    exchangeMailboxAuditGroupRecord.DestFolder.PathName = text;
                }
            }
            foreach (KeyValuePair <StoreObjectId, FolderAuditInfo> keyValuePair in folders)
            {
                StoreObjectId   key   = keyValuePair.Key;
                FolderAuditInfo value = keyValuePair.Value;
                if (settings.CurrentFolderId == null || !key.Equals(settings.CurrentFolderId))
                {
                    exchangeMailboxAuditGroupRecord.Folders = (exchangeMailboxAuditGroupRecord.Folders ?? new List <ExchangeFolder>(folders.Count));
                    ExchangeFolder exchangeFolder = new ExchangeFolder();
                    exchangeMailboxAuditGroupRecord.Folders.Add(exchangeFolder);
                    exchangeFolder.Id = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                    {
                        key
                    });
                    if (value.PathName != null)
                    {
                        exchangeFolder.PathName = value.PathName;
                    }
                }
            }
            foreach (KeyValuePair <StoreObjectId, ItemAuditInfo> keyValuePair2 in items)
            {
                StoreObjectId key2   = keyValuePair2.Key;
                ItemAuditInfo value2 = keyValuePair2.Value;
                exchangeMailboxAuditGroupRecord.SourceItems = (exchangeMailboxAuditGroupRecord.SourceItems ?? new List <ExchangeItem>(items.Count));
                ExchangeItem exchangeItem = new ExchangeItem();
                exchangeMailboxAuditGroupRecord.SourceItems.Add(exchangeItem);
                exchangeItem.Id = string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    key2
                });
                if (value2.Subject != null)
                {
                    exchangeItem.Subject = value2.Subject;
                }
                FolderAuditInfo folderAuditInfo2;
                if (value2.ParentFolderId != null && parentFolders.TryGetValue(value2.ParentFolderId, out folderAuditInfo2))
                {
                    exchangeItem.ParentFolder          = (exchangeItem.ParentFolder ?? new ExchangeFolder());
                    exchangeItem.ParentFolder.PathName = folderAuditInfo2.PathName;
                }
            }
            return(exchangeMailboxAuditGroupRecord);
        }