Beispiel #1
0
 private void ResetChangeDataStatuses(ChangeData changeData)
 {
     changeData.RecipientStatus = ChangeData.RequestStatus.NotStarted;
     changeData.RecipientResult = null;
     changeData.ManagerStatus   = ChangeData.RequestStatus.NotStarted;
     changeData.ManagerResult   = null;
 }
        private List <ChangeData> CalculateEntities(long changeAmount)
        {
            long changeRest = changeAmount;

            List <ChangeData> changeDataCollection = new List <ChangeData>();

            while (changeRest > 0)
            {
                ChangeData currentData = new ChangeData();

                AbstractProcessor      proc         = ProcessorFactory.CreateProcessor(changeRest);
                Dictionary <int, long> monetaryObjs = proc.CalculateChange(changeRest);

                currentData.Name             = proc.GetName();
                currentData.ChangeDictionary = monetaryObjs.Where(p => p.Value > 0).ToDictionary(p => p.Key, p => p.Value);

                long currentProduct = monetaryObjs.Sum(p => p.Key * p.Value);

                changeRest = changeRest - currentProduct;

                changeDataCollection.Add(currentData);

                // Dispara o evento informando que um processador foi executado.
                if (this.OnProcessorExecuted != null)
                {
                    string nameProcessor = proc.GetName();

                    this.OnProcessorExecuted(this, nameProcessor, currentProduct);
                }
            }

            return(changeDataCollection);
        }
Beispiel #3
0
    private void Confirm()
    {
        var animator = character.GetComponent <Animator>();

        animator.SetInteger("Skill", 2);
        UnityEngine.Object.Destroy(restoreChakraUI);

        RoundManager.GetInstance().Invoke(() => {
            animator.speed = 0;
            FXManager.GetInstance().Spawn("Chakra", animator.GetBoneTransform(HumanBodyBones.Chest).position, 3f);
        }, 0.5f);
        RoundManager.GetInstance().Invoke(() => {
            animator.speed = 1;
            animator.SetInteger("Skill", 0);
            var currentHp    = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "hp").value;
            var mud          = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mud").value;
            var restoreValue = slider.value - character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mp").value;
            var hp           = currentHp - mud * restoreValue;
            ChangeData.ChangeValue(character, "hp", (int)hp);
            ChangeData.ChangeValue(character, "mp", (int)slider.value);

            UIManager.GetInstance().FlyNum(character.GetComponent <CharacterStatus>().arrowPosition / 2 + character.position + Vector3.down * 0.2f, restoreValue.ToString(), UIManager.mpColor);

            var buff = new DataBuff(1, "def", -5);
            buff.Apply(character);
            character.GetComponent <CharacterStatus>().Buffs.Add(buff);

            character.GetComponent <Unit>().OnUnitEnd();   //真正的回合结束所应执行的逻辑。
            RoundManager.GetInstance().EndTurn();

            skillState = SkillState.confirm;
        }, 0.5f + 3.4f);
    }
Beispiel #4
0
    // Use this for initialization
    void Start()
    {
        MyData md = new MyData();

        md.x = 10;
        md.y = 20;

        ChangeData cd = new ChangeData();

        cd.change(md);
        print(md.x);
        print(md.y);

        cd.change(ref md);
        print(md.x);
        print(md.y);

        MyData m;

        m.x = 10;
        m.y = 20;
        cd.change(ref m);
        print(m.x);
        print(m.y);

        MyDataClass mdc = new MyDataClass();

        mdc.x = 10;
        mdc.y = 20;
        cd.change(mdc);
        print(mdc.x);
        print(mdc.y);
    }
Beispiel #5
0
 //设定岩墙防御
 private void OnGameStarted(object sender, EventArgs e)
 {
     foreach (var r in rocks)
     {
         ChangeData.ChangeValue(r.transform, "def", r.attributes.Find(d => d.eName == "def").value + 10 * GetRockIntensity(r.gameObject.name));
     }
 }
Beispiel #6
0
    public void Confirm()
    {
        //技能逻辑
        var currentHp    = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "hp").value;
        var currentHPMax = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "hp").valueMax;

        //“修养”接口预留(通过控制factor)

        RoundManager.GetInstance().Invoke(() => {
            var restValue = (int)(currentHPMax * factor);
            restValue     = currentHp + restValue > currentHPMax ? currentHPMax - currentHp : restValue;

            var hp = currentHp + restValue;

            UIManager.GetInstance().FlyNum(character.GetComponent <CharacterStatus>().arrowPosition / 2 + character.position + Vector3.down * 0.2f, restValue.ToString(), UIManager.hpColor);


            ChangeData.ChangeValue(character, "hp", hp);
            //持续到回合结束的防御力debuff
            var buff = new DataBuff(1, "def", -5);
            buff.Apply(character);
            character.GetComponent <CharacterStatus>().Buffs.Add(buff);

            //回合直接结束
            UnityEngine.Object.Destroy(restUI);
            skillState = SkillState.confirm;
            character.GetComponent <Unit>().OnUnitEnd();
            RoundManager.GetInstance().EndTurn();
        }, 0.5f);
    }
Beispiel #7
0
        private void Check_Click(object sender, EventArgs e)
        {
            var queue1 = new MyQueue();
            var queue2 = new MyQueue();

            string[] arr1 = queueBox1.Text.Split(new char[] { ',', ' ', '/' });
            string[] arr2 = queueBox2.Text.Split(new char[] { ',', ' ', '/' });
            for (int i = 0; i < arr1.Length; i++)
            {
                try
                {
                    queue1.Push(Convert.ToDouble(arr1[i]));
                }
                catch (Exception)
                {
                    throw new ArgumentException("Ошибка при считывании аргумента:{0} в очереди 1", arr1[i]);
                }
            }
            for (int i = 0; i < arr2.Length; i++)
            {
                try
                {;
                 queue2.Push(Convert.ToDouble(arr2[i])); }
                catch (Exception)
                {
                    throw new ArgumentException("Ошибка при считывании аргумента:{0} в очереди 1", arr1[i]);
                }
            }
            ResultBox.Text = Convert.ToString(ChangeData.CheckQueue(queue1, queue2));
        }
Beispiel #8
0
        private void DoUpdateWork()
        {
            int c = 0;

            while (this._runUpdateWork)
            {
                c = this._updateEventQueue.Count;

                if (c <= 0)
                {
                    this._bufferRearResetEvent.WaitOne(1);//利用這個waitone來讓CPU的使用率不要爆高
                }
                else
                {
                    //Console.WriteLine("                                                   #C ---> [[[ {0}  ]]] ---> Update ", c);
                }

                while (c > 0)
                {
                    ChangeData newOutcome = null;
                    if (this._updateEventQueue.TryDequeue(out newOutcome))
                    {
                        DispatchNotify(newOutcome);
                        //UpdateGridView(this._symbolGV);
                        //Console.WriteLine("Data Change: [ {0}  => {1} ]", newOutcome.Topic.YwFieldType.ToString(), newOutcome.Data);
                    }
                    c--;
                }
                this._bufferRearResetEvent.Set();
            }
        }
Beispiel #9
0
        private void DispatchNotify(ChangeData notify)
        {
            string symbol = notify.Topic.Symbol;
            ConcurrentDictionary <string, DataGridView> gridMap = null;

            if (this._symbolToGrids.TryGetValue(symbol, out gridMap))
            {
                foreach (DataGridView gv in gridMap.Values)
                {
                    Type dsType = null;
                    if (this._gridNameToType.TryGetValue(gv.Name, out dsType))
                    {
                        if (IsRefreshRequire(notify))
                        {
                            if (IsTypeContainProp(dsType, notify.Topic.FieldName))
                            {
                                //Stopwatch st = Stopwatch.StartNew();
                                UpdateGridView(gv);
                                //Console.WriteLine("{0} : {1} = {2}", notify.Topic.Symbol, notify.Topic.FieldName, notify.Data);
                                //st.Stop();
                                //Console.WriteLine("t->{0} , m->{1}", st.ElapsedTicks, st.ElapsedMilliseconds);
                            }
                        }
                    }
                }
            }
        }
Beispiel #10
0
        private void DoFrontWork()
        {
            int c = 0;

            while (this._runFrontWork)
            {
                this._bufferFrontResetEvent.WaitOne();
                if (this._rtdCore == null)
                {
                    continue;
                }
                c = this._rtdCore.ChangeDataQueue.Count;
                if (c > 0)
                {
                    //Console.WriteLine("A ---> [[[ {0}  ]]] ---> B ", c);
                }


                while (c > 0)
                {
                    ChangeData newIncome = null;
                    if (this._rtdCore.ChangeDataQueue.TryDequeue(out newIncome))
                    {
                        this._bufferEventQueue.Enqueue(newIncome);
                    }
                    c--;
                }
            }
        }
Beispiel #11
0
        private void DoRearWork()
        {
            int c = 0;

            while (this._runRearWork)
            {
                this._bufferRearResetEvent.WaitOne();
                c = this._bufferEventQueue.Count;
                if (c > 0)
                {
                    //Console.WriteLine("                         #B ---> [[[ {0}  ]]] ---> C ", c);
                }


                while (c > 0)
                {
                    ChangeData buffered = null;
                    if (this._bufferEventQueue.TryDequeue(out buffered))
                    {
                        this._updateEventQueue.Enqueue(buffered);
                    }
                    c--;
                }

                this._bufferFrontResetEvent.Set();
            }
        }
Beispiel #12
0
        private void Check_Click(object sender, EventArgs e)
        {
            string[] a      = StackBox1.Text.Split(new char[] { ',', ' ', '/' });
            string[] b      = StackBox2.Text.Split(new char[] { ',', ' ', '/' });
            int      s      = 0;
            var      stack1 = new MyStack();
            var      stack2 = new MyStack();

            for (int i = 0; i < a.Length; i++)
            {
                try
                {
                    stack1.Push(Convert.ToInt32(a[i]));
                }
                catch (Exception)
                {
                    ResBox.Text = "Стек(1) должен оканчиваться числом и состоять из чисел";
                }
            }
            for (int j = 0; j < b.Length; j++)
            {
                try
                {
                    stack2.Push(Convert.ToInt32(b[j]));
                }
                catch (Exception)
                {
                    ResBox.Text = "Стек(2) должен оканчиваться числом и состоять из чисел";
                }
            }
            ResBox.Text = Convert.ToString(ChangeData.CheckStack(stack1, stack2));
        }
 private void ClearOtherStatuses(ChangeData changeData)
 {
     changeData.SenderStatus    = ChangeData.RequestStatus.NotStarted;
     changeData.SenderResult    = null;
     changeData.RecipientStatus = ChangeData.RequestStatus.NotStarted;
     changeData.RecipientResult = null;
 }
        public List <ChangeData> GetAllChangeDetails()
        {
            List <ChangeData> ListChangeData   = new List <ChangeData>();
            string            connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand("Sp_Get_Change_Data", connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;

                connection.Open();
                SqlDataReader datareader = command.ExecuteReader();

                while (datareader.Read())
                {
                    ChangeData changedata = new ChangeData();
                    changedata.StudentName = datareader["StudentName"].ToString();
                    changedata.ActionType  = datareader["ActionType"].ToString();
                    changedata.ActionTable = datareader["ActionTable"].ToString();
                    changedata.Professor   = datareader["Professor"].ToString();

                    ListChangeData.Add(changedata);
                }
            }
            return(ListChangeData);
        }
        public void CalculateEntities_GetChangeWithCoinsOnly_Test()
        {
            CadeMeuTrocoManager manager = new CadeMeuTrocoManager();

            PrivateObject privateObject = new PrivateObject(manager);
            object        objResult     = privateObject.Invoke("CalculateEntities", Convert.ToInt64(170));

            IEnumerable <ChangeData> result = (IEnumerable <ChangeData>)objResult;

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count() == 1);

            ChangeData changeData = result.ElementAt(0);

            Assert.IsTrue("Coin".Equals(changeData.Name, StringComparison.InvariantCultureIgnoreCase) == true);

            Assert.IsTrue(changeData.ChangeDictionary.Count == 3);

            Assert.IsTrue(changeData.ChangeDictionary.ContainsKey(100) == true);
            Assert.IsTrue(changeData.ChangeDictionary.ContainsKey(50) == true);
            Assert.IsTrue(changeData.ChangeDictionary.ContainsKey(10) == true);

            Assert.AreEqual(1, changeData.ChangeDictionary[100]);
            Assert.AreEqual(1, changeData.ChangeDictionary[50]);
            Assert.AreEqual(2, changeData.ChangeDictionary[10]);
        }
        private void VerifyChangeOnServer(ChangeData change, IAsyncContinuation continuation)
        {
            //// For now use different data service context to re-query and verify entities and links.
            //// In the future consider using an 'Oracle' component to re-query the changes if/when it comes online.
            using (IWrapperScope scope = new NullWrapperScope())
            {
                WrappedDataServiceContext otherContext = this.DataServiceContextCreator.CreateContext(scope, this.currentContextData.ContextType, this.currentContextData.BaseUri);
                otherContext.ResolveName = this.currentContextData.ResolveName;
                otherContext.ResolveType = this.currentContextData.ResolveType;
                otherContext.IgnoreResourceNotFoundException = true;

                var uri = change.GetUriForRequery();
                otherContext.Execute <WrappedObject>(
                    continuation,
                    this.Asynchronous,
                    change.ClrTypeForRequery,
                    uri,
                    results =>
                {
                    var result = results.ToList();
                    VerifyChangeOnServer(change, otherContext, result);
                    continuation.Continue();
                });
            }
        }
Beispiel #17
0
    private IEnumerator RockDrama()
    {
        var rockUnits = UnitManager.GetInstance().units.FindAll(p => p.GetComponent <CharacterStatus>().roleEName == "Rock");

        foreach (var u in rockUnits)
        {
            if (u.GetComponent <Unit>().UnitEnd)
            {
                break;
            }
            outline.RenderOutLine(u.transform);
            rtsCamera.FollowTarget(u.transform.position);

            //rock auto recovers
            var currentHp    = u.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "hp").value;
            var currentHPMax = u.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "hp").valueMax;
            var restValue    = (int)(currentHPMax * (0.2f + GetRockIntensity(u.gameObject.name) * 0.1f));
            //if the recover HP makes currentHp full, then Hp gets full
            //else just recovers currentHPMax * (0.2f + GetRockIntensity(u.gameObject.name) * 0.1f) HP
            restValue = currentHp + restValue > currentHPMax ? currentHPMax - currentHp : restValue;

            var hp = currentHp + restValue;

            UIManager.GetInstance().FlyNum(u.GetComponent <CharacterStatus>().arrowPosition / 2 + u.transform.position + Vector3.down * 0.2f, restValue.ToString(), UIManager.hpColor);

            ChangeData.ChangeValue(u.transform, "hp", hp);

            u.OnUnitEnd();   //真正的回合结束所应执行的逻辑。
            DebugLogPanel.GetInstance().Log(u.GetComponent <CharacterStatus>().roleCName + "执行完毕");
            yield return(new WaitForSeconds(1f));
        }

        yield return(0);
    }
Beispiel #18
0
    public void Apply(Transform character)
    {
        var CA = character.GetComponent <CharacterAction>();

        if (itemData != null)
        {
            if (!CA.SetItem(_dodgeName, itemData))
            {
                Debug.Log("Set item False");
            }
            done = true;
        }
        else
        {
            if (!CA.SetSkill(_dodgeName))
            {
                Debug.Log("Set Skill False");
            }
            else
            {
                var currentMP = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mp").value;
                var costMP    = ((UnitSkill)SkillManager.GetInstance().skillList.Find(s => s.EName == _dodgeName)).costMP;
                var mp        = currentMP - costMP;

                ChangeData.ChangeValue(character, "mp", mp);
                done = true;
            }
        }
    }
Beispiel #19
0
 public static dynamic GetTSObject(ChangeData dynObject)
 {
     if (dynObject is null)
     {
         return(null);
     }
     return(dynObject.teklaObject);
 }
 public ChangeViewModel(ChangeData change, PipelineConfiguration config)
     : this(change.Id,
            StringUtils.CompressNewLines(change.Message),
            change.Author?.DisplayName,
            DateTimeHelper.GetLocalTimeWithTimeZone(change.Timestamp),
            LinkHelper.GetCommitLink(change.Id, change.Location.AbsoluteUri, config))
 {
 }
Beispiel #21
0
 public void     BindCallback(string key, Action <object> callback)
 {
     if (!values.ContainsKey(key))
     {
         values[key] = new ChangeData();
     }
     values[key].callback = callback;
 }
Beispiel #22
0
        // This let the ticket salesman remove/cancel reservations. You have to type in the ticketnumber to remove the reservation.
        public static void RemoveReservation()
        {
            Console.WriteLine("\nPlease enter the ticketnumber of the reservation you want to remove:");
            string Cticketnumber = Console.ReadLine();

            ChangeData DeleteTicket = new ChangeData();

            DeleteTicket.DeleteReservation(Cticketnumber);
        }
Beispiel #23
0
        public void PerformFor(ChangeData changeData)
        {
            var change = _changeFactory.CreateOneDescribedBy(changeData);

            if (change != null)
            {
                change.MakeTo(_authorizationStructure);
            }
        }
Beispiel #24
0
    //后处理附加效果
    protected override void PostEffect(Transform o)
    {
        var currentMp = o.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mp").value;

        DebugLogPanel.GetInstance().Log("2 MP" + "(" + character.GetComponent <CharacterStatus>().roleCName + " -> " + o.GetComponent <CharacterStatus>().roleCName + ")");
        var mp = currentMp - 2;

        ChangeData.ChangeValue(o, "mp", mp);
    }
Beispiel #25
0
        public ComputeChangeResponse ComputeChange(ComputeChangeRequest request)
        {
            ComputeChangeResponse response = new ComputeChangeResponse();

            Logger.Log(request);

            try {
                // Verifica se os dados recebidos são válidos.
                if (request.IsValid == false)
                {
                    response.OperationReport = request.ValidationReport;
                    return(response);
                }

                uint change                      = CalculateTotalChangeAmount(request.ReceivedAmount, request.ProductAmount);
                uint totalChangeAmount           = change;
                List <ChangeData> changeDataList = new List <ChangeData>();

                while (change > 0)
                {
                    AbstractProcessor processor = ProcessorFactory.Create(change);

                    if (processor == null)
                    {
                        Report report = new Report();
                        report.Message = "Ocorreu um erro: Não há troco disponível";
                        response.OperationReport.Add(report);
                        return(response);
                    }

                    Dictionary <uint, uint> changeDictionary = processor.Calculate(change);

                    ChangeData changeData = new ChangeData()
                    {
                        Name             = processor.GetName(),
                        ChangeDictionary = changeDictionary
                    };

                    changeDataList.Add(changeData);
                    long totalCurrentAmount = changeDictionary.Sum(p => (p.Value * p.Key));

                    change -= (uint)totalCurrentAmount;
                }
                response.ChangeDataList    = changeDataList;
                response.TotalChangeAmount = totalChangeAmount;
                response.Success           = true;
            }
            catch (Exception e) {
                Logger.Log(e);
                Report report = new Report();
                report.Message = "Ocorreu um erro: não foi possível processar sua operação.";
                response.OperationReport.Add(report);
            }

            Logger.Log(response);
            return(response);
        }
Beispiel #26
0
 //设定岩墙防御
 private void OnGameStarted(object sender, EventArgs e)
 {
     GameController.GetInstance().Invoke(() => {
         foreach (var r in rocks)
         {
             ChangeData.ChangeValue(r.transform, "def", r.attributes.Find(d => d.eName == "def").value + 10 * GetRockIntensity(r.gameObject.name));
         }
     }, 1.5f);
 }
Beispiel #27
0
    public void Undo(Transform character)
    {
        var currentMP = character.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mp").value;
        var costMP    = ((UnitSkill)SkillManager.GetInstance().skillList.Find(s => s.EName == _dodgeName)).costMP;
        var mp        = currentMP - costMP;

        ChangeData.ChangeValue(character, "mp", mp);
        character.GetComponent <Unit>().Buffs.Remove(this);
    }
Beispiel #28
0
 private void OnGameStarted(object sender, EventArgs e)
 {
     for (int i = 1; i < 4; i++)
     {
         ChangeData.ChangeValue(rocks[(weakPoint + i) % 8].transform, "def", rocks[(weakPoint + i) % 8].attributes.Find(d => d.eName == "def").value + 10 * i);
         ChangeData.ChangeValue(rocks[(weakPoint + 8 - i) % 8].transform, "def", rocks[(weakPoint + 8 - i) % 8].attributes.Find(d => d.eName == "def").value + 10 * i);
     }
     ChangeData.ChangeValue(rocks[strongPoint].transform, "def", 50);
 }
Beispiel #29
0
    //后处理附加效果
    protected override void PostEffect(Transform o)
    {
        var damageMP  = 1;
        var currentMp = o.GetComponent <CharacterStatus>().attributes.Find(d => d.eName == "mp").value;
        //DebugLogPanel.GetInstance().Log(damageMP.ToString() + " MP" + "(" + character.GetComponent<CharacterStatus>().roleCName + " -> " + o.GetComponent<CharacterStatus>().roleCName + ")");
        var mp = currentMp - damageMP;

        ChangeData.ChangeValue(o, "mp", mp);
        UIManager.GetInstance().FlyNum(o.GetComponent <CharacterStatus>().arrowPosition / 2 + o.position + Vector3.down * 0.3f, "-" + damageMP.ToString(), new Color(80f / 255f, 248f / 255f, 144f / 255f));
    }
Beispiel #30
0
        public void Menu()
        {
            ShowData SD         = new ShowData();
            bool     checkLogin = true;

            Console.Clear();
            SHA256 encrypter = SHA256.Create();

            while (checkLogin == true)
            {
                Console.WriteLine("\nGive your Username[CaseSenSiTive] or enter [exit] to return to the menu");
                string Username = Console.ReadLine();
                if (Username == "exit")
                {
                    break;
                }
                else if (Username.Contains(" "))
                {
                    Console.WriteLine("You are not using the right format!");
                }
                else
                {
                    Console.WriteLine("Fill in your Password[CaseSenSiTive] or enter [exit] to return to the menu");
                    string Password = Console.ReadLine();
                    if (Password == "exit")
                    {
                        break;
                    }
                    else if (Username.Contains(" "))
                    {
                        Console.WriteLine("You are not using the right format!");
                    }
                    else
                    {
                        ChangeData logincheck = new ChangeData();

                        string encryptedusername = sha256_hash(Username);
                        string encryptedpassword = sha256_hash(Password);

                        string checkeddata = logincheck.checkLoginAndFunction(encryptedusername, encryptedpassword);

                        if (checkeddata != "")
                        {
                            Function   = checkeddata;
                            checkLogin = false;
                        }
                        else
                        {
                            SD.ClearAndErrorMessage("\nWrong Username/Password");
                        }
                    }
                }
            }
        }
        private void VerifyChangeOnServer(ChangeData change, IAsyncContinuation continuation)
        {
            //// For now use different data service context to re-query and verify entities and links.
            //// In the future consider using an 'Oracle' component to re-query the changes if/when it comes online.
            using (IWrapperScope scope = new NullWrapperScope())
            {
                WrappedDataServiceContext otherContext = this.DataServiceContextCreator.CreateContext(scope, this.currentContextData.ContextType, this.currentContextData.BaseUri);
                otherContext.ResolveName = this.currentContextData.ResolveName;
                otherContext.ResolveType = this.currentContextData.ResolveType;
                otherContext.IgnoreResourceNotFoundException = true;

                var uri = change.GetUriForRequery();
                otherContext.Execute<WrappedObject>(
                    continuation, 
                    this.Asynchronous,
                    change.ClrTypeForRequery,
                    uri,
                    results =>
                    {
                        var result = results.ToList();
                        VerifyChangeOnServer(change, otherContext, result);
                        continuation.Continue();
                    });
            }
        }
        private void VerifyChangeOnServer(ChangeData change, WrappedDataServiceContext wrappedContext, List<WrappedObject> result)
        {
            var linkChange = change as LinkChangeData;
            int expectedCount = change.State == EntityStates.Deleted ? 0 : 1;
            if (linkChange != null && linkChange.DescriptorData.TargetDescriptor == null)
            {
                expectedCount = 0;
            }

            this.Assert.AreEqual(expectedCount, result.Count, "Verify only one entity is returned for the uri representing link or descriptor.");

            if (expectedCount == 1)
            {
                var entity = result.Single();

                this.Assert.AreEqual((object)change.ClrTypeForRequery, entity.Product.GetType(), "Verify the CLR type for the query");
                if (linkChange != null)
                {
                    var targetEntity = linkChange.DescriptorData.TargetDescriptor.Entity;
                    ExceptionUtilities.CheckObjectNotNull(targetEntity, "Target was unexpectedly null for link change: {0}", linkChange.ToString());
                    
                    var targetType = this.GetEntityType(targetEntity.GetType());
                    var possibleSets = this.ModelSchema.EntityContainers.SelectMany(c => c.EntitySets).Where(s => targetType.IsKindOf(s.EntityType)).ToList();
                    if (!possibleSets.Any(s => s.Annotations.OfType<EntryIdReplacementAnnotation>().Any(a => a.AppendRequestIdToName)))
                    {
                        var expectedIdentity = linkChange.DescriptorData.TargetDescriptor.Identity;
                        var actualIdentity = wrappedContext.GetEntityDescriptor(entity).Identity;

                        this.Assert.AreEqual(expectedIdentity, actualIdentity, ValueComparer.Instance, "Entity ID did not match for link change: {0}", linkChange.ToString());
                    }
                }
                else if (this.VerifyData)
                {
                    this.VerifyPropertiesValues((EntityChangeData)change, entity.Product);
                }
            }
        }
        private void Queue(DateTime eventTime, XUri channel, XUri resource, string[] origin, XDoc doc) {
            doc.Attr("wikiid", _wikiid).Attr("event-time", eventTime);
            var data = new ChangeData();
            data.Channel = channel;
            data.Resource = resource == null ? null : resource.WithoutQuery().WithoutFragment();
            data.Origin = origin;
            data.Doc = doc;

            if(!_changeQueue.TryEnqueue(data)) {
                _log.WarnFormat("unable to enqueue change data into processing queue");
            }
        }
        private void Publish(ChangeData data) {
            _log.DebugFormat("publishing {0} on channel {1}", data.Resource, data.Channel);
            DreamMessage message = DreamMessage.Ok(data.Doc);
            message.Headers.DreamEventChannel = data.Channel.ToString();
            if(data.Resource != null) {
                message.Headers.DreamEventResource = data.Resource.ToString();
            }
            message.Headers.DreamEventOrigin = data.Origin;
            _publishPlug.Post(message, new Result<DreamMessage>()).WhenDone(
                r => {
                    if(r.HasException) {
                        _log.Warn("unable to publish deki change", r.Exception);
                    } else if(!r.Value.IsSuccessful) {
                        _log.WarnFormat("unable to publish deki change: {0}", r.Value.Status);
                    }
                });

        }
		protected void Flush (bool continue_only)
		{
			IndexerRequest flushed_request;

			if (continue_only) {
				// if the request is merely to signal indexhelper to continue indexing,
				// then sent a fake indexerrequest but then use the previous request to retrieve
				// deferred indexables
				flushed_request = new IndexerRequest ();
				flushed_request.ContinueIndexing = true;

				// Do not pass this through PreFlushHook since this is a fake request
			} else {
				lock (request_lock) {
					if (pending_request.IsEmpty)
						return;

					flushed_request = pending_request;
					pending_request = new IndexerRequest ();

					// We hold the request_lock when calling PreFlushHook, so
					// that no other requests can come in until it exits.
					PreFlushHook (flushed_request);
				}
			}

			IndexerReceipt [] receipts;
			receipts = indexer.Flush (flushed_request);

			PostFlushHook (flushed_request, receipts);

			if (continue_only) {
				flushed_request = pending_request;
			}

			// Silently return if we get a null back.  This is probably
			// a bad thing to do. If IndexHelper is shutdown because of
			// memory blowup or is crashed, then null is returned. Silently
			// returning means ignoring the indexables in the IndexHelper's
			// queue (which could be more than what was sent in the last request,
			// since there could be some deferred-indexables too).
			if (receipts == null)
				return;

			// Nothing happened (except maybe an optimize, which does not
			// generate a receipt).  Also do nothing.
			if (receipts.Length == 0)
				return;

			// Update the cached count of items in the driver
			// FIXME: Verify that this still works after all the deferred-indexable fu
			driver.SetItemCount (indexer.GetItemCount ());

			// Something happened, so schedule an optimize just in case.
			ScheduleOptimize ();
			
			if (fa_store != null)
				fa_store.BeginTransaction ();

			ArrayList added_uris = new ArrayList ();
			ArrayList removed_uris  = new ArrayList ();
			bool indexer_indexable_receipt = false;

			for (int i = 0; i < receipts.Length; ++i) {

				if (receipts [i] is IndexerAddedReceipt) {
					
					IndexerAddedReceipt r;
					r = (IndexerAddedReceipt) receipts [i];
					Indexable indexable = flushed_request.RetrieveRequestIndexable (r);

					if (indexable == null) {
						Log.Debug ("Should not happen! Previously requested indexable with id #{0} has eloped!", r.Id);
						continue;
					}

					// Add the Uri to the list for our change data
					// *before* doing any post-processing.
					// This ensures that we have internal uris when
					// we are remapping.
					added_uris.Add (indexable.Uri);
					
					// Call the appropriate hook
					Uri notification_uri = indexable.Uri;
					try {
						// Map from internal->external Uris in the PostAddHook
						notification_uri = PostAddHook (indexable, r);
					} catch (Exception ex) {
						Logger.Log.Warn (ex, "Caught exception in PostAddHook '{0}' '{1}' '{2}'",
								 indexable.Uri, r.FilterName, r.FilterVersion);
					}

					// Every added Uri also needs to be listed as removed,
					// to avoid duplicate hits in the query.  Since the
					// removed Uris need to be external Uris, we add them
					// to the list *after* post-processing.
					removed_uris.Add (notification_uri);

				} else if (receipts [i] is IndexerRemovedReceipt) {

					IndexerRemovedReceipt r;
					r = (IndexerRemovedReceipt) receipts [i];

					Indexable indexable = flushed_request.RetrieveRequestIndexable (r);
					if (indexable == null) { // Should never happen
						Log.Warn ("Unable to match indexable-remove #{0} to any request!", r.Id);
						continue;
					}

					// Call the appropriate hook
					Uri notification_uri = indexable.Uri;
					try {
						notification_uri = PostRemoveHook (indexable, r.NumRemoved);
					} catch (Exception ex) {
						Logger.Log.Warn (ex, "Caught exception in PostRemoveHook '{0}'",
								 indexable.Uri);
					}

					// If nothing was removed, no need for change notification
					if (r.NumRemoved <= 0)
						continue;

					// Add the removed Uri to the list for our
					// change data.  This will be an external Uri
					// when we are remapping.
					removed_uris.Add (notification_uri);
					
				} else if (receipts [i] is IndexerIndexablesReceipt) {
					indexer_indexable_receipt = true;
				}
			}

			if (! continue_only) {
				lock (request_lock) {
					pending_request.DeferredIndexables = flushed_request.DeferredIndexables;
				}
			}

			if (indexer_indexable_receipt) {
				Log.Debug ("Indexing of indexer generated indexables is paused. Scheduling job to continue.");
				// Create a task asking the indexer to continue indexing
				Scheduler.Task task;
				task = Scheduler.TaskFromHook (new Scheduler.TaskHook (ContinueIndexerIndexableIndexing));
				// Schedule it so that it is the immediate next task to be scheduled
				task.Priority = Scheduler.Priority.Immediate;
				task.SubPriority = 100;
				task.Source = this;
				task.Tag = "Continue indexing generated indexables from " + IndexName;
				ThisScheduler.Add (task);
			}

			if (fa_store != null)
				fa_store.CommitTransaction ();

			// Propagate the change notification to any open queries.
			if (added_uris.Count > 0 || removed_uris.Count > 0) {
				ChangeData change_data;
				change_data = new ChangeData ();
				change_data.AddedUris = added_uris;
				change_data.RemovedUris = removed_uris;

				QueryDriver.QueryableChanged (this, change_data);
			}
		}