Пример #1
0
        /// <summary>Commit changes made to the collection.</summary>
        async Task ICollectionRef <T> .Commit()
        {
            try
            {
                using LiteRepository _liteRepo = new LiteRepository(RefConfig.Location);
                if (ToSave.Any() || ToModify.Any())
                {
                    IList <T> _combinedList = ToSave.Concat(ToModify).ToList();
                    _liteRepo.Upsert <T>(_combinedList, RefConfig.Collection);
                }
                if (ToRemove.Any())
                {
                    BsonValue[] _bsonValues = ToRemove.Select(_id => new BsonValue(_id)).ToArray();
                    _liteRepo.DeleteMany <T>(Query.In("_id", _bsonValues), RefConfig.Collection);
                }

                await Task.Run(() =>
                {
                    ToSave.Clear();
                    ToModify.Clear();
                    ToRemove.Clear();
                });
            }
            catch (Exception ex)
            { throw ex; }
        }
Пример #2
0
        /// <summary>
        ///     Checks to see if any pending entities can be added to the world and
        ///     adds them if applicable.
        /// </summary>
        private void UpdatePendingEntities(Tick serverTick)
        {
            foreach (RailEntityClient entity in pendingEntities.Values)
            {
                if (!entity.HasReadyState(serverTick))
                {
                    continue;
                }

                // Note: We're using ToRemove here to remove from the *pending* list
                ToRemove.Add(entity);

                // If the entity was removed while pending, forget about it
                Tick removeTick = entity.RemovedTick; // Can't use ShouldRemove
                if (removeTick.IsValid && removeTick <= serverTick)
                {
                    knownEntities.Remove(entity.Id);
                }
                else
                {
                    RegisterEntity(entity);
                }
            }

            foreach (RailEntityClient entity in ToRemove)
            {
                pendingEntities.Remove(entity.Id);
            }

            ToRemove.Clear();
        }
Пример #3
0
        public async Task Processed(QuestionView QuestionView)
        {
            MainWindow.UpdateGui(() =>
            {
                int i = QuestionView.QuestionListView.SelectedIndex;
                int c;

                QuestionView.Details.Children.Clear();
                QuestionView.QuestionListView.Items.Remove(this);

                c = QuestionView.QuestionListView.Items.Count;
                if (c == 0)
                {
                    MainWindow.currentInstance.CloseTab_Executed(this, null);
                }
                else if (i < c)
                {
                    QuestionView.QuestionListView.SelectedIndex = i;
                }
            });

            await Database.Delete(this);

            LinkedList <Question> ToRemove = null;

            foreach (Question Question in QuestionView.QuestionListView.Items)
            {
                if (Question.IsResolvedBy(this))
                {
                    if (ToRemove is null)
                    {
                        ToRemove = new LinkedList <Question>();
                    }

                    ToRemove.AddLast(Question);
                }
            }

            if (ToRemove != null)
            {
                MainWindow.UpdateGui(() =>
                {
                    foreach (Question Question in ToRemove)
                    {
                        QuestionView.QuestionListView.Items.Remove(Question);
                    }

                    if (QuestionView.QuestionListView.Items.Count == 0)
                    {
                        MainWindow.currentInstance.CloseTab_Executed(this, null);
                    }
                });

                foreach (Question Question in ToRemove)
                {
                    await Database.Delete(Question);
                }
            }
        }
Пример #4
0
 protected override void RemoveItem(int index)
 {
     ToRemove.Add(this[index]);
     foreach (var trigger in this.Property.Triggers.Where(p => p.PropertyTriggerType == PropertyTriggerType.ItemsDelete))
     {
         new ModelMethodContext(this.Con, this.ConFac).ExcuteOperation(this[index], trigger as IOperation);
     }
     base.RemoveItem(index);
 }
Пример #5
0
 public bool Remove(string name)
 {
     if (!Dictionary.ContainsKey(name))
     {
         return(false);
     }
     ToRemove.Add(name);
     return(true);
 }
Пример #6
0
    void AggiungiRighe()
    {
        int       nrows             = ToAdd.Rows.Count;
        ArrayList Selected          = new ArrayList();
        ArrayList ToRemoveFromToAdd = new ArrayList();

        for (int index = 0; index < nrows; index++)
        {
            hwCheckBox HwC = GridToAdd.FindControl("Chk_Selector_" + GridToAdd.ID + "_" + index) as hwCheckBox;
            if (HwC == null)
            {
                continue;
            }
            if (HwC.Checked == true)
            {
                Selected.Add(index);
            }
        }

        /*
         * foreach (hwCheckBox hwC in GridToAdd.Controls)
         * {
         *  if (hwC.Checked == true)
         *  {
         *      int i = Int32.Parse(hwC.Tag);
         *      Selected.Add(i);
         *  }
         * }
         */

        foreach (int index in Selected)
        {
            DataRow Curr = ToAdd.Rows[index];
            ToRemoveFromToAdd.Add(Curr);

            //La  aggiunge ad Added
            AddRowToTable(Added, Curr);
        }

        //Rimuove tutte le righe da ToAdd
        foreach (DataRow ToRemove in ToRemoveFromToAdd)
        {
            ToRemove.Delete();
            if (ToRemove.RowState != DataRowState.Detached)
            {
                ToRemove.AcceptChanges();
            }
        }
        UpdateSourceTable();
    }
Пример #7
0
 public void RemoveChild(UIElement child)
 {
     if (Children.Contains(child))
     {
         if (!ToRemove.Add(child))
         {
             throw new Exception("Tried to remove a child twice!");
         }
     }
     else
     {
         throw new Exception("Tried to remove a child that does not belong to this element!");
     }
 }
        private void UpdateTokenSource(string Token, string From)
        {
            LinkedList <KeyValuePair <DateTime, string> > ToRemove = null;
            Triplet <string, DateTime, X509Certificate2>  Rec;
            DateTime TP      = DateTime.Now;
            DateTime Timeout = TP.AddMinutes(-1);

            lock (this.synchObject)
            {
                if (this.sourceByToken.TryGetValue(Token, out Rec))
                {
                    this.sourceByToken.Remove(Token);
                    this.tokenByLastAccess.Remove(Rec.Value2);
                }

                foreach (KeyValuePair <DateTime, string> P in tokenByLastAccess)
                {
                    if (P.Key <= Timeout)
                    {
                        if (ToRemove == null)
                        {
                            ToRemove = new LinkedList <KeyValuePair <DateTime, string> > ();
                        }

                        ToRemove.AddLast(P);
                    }
                    else
                    {
                        break;
                    }
                }

                if (ToRemove != null)
                {
                    foreach (KeyValuePair <DateTime, string> P in ToRemove)
                    {
                        this.tokenByLastAccess.Remove(P.Key);
                        this.sourceByToken.Remove(P.Value);
                    }
                }

                while (this.tokenByLastAccess.ContainsKey(TP))
                {
                    TP = TP.AddTicks(gen.Next(1, 10));
                }

                this.sourceByToken [Token]  = new Triplet <string, DateTime, X509Certificate2> (From, TP, null);
                this.tokenByLastAccess [TP] = Token;
            }
        }
Пример #9
0
        public void RemoveWords(params string[] ToRemove)
        {
            int index;

            if (ToRemove.Count() != 0)
            {
                List <int> RemoveIndices = new List <int>();
                foreach (var RemovedWord in ToRemove)
                {
                    index = Words.IndexOf(RemovedWord);
                    Words.RemoveAt(index);
                    RemoveIndices.Add(index);
                }
                AdjustVectorLists(RemoveIndices.ToArray());
                RemoveIndices = null;
            }
        }
Пример #10
0
        private void TimerCallback(object State)
        {
            LinkedList <SensorDataEventArgs> ToRemove = null;
            DateTime Now = DateTime.Now;

            lock (this.synchObj)
            {
                foreach (KeyValuePair <DateTime, SensorDataEventArgs> Pair in this.byTimeout)
                {
                    if (Pair.Key > Now)
                    {
                        break;
                    }

                    if (ToRemove == null)
                    {
                        ToRemove = new LinkedList <SensorDataEventArgs> ();
                    }

                    ToRemove.AddLast(Pair.Value);
                }
            }

            if (ToRemove != null)
            {
                foreach (SensorDataEventArgs e in ToRemove)
                {
                    lock (this.synchObj)
                    {
                        this.byTimeout.Remove(e.Timeout);
                        this.receiving.Remove(e.SeqNr);

                        if (this.byTimeout.Count == 0 && this.timer != null)
                        {
                            this.timer.Dispose();
                            this.timer = null;
                        }
                    }

                    e.Receiving();
                    e.ReadoutState = ReadoutState.Timeout;
                    e.Done         = true;
                    e.DoCallback(this);
                }
            }
        }
Пример #11
0
 // Grows child 'i' to make sure it's possible to remove an
 // item from it while keeping it at minItems, then calls remove to actually
 // remove it
 //
 // Most documentation says we have to do two sets of special casing:
 //    1) item is in this node
 //    2) item is in child
 // In both cases, we need to handle the two subcases:
 //    A) node has enough values that it can spare one
 //    B) node doesn't have enough values
 // For the latter, we have to check:
 //    a) left sibling has node to spare
 //    b) right sibling has node to spare
 //    c) we must merge
 // To simplify our code here, we handle cases #1 and #2 the same:
 // If a node doesn't have enough items, we make sure it does (using a,b,c).
 // We then simply redo our remove call, and the second time (regardless of
 // whether we're in case 1 or 2), we'll have enough items and can guarantee
 // that we hit case A.
 public T GrowChildAndRemove(int i, T item, int minItems, ToRemove typ)
 {
     if (i > 0 && Children[i - 1].Items.Length > minItems)
     {
         // Steal from left child
         Node <T> child      = MutableChild(i);
         Node <T> stealFrom  = MutableChild(i - 1);
         T        stolenItem = stealFrom.Items.Pop();
         child.Items.InsertAt(0, Items[i - 1]);
         Items[i - 1] = stolenItem;
         if (stealFrom.Children.Length > 0)
         {
             child.Children.InsertAt(0, stealFrom.Children.Pop());
         }
     }
     else if (i < Items.Length && Children[i + 1].Items.Length > minItems)
     {
         // steal from right child
         Node <T> child      = MutableChild(i);
         Node <T> stealFrom  = MutableChild(i + 1);
         T        stolenItem = stealFrom.Items.RemoveAt(0);
         child.Items.Append(Items[i]);
         Items[i] = stolenItem;
         if (stealFrom.Children.Length > 0)
         {
             child.Children.Append(stealFrom.Children.RemoveAt(0));
         }
     }
     else
     {
         if (i >= Items.Length)
         {
             i--;
         }
         Node <T> child = MutableChild(i);
         // merge with right child
         T        mergeItem  = Items.RemoveAt(i);
         Node <T> mergeChild = Children.RemoveAt(i + 1);
         child.Items.Append(mergeItem);
         child.Items.Append(mergeChild.Items);
         child.Children.Append(mergeChild.Children);
         _ = Cow.FreeNode(mergeChild);
     }
     return(Remove(item, minItems, typ));
 }
Пример #12
0
        internal bool UnregisterSubscription(IPEndPoint RemoteEndpoint, ulong Token)
        {
            string Prefix = RemoteEndpoint.ToString() + " ";
            string Key    = Prefix + Token.ToString();

            lock (this.registrations)
            {
                this.registeredMessages = null;
                if (this.registrations.Remove(Key))
                {
                    return(true);
                }

                if (Token == 0)
                {
                    LinkedList <string> ToRemove = null;

                    foreach (string Key2 in this.registrations.Keys)
                    {
                        if (Key2.StartsWith(Prefix))
                        {
                            if (ToRemove is null)
                            {
                                ToRemove = new LinkedList <string>();
                            }

                            ToRemove.AddLast(Key2);
                        }
                    }

                    if (ToRemove != null)
                    {
                        foreach (string Key2 in ToRemove)
                        {
                            this.registrations.Remove(Key2);
                        }

                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #13
0
 public static void Update()
 {
     foreach (Entity e in Entities)
     {
         e.Update();
         //if (e.ToRemove())
         //    ToRemove.Add(e);
     }
     foreach (Entity e in ToRemove)
     {
         Entities.Remove(e);
     }
     ToRemove.Clear();
     foreach (Entity e in ToAdd)
     {
         Entities.Add(e);
     }
     ToAdd.Clear();
 }
Пример #14
0
 public void RemoveChild(UIElement child)
 {
     if (Children.Contains(child))
     {
         if (!ToRemove.Add(child))
         {
             // This is probably fine actually.
             //throw new Exception("Tried to remove a child twice!");
         }
     }
     else if (ToAdd.Contains(child))
     {
         ToAdd.Remove(child);
     }
     else
     {
         throw new Exception("Tried to remove a child that does not belong to this element!");
     }
 }
Пример #15
0
    void RimuoviRighe()
    {
        int       nrows             = Added.Rows.Count;
        ArrayList Selected          = new ArrayList();
        ArrayList ToRemoveFromAdded = new ArrayList();

        for (int index = 0; index < nrows; index++)
        {
            hwCheckBox HwC = GridAdded.FindControl("Chk_Selector_" + GridAdded.ID + "_" + index) as hwCheckBox;
            if (HwC == null)
            {
                continue;
            }
            if (HwC.Checked == true)
            {
                Selected.Add(index);
            }
        }

        foreach (int index in Selected)
        {
            //Prende una riga selezionata
            //gridAdded.CurrentRowIndex = index;
            //DataRowView CurrDV = (DataRowView)gridToAdd.BindingContext[myDS, Added.TableName].Current;
            DataRow Curr = Added.Rows[index];
            ToRemoveFromAdded.Add(Curr);

            //La  aggiunge a ToAdd
            AddRowToTable(ToAdd, Curr);
        }

        //Rimuove tutte le righe da Added
        foreach (DataRow ToRemove in ToRemoveFromAdded)
        {
            ToRemove.Delete();
            if (ToRemove.RowState != DataRowState.Detached)
            {
                ToRemove.AcceptChanges();
            }
        }
        UpdateSourceTable();
    }
Пример #16
0
        private void RecalcTimerLocked()
        {
            if (this.timer != null)
            {
                this.timer.Dispose();
                this.timer = null;
            }

            LinkedList <DateTime> ToRemove = null;
            DateTime Now = DateTime.Now;
            TimeSpan TimeLeft;

            foreach (KeyValuePair <DateTime, ScheduledEvent> Event in this.events)
            {
                TimeLeft = Event.Key - Now;
                if (TimeLeft <= TimeSpan.Zero)
                {
                    if (ToRemove == null)
                    {
                        ToRemove = new LinkedList <DateTime>();
                    }

                    ToRemove.AddLast(Event.Key);

                    Task.Run((Action)Event.Value.Execute);
                }
                else
                {
                    this.timer = new Timer(this.TimerElapsed, null, TimeLeft, OnlyOnce);
                    break;
                }
            }

            if (ToRemove != null)
            {
                foreach (DateTime TP in ToRemove)
                {
                    this.events.Remove(TP);
                }
            }
        }
Пример #17
0
        private T DeleteItem(T item, ToRemove typ)
        {
            if (Root == null || Root.Items.Length == 0)
            {
                return(null);
            }
            Root = Root.MutableFor(Cow);
            T result = Root.Remove(item, MinItems(), typ);

            if (Root.Items.Length == 0 && Root.Children.Length > 0)
            {
                Node <T> oldRoot = Root;
                Root = Root.Children[0];
                _    = Cow.FreeNode(oldRoot);
            }
            if (result != null)
            {
                Length--;
            }
            return(result);
        }
Пример #18
0
        public override XmlNode ToXml(XmlDocument doc)
        {
            XmlElement root = doc.CreateElement("secDNS:update", "urn:ietf:params:xml:ns:secDNS-1.1");

            root.SetAttribute("xmlns:secDNS", "urn:ietf:params:xml:ns:secDNS-1.1");

            XmlAttribute xsd = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");

            xsd.Value = "urn:ietf:params:xml:ns:secDNS-1.1 secDNS-1.1.xsd";
            root.Attributes.Append(xsd);

            if (ToRemove.Any())
            {
                XmlElement removeNode = doc.CreateElement("secDNS:rem", "urn:ietf:params:xml:ns:secDNS-1.1");

                foreach (SecDNSData data in ToRemove)
                {
                    removeNode.AppendChild(data.ToXml(doc));
                }

                root.AppendChild(removeNode);
            }

            if (ToAdd.Any())
            {
                XmlElement addNode = doc.CreateElement("secDNS:add", "urn:ietf:params:xml:ns:secDNS-1.1");

                foreach (SecDNSData data in ToAdd)
                {
                    addNode.AppendChild(data.ToXml(doc));
                }

                root.AppendChild(addNode);
            }

            return(root);
        }
Пример #19
0
        /// <summary>
        ///     Updates the room a number of ticks. If we have entities waiting to be
        ///     added, this function will check them and add them if applicable.
        /// </summary>
        public void ClientUpdate(Tick localTick, Tick estimatedServerTick)
        {
            Tick = estimatedServerTick;
            UpdatePendingEntities(estimatedServerTick);
            OnPreRoomUpdate(Tick);

            // Collect the entities in the priority order and
            // separate them out for either update or removal
            foreach (RailEntityBase railEntityBase in Entities)
            {
                RailEntityClient entity = (RailEntityClient)railEntityBase;
                if (entity.ShouldRemove)
                {
                    ToRemove.Add(entity);
                }
                else
                {
                    ToUpdate.Add(entity);
                }
            }

            // Wave 0: Remove all sunsetted entities
            ToRemove.ForEach(RemoveEntity);

            // Wave 1: Start/initialize all entities
            ToUpdate.ForEach(e => e.PreUpdate());

            // Wave 2: Update all entities
            ToUpdate.ForEach(e => e.ClientUpdate(localTick));

            // Wave 3: Post-update all entities
            ToUpdate.ForEach(e => e.PostUpdate());

            ToRemove.Clear();
            ToUpdate.Clear();
            OnPostRoomUpdate(Tick);
        }
Пример #20
0
        public void ServerUpdate()
        {
            Tick = Tick.GetNext();
            OnPreRoomUpdate(Tick);

            // Collect the entities in the priority order and
            // separate them out for either update or removal
            foreach (RailEntityBase railEntityBase in Entities)
            {
                RailEntityServer entity = (RailEntityServer)railEntityBase;
                if (entity.ShouldRemove)
                {
                    ToRemove.Add(entity);
                }
                else
                {
                    ToUpdate.Add(entity);
                }
            }

            // Wave 0: Remove all sunsetted entities
            ToRemove.ForEach(RemoveEntity);

            // Wave 1: Start/initialize all entities
            ToUpdate.ForEach(e => e.PreUpdate());

            // Wave 2: Update all entities
            ToUpdate.ForEach(e => e.ServerUpdate());

            // Wave 3: Post-update all entities
            ToUpdate.ForEach(e => e.PostUpdate());

            ToRemove.Clear();
            ToUpdate.Clear();
            OnPostRoomUpdate(Tick);
        }
Пример #21
0
 /// <summary>
 /// Checks if this element has the specified child.
 /// </summary>
 /// <param name="element">The possible child.</param>
 /// <returns></returns>
 public bool HasChild(UIElement element)
 {
     return(Children.Contains(element) && !ToRemove.Contains(element));
 }
Пример #22
0
        public void Update(GameTime gameTime)
        {
            foreach (Bullet b in Bullets.ToArray())
            {
                b.Update(gameTime);
                if (b.Bounds.Intersects(Parent.Player.Bounds))
                {
                    Parent.Health.Value--;
                    AssetManager.PlaySound("Hit", 1f);
                    Parent.GFM.SpawnMiniExplosion(b);
                    Bullets.Remove(b);
                }
                else if (b.ShouldRemove)
                {
                    Parent.GFM.SpawnMiniExplosion(b);
                    Bullets.Remove(b);
                }
            }

            CurrentTime += gameTime.ElapsedGameTime.TotalSeconds;
            if (CurrentTime >= SpawnInterval)
            {
                CurrentTime = 0;
                for (int i = 0; i < Rand.Next(5); i++)
                {
                    //Spawn at top of screen, choose random enemy
                    int R = Rand.Next(4);
                    if (R == 1)
                    {
                        Enemies.Add(new ShooterEnemy(new Rectangle(Rand.Next(64, 64 + 192 - 9), Rand.Next(-32, 0), 7, 14), this));
                    }
                    else if (R == 2)
                    {
                        Enemies.Add(new FighterEnemy(new Rectangle(Rand.Next(64, 64 + 192 - 9), Rand.Next(-32, 0), 9, 13), this));
                    }
                    else if (R == 3)
                    {
                        Enemies.Add(new FollowEnemy(new Rectangle(Rand.Next(64, 64 + 192 - 9), Rand.Next(-32, 0), 9, 9), this));
                    }
                    else
                    {
                        Enemies.Add(new SpikeEnemy(new Rectangle(Rand.Next(64, 64 + 192 - 9), Rand.Next(-32, 0), 13, 13), this));
                    }
                }
            }

            ToRemove.Clear();
            foreach (IEnemy E in Enemies)
            {
                E.Update(gameTime);

                if (E.Bounds.Intersects(Parent.Player.Bounds))
                {
                    ToRemove.Add(E);
                    Parent.Health.Value--;
                }

                foreach (Bullet B in Parent.Player.Bullets.ToArray())
                {
                    if (B.Bounds.Intersects(E.Bounds))
                    {
                        E.Health--;
                        Parent.GFM.SpawnMiniExplosion(E);
                        if (E.Health <= 0)
                        {
                            Parent.Score.Value++;
                            ToRemove.Add(E);
                        }
                        else
                        {
                            AssetManager.PlaySound("Hit");
                        }
                        Parent.Player.Bullets.Remove(B);
                    }
                }
            }

            foreach (IEnemy E in ToRemove)
            {
                if (Enemies.Contains(E))
                {
                    Parent.GFM.SpawnExplosion(E);
                    Parent.Camera.ScreenShake(20, 0.075f);
                    Enemies.Remove(E);
                }
            }
        }
        /// <summary>
        /// Reports a set of newly measured field values. Conditions in existing event subscriptions will be analyzed and any corresponding events sent.
        /// </summary>
        /// <param name="FieldValues">Field values.</param>
        public void MomentaryValuesUpdated(params KeyValuePair <string, double>[] FieldValues)
        {
            Dictionary <Subscription, bool> ToUpdate = null;
            LinkedList <Subscription>       ToRemove = null;
            List <Subscription>             Subscriptions;
            DateTime    Now = DateTime.Now;
            TimeSpan    SinceLast;
            XmppContact Contact;
            bool        MaxIntervalReached;
            bool        Update;

            lock (this.synchObj)
            {
                foreach (KeyValuePair <string, double> Pair in FieldValues)
                {
                    this.currentValues [Pair.Key] = Pair.Value;
                    if (this.subscriptionsByField.TryGetValue(Pair.Key, out Subscriptions))
                    {
                        foreach (Subscription Subscription in Subscriptions)
                        {
                            Contact = this.client.GetLocalContact(Subscription.From);
                            if (Contact == null || (Contact.Subscription != RosterItemSubscription.Both && Contact.Subscription != RosterItemSubscription.To))
                            {
                                if (ToRemove == null)
                                {
                                    ToRemove = new LinkedList <Subscription> ();
                                }

                                ToRemove.AddLast(Subscription);
                                continue;
                            }

                            if (Contact.LastPresence == null || Contact.LastPresence.Status == PresenceStatus.Offline)
                            {
                                continue;
                            }

                            SinceLast = Now - Subscription.LastUpdate;
                            if (SinceLast < Subscription.MinInterval)
                            {
                                continue;
                            }

                            Update = MaxIntervalReached = SinceLast >= Subscription.MaxInterval;

                            foreach (Condition Condition in Subscription.Conditions)
                            {
                                if (Condition.Trigger(Pair.Key, Pair.Value, MaxIntervalReached))
                                {
                                    Update = true;
                                    break;
                                }
                            }

                            if (Update)
                            {
                                if (ToUpdate == null)
                                {
                                    ToUpdate = new Dictionary <Subscription, bool> ();
                                }

                                ToUpdate [Subscription] = true;
                                Subscription.LastUpdate = Now;
                            }
                        }
                    }
                }
            }

            if (ToUpdate != null)
            {
                foreach (Subscription Subscription in ToUpdate.Keys)
                {
                    this.SendFields(Subscription.SeqNr, Subscription.From, Subscription.Request);
                }
            }

            if (ToRemove != null)
            {
                foreach (Subscription Subscription in ToRemove)
                {
                    this.RemoveSubscription(Subscription.Key, Subscription.SeqNr);
                }
            }
        }
Пример #24
0
        private async void GetFormHandler(object Sender, IqEventArgs e)
        {
            try
            {
                LinkedList <IThingReference> Nodes = null;
                XmlElement E;
                string     ServiceToken = XML.Attribute(e.Query, "st");
                string     DeviceToken  = XML.Attribute(e.Query, "dt");
                string     UserToken    = XML.Attribute(e.Query, "ut");

                foreach (XmlNode N in e.Query.ChildNodes)
                {
                    E = N as XmlElement;
                    if (E is null)
                    {
                        continue;
                    }

                    if (E.LocalName == "nd")
                    {
                        if (Nodes is null)
                        {
                            Nodes = new LinkedList <IThingReference>();
                        }

                        string NodeId    = XML.Attribute(E, "id");
                        string SourceId  = XML.Attribute(E, "src");
                        string Partition = XML.Attribute(E, "pt");

                        if (this.OnGetNode is null)
                        {
                            Nodes.AddLast(new ThingReference(NodeId, SourceId, Partition));
                        }
                        else
                        {
                            IThingReference Ref = await this.OnGetNode(NodeId, SourceId, Partition);

                            if (Ref is null)
                            {
                                throw new ItemNotFoundException("Node not found.", e.IQ);
                            }

                            Nodes.AddLast(Ref);
                        }
                    }
                }

                ControlParameter[] Parameters;

                if (Nodes is null)
                {
                    Parameters = await this.GetControlParameters(null);

                    if (Parameters is null)
                    {
                        NotFound(e);
                        return;
                    }
                }
                else
                {
                    Dictionary <string, ControlParameter> Parameters1;
                    Dictionary <string, ControlParameter> Parameters2;
                    LinkedList <string> ToRemove = null;

                    Parameters  = null;
                    Parameters1 = null;

                    foreach (IThingReference Node in Nodes)
                    {
                        if (Parameters1 is null)
                        {
                            Parameters = await this.GetControlParameters(Node);

                            if (Parameters is null)
                            {
                                NotFound(e);
                                return;
                            }

                            Parameters1 = new Dictionary <string, ControlParameter>();

                            foreach (ControlParameter P in Parameters)
                            {
                                Parameters1[P.Name] = P;
                            }
                        }
                        else
                        {
                            Parameters2 = await this.GetControlParametersByName(Node);

                            if (Parameters2 is null)
                            {
                                NotFound(e);
                                return;
                            }

                            foreach (KeyValuePair <string, ControlParameter> P in Parameters1)
                            {
                                if (!Parameters2.TryGetValue(P.Key, out ControlParameter P2) || !P.Value.Equals(P2))
                                {
                                    if (ToRemove is null)
                                    {
                                        ToRemove = new LinkedList <string>();
                                    }

                                    ToRemove.AddLast(P.Key);
                                }
                            }

                            if (ToRemove != null)
                            {
                                foreach (string Key in ToRemove)
                                {
                                    Parameters1.Remove(Key);
                                }

                                ToRemove = null;
                            }
                        }
                    }

                    List <ControlParameter> Left = new List <ControlParameter>();

                    foreach (ControlParameter P in Parameters)
                    {
                        if (Parameters1.ContainsKey(P.Name))
                        {
                            Left.Add(P);
                        }
                    }

                    Parameters = Left.ToArray();
                }

                if (this.provisioningClient != null)
                {
                    int      i, c = Parameters.Length;
                    string[] ParameterNames = new string[c];

                    for (i = 0; i < c; i++)
                    {
                        ParameterNames[i] = Parameters[i].Name;
                    }

                    this.provisioningClient.CanControl(e.FromBareJid, Nodes, ParameterNames,
                                                       ServiceToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                       DeviceToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                       UserToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                       (sender2, e2) =>
                    {
                        if (e2.Ok && e2.CanControl)
                        {
                            if (e2.ParameterNames != null)
                            {
                                List <ControlParameter> Parameters2 = new List <ControlParameter>();

                                foreach (ControlParameter P in Parameters)
                                {
                                    if (Array.IndexOf <string>(e2.ParameterNames, P.Name) >= 0)
                                    {
                                        Parameters2.Add(P);
                                    }
                                }

                                Parameters = Parameters2.ToArray();

                                if (Parameters.Length == 0)
                                {
                                    e.IqError("<error type='cancel'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
                                              "<text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas' xml:lang='en'>Access denied.</text></error>");
                                    return;
                                }
                            }

                            this.ReturnForm(e, Parameters, Nodes);
                        }
                        else
                        {
                            e.IqError("<error type='cancel'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
                                      "<text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas' xml:lang='en'>Access denied.</text></error>");
                        }
                    }, null);
                }
                else
                {
                    this.ReturnForm(e, Parameters, Nodes);
                }
            }
            catch (Exception ex)
            {
                e.IqError(ex);
            }
        }
Пример #25
0
        private async void GetFormHandler(object Sender, IqEventArgs e)
        {
            try
            {
                LinkedList <ThingReference> Nodes = null;
                XmlElement E;

                foreach (XmlNode N in e.Query.ChildNodes)
                {
                    E = N as XmlElement;
                    if (E == null)
                    {
                        continue;
                    }

                    if (E.LocalName == "nd")
                    {
                        if (Nodes == null)
                        {
                            Nodes = new LinkedList <ThingReference>();
                        }

                        Nodes.AddLast(new ThingReference(
                                          XML.Attribute(E, "id"),
                                          XML.Attribute(E, "src"),
                                          XML.Attribute(E, "pt")));
                    }
                }

                ControlParameter[] Parameters;

                if (Nodes == null)
                {
                    Parameters = await this.GetControlParameters(null);

                    if (Parameters == null)
                    {
                        NotFound(e);
                        return;
                    }
                }
                else
                {
                    Dictionary <string, ControlParameter> Parameters1;
                    Dictionary <string, ControlParameter> Parameters2;
                    LinkedList <string> ToRemove = null;

                    Parameters  = null;
                    Parameters1 = null;

                    foreach (ThingReference Node in Nodes)
                    {
                        if (Parameters1 == null)
                        {
                            Parameters = await this.GetControlParameters(Node);

                            if (Parameters == null)
                            {
                                NotFound(e);
                                return;
                            }

                            Parameters1 = new Dictionary <string, ControlParameter>();

                            foreach (ControlParameter P in Parameters)
                            {
                                Parameters1[P.Name] = P;
                            }
                        }
                        else
                        {
                            Parameters2 = await this.GetControlParametersByName(Node);

                            if (Parameters2 == null)
                            {
                                NotFound(e);
                                return;
                            }

                            foreach (KeyValuePair <string, ControlParameter> P in Parameters1)
                            {
                                if (!Parameters2.TryGetValue(P.Key, out ControlParameter P2) || !P.Value.Equals(P2))
                                {
                                    if (ToRemove == null)
                                    {
                                        ToRemove = new LinkedList <string>();
                                    }

                                    ToRemove.AddLast(P.Key);
                                }
                            }

                            if (ToRemove != null)
                            {
                                foreach (string Key in ToRemove)
                                {
                                    Parameters1.Remove(Key);
                                }

                                ToRemove = null;
                            }
                        }
                    }

                    List <ControlParameter> Left = new List <ControlParameter>();

                    foreach (ControlParameter P in Parameters)
                    {
                        if (Parameters1.ContainsKey(P.Name))
                        {
                            Left.Add(P);
                        }
                    }

                    Parameters = Left.ToArray();
                }

                StringBuilder  Xml    = new StringBuilder();
                XmlWriter      Output = XmlWriter.Create(Xml, XML.WriterSettings(false, true));
                ThingReference FirstNode;

                Output.WriteStartElement("x", XmppClient.NamespaceData);
                Output.WriteAttributeString("xmlns", "xdv", null, XmppClient.NamespaceDataValidate);
                Output.WriteAttributeString("xmlns", "xdl", null, XmppClient.NamespaceDataLayout);
                Output.WriteAttributeString("xmlns", "xdd", null, XmppClient.NamespaceDynamicForms);

                if (Nodes == null)
                {
                    FirstNode = null;
                    Output.WriteElementString("title", this.client.BareJID);
                }
                else
                {
                    FirstNode = Nodes.First.Value;

                    if (Nodes.First.Next == null)
                    {
                        Output.WriteElementString("title", Nodes.First.Value.NodeId);
                    }
                    else
                    {
                        Output.WriteElementString("title", Nodes.Count.ToString() + " nodes");
                    }
                }

                LinkedList <string> PagesInOrder = new LinkedList <string>();
                Dictionary <string, LinkedList <ControlParameter> > ParametersPerPage = new Dictionary <string, LinkedList <ControlParameter> >();

                foreach (ControlParameter P in Parameters)
                {
                    if (!ParametersPerPage.TryGetValue(P.Page, out LinkedList <ControlParameter> List))
                    {
                        PagesInOrder.AddLast(P.Page);
                        List = new LinkedList <ControlParameter>();
                        ParametersPerPage[P.Page] = List;
                    }

                    List.AddLast(P);
                }

                foreach (string Page in PagesInOrder)
                {
                    Output.WriteStartElement("xdl", "page", null);
                    Output.WriteAttributeString("label", Page);

                    foreach (ControlParameter P in ParametersPerPage[Page])
                    {
                        Output.WriteStartElement("xdl", "fieldref", null);
                        Output.WriteAttributeString("var", P.Name);
                        Output.WriteEndElement();
                    }

                    Output.WriteEndElement();
                }

                foreach (ControlParameter P in Parameters)
                {
                    P.ExportToForm(Output, FirstNode);
                }

                Output.WriteEndElement();
                Output.Flush();

                e.IqResult(Xml.ToString());
            }
            catch (Exception ex)
            {
                e.IqError(ex);
            }
        }
Пример #26
0
        private void SubscribeHandler(object Sender, IqEventArgs e)
        {
            List <ThingReference> Nodes = null;
            Dictionary <string, FieldSubscriptionRule> Fields = null;
            XmlElement E            = e.Query;
            FieldType  FieldTypes   = (FieldType)0;
            Duration   MaxAge       = null;
            Duration   MinInterval  = null;
            Duration   MaxInterval  = null;
            string     ServiceToken = string.Empty;
            string     DeviceToken  = string.Empty;
            string     UserToken    = string.Empty;
            string     NodeId;
            string     SourceId;
            string     Partition;
            string     Id  = string.Empty;
            bool       Req = false;
            bool       b;

            foreach (XmlAttribute Attr in E.Attributes)
            {
                switch (Attr.Name)
                {
                case "id":
                    Id = Attr.Value;
                    break;

                case "maxAge":
                    if (!Duration.TryParse(Attr.Value, out MaxAge))
                    {
                        MaxAge = null;
                    }
                    break;

                case "minInt":
                    if (!Duration.TryParse(Attr.Value, out MinInterval))
                    {
                        MinInterval = null;
                    }
                    break;

                case "maxInt":
                    if (!Duration.TryParse(Attr.Value, out MaxInterval))
                    {
                        MaxInterval = null;
                    }
                    break;

                case "st":
                    ServiceToken = Attr.Value;
                    break;

                case "dt":
                    DeviceToken = Attr.Value;
                    break;

                case "ut":
                    UserToken = Attr.Value;
                    break;

                case "all":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.All;
                    }
                    break;

                case "h":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Historical;
                    }
                    break;

                case "m":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Momentary;
                    }
                    break;

                case "p":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Peak;
                    }
                    break;

                case "s":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Status;
                    }
                    break;

                case "c":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Computed;
                    }
                    break;

                case "i":
                    if (CommonTypes.TryParse(Attr.Value, out b) && b)
                    {
                        FieldTypes |= FieldType.Identity;
                    }
                    break;

                case "req":
                    if (!CommonTypes.TryParse(Attr.Value, out Req))
                    {
                        Req = false;
                    }
                    break;
                }
            }

            foreach (XmlNode N in E.ChildNodes)
            {
                switch (N.LocalName)
                {
                case "nd":
                    if (Nodes == null)
                    {
                        Nodes = new List <ThingReference>();
                    }

                    E         = (XmlElement)N;
                    NodeId    = XML.Attribute(E, "id");
                    SourceId  = XML.Attribute(E, "src");
                    Partition = XML.Attribute(E, "pt");

                    ThingReference Ref = new ThingReference(NodeId, SourceId, Partition);
                    Nodes.Add(Ref);
                    break;

                case "f":
                    if (Fields == null)
                    {
                        Fields = new Dictionary <string, FieldSubscriptionRule>();
                    }

                    string FieldName    = null;
                    double?CurrentValue = null;
                    double?ChangedBy    = null;
                    double?ChangedUp    = null;
                    double?ChangedDown  = null;
                    double d;

                    foreach (XmlAttribute Attr in N.Attributes)
                    {
                        switch (Attr.Name)
                        {
                        case "n":
                            FieldName = Attr.Value;
                            break;

                        case "v":
                            if (CommonTypes.TryParse(Attr.Value, out d))
                            {
                                CurrentValue = d;
                            }
                            break;

                        case "by":
                            if (CommonTypes.TryParse(Attr.Value, out d))
                            {
                                ChangedBy = d;
                            }
                            break;

                        case "up":
                            if (CommonTypes.TryParse(Attr.Value, out d))
                            {
                                ChangedUp = d;
                            }
                            break;

                        case "dn":
                            if (CommonTypes.TryParse(Attr.Value, out d))
                            {
                                ChangedDown = d;
                            }
                            break;
                        }
                    }

                    if (!string.IsNullOrEmpty(FieldName))
                    {
                        Fields[FieldName] = new FieldSubscriptionRule(FieldName, CurrentValue, ChangedBy, ChangedUp, ChangedDown);
                    }

                    break;
                }
            }

            if (this.provisioningClient != null)
            {
                this.provisioningClient.CanRead(e.FromBareJid, FieldTypes, Nodes, Fields.Keys,
                                                ServiceToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                DeviceToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                UserToken.Split(space, StringSplitOptions.RemoveEmptyEntries),
                                                (sender2, e2) =>
                {
                    if (e2.Ok && e2.CanRead)
                    {
                        if (e2.FieldsNames != null)
                        {
                            Dictionary <string, bool> FieldNames = new Dictionary <string, bool>();

                            foreach (string FieldName in FieldNames.Keys)
                            {
                                FieldNames[FieldName] = true;
                            }

                            LinkedList <string> ToRemove = null;

                            foreach (string FieldName in Fields.Keys)
                            {
                                if (!FieldNames.ContainsKey(FieldName))
                                {
                                    if (ToRemove == null)
                                    {
                                        ToRemove = new LinkedList <string>();
                                    }

                                    ToRemove.AddLast(FieldName);
                                }
                            }

                            if (ToRemove != null)
                            {
                                foreach (string FieldName in ToRemove)
                                {
                                    Fields.Remove(FieldName);
                                }
                            }
                        }

                        this.PerformSubscription(Req, e, Id, Fields, e2.Nodes, e2.FieldTypes,
                                                 ServiceToken, DeviceToken, UserToken, MaxAge, MinInterval, MaxInterval);
                    }
                    else
                    {
                        e.IqError("<error type='cancel'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" +
                                  "<text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas' xml:lang='en'>Access denied.</text></error>");
                    }
                }, null);
            }
            else
            {
                this.PerformSubscription(Req, e, Id, Fields, Nodes?.ToArray(), FieldTypes,
                                         ServiceToken, DeviceToken, UserToken, MaxAge, MinInterval, MaxInterval);
            }
        }
Пример #27
0
 /// <summary>Remove an object that matches the given id.</summary>
 void ICollectionRef <T> .Remove(Guid id) => ToRemove.Add(id);
Пример #28
0
 /// <summary>Remove objects that matches the given ids.</summary>
 void ICollectionRef <T> .Remove(IList <Guid> ids) => ToRemove = ToRemove.Concat(ids).ToList();
Пример #29
0
        private void OnMessage(XmppClient Client, XmppMessage Message)
        {
            if (Message.MessageType != MessageType.Chat)
            {
                return;
            }

            string s = Message.Body.Trim();

            if (string.IsNullOrEmpty(s))
            {
                return;
            }

            DateTime             Now      = DateTime.Now;
            DateTime             Timeout  = Now.AddMinutes(-15);
            LinkedList <Session> ToRemove = null;
            Session Session;
            string  s2;
            int     i;

            lock (this.sessionByJid)
            {
                foreach (KeyValuePair <DateTime, Session> P in this.sessionByLastAccess)
                {
                    if (P.Key <= Timeout)
                    {
                        if (ToRemove == null)
                        {
                            ToRemove = new LinkedList <Session> ();
                        }

                        ToRemove.AddLast(P.Value);
                    }
                    else
                    {
                        break;
                    }
                }

                if (ToRemove != null)
                {
                    foreach (Session S in ToRemove)
                    {
                        this.sessionByJid.Remove(S.From);
                        this.sessionByLastAccess.Remove(S.LastAccess);
                    }
                }

                if (this.sessionByJid.TryGetValue(Message.From, out Session))
                {
                    this.sessionByLastAccess.Remove(Session.LastAccess);
                }
                else
                {
                    Session      = new Session();
                    Session.From = Message.From;
                    this.sessionByJid [Session.From] = Session;
                }

                while (this.sessionByLastAccess.ContainsKey(Now))
                {
                    Now = Now.AddTicks(gen.Next(1, 10));
                }

                Session.LastAccess             = Now;
                this.sessionByLastAccess [Now] = Session;
            }

            switch (s)
            {
            case "#":
                this.SendMenu(Client, Message.From, true, string.Empty, Session);
                break;

            case "##":
                this.SendMenu(Client, Message.From, false, string.Empty, Session);
                break;

            case "?":
                if (this.provisioning == null)
                {
                    this.SendErrorMessage(Message.From, "No provisioning server has been found, so readout through the chat interface is not allowed.", Session);
                }
                else if (this.sensor == null)
                {
                    this.SendErrorMessage(Message.From, "No sensor interface provided.", Session);
                }
                else
                {
                    ReadoutRequest Request = new ReadoutRequest(ReadoutType.MomentaryValues, DateTime.MinValue, DateTime.MaxValue);
                    this.provisioning.CanRead(Request, Message.From, this.CanReadResponse, new object[] { Message.From, Session });
                }
                break;

            case "??":
                if (this.provisioning == null)
                {
                    this.SendErrorMessage(Message.From, "No provisioning server has been found, so readout through the chat interface is not allowed.", Session);
                }
                else if (this.sensor == null)
                {
                    this.SendErrorMessage(Message.From, "No sensor interface provided.", Session);
                }
                else
                {
                    ReadoutRequest Request = new ReadoutRequest(ReadoutType.All, DateTime.MinValue, DateTime.MaxValue);
                    this.provisioning.CanRead(Request, Message.From, this.CanReadResponse, new object[] { Message.From, Session });
                }
                break;

            case "html+":
                Session.Html = true;
                Client.SendMessage(Message.From, "HTML mode turned on.", MessageType.Chat);
                break;

            case "html-":
                Session.Html = false;
                Client.SendMessage(Message.From, "HTML mode turned off.", MessageType.Chat);
                break;

            case "=?":
            case "!?":
                if (this.provisioning == null)
                {
                    this.SendErrorMessage(Message.From, "No provisioning server has been found, so control  through the chat interface is not allowed.", Session);
                }
                else if (this.control == null)
                {
                    this.SendErrorMessage(Message.From, "No control interface provided.", Session);
                }
                else
                {
                    this.provisioning.CanControl(Message.From, this.CanControlListParametersResponse, new object[] {
                        Message.From,
                        Session
                    }, null, null, null, this.control.Parameters, null);
                }
                break;

            default:
                if (s.EndsWith("??"))
                {
                    if (this.provisioning == null)
                    {
                        this.SendErrorMessage(Message.From, "No provisioning server has been found, so readout through the chat interface is not allowed.", Session);
                    }
                    else if (this.sensor == null)
                    {
                        this.SendErrorMessage(Message.From, "No sensor interface provided.", Session);
                    }
                    else
                    {
                        ReadoutRequest Request = new ReadoutRequest(ReadoutType.All, DateTime.MinValue, DateTime.MaxValue, null, new string[] { s.Substring(0, s.Length - 2) });
                        this.provisioning.CanRead(Request, Message.From, this.CanReadResponse, new object[] { Message.From, Session });
                    }
                }
                else if (s.EndsWith("?"))
                {
                    if (this.provisioning == null)
                    {
                        this.SendErrorMessage(Message.From, "No provisioning server has been found, so readout through the chat interface is not allowed.", Session);
                    }
                    else if (this.sensor == null)
                    {
                        this.SendErrorMessage(Message.From, "No sensor interface provided.", Session);
                    }
                    else
                    {
                        ReadoutRequest Request = new ReadoutRequest(ReadoutType.MomentaryValues, DateTime.MinValue, DateTime.MaxValue, null, new string[] { s.Substring(0, s.Length - 1) });
                        this.provisioning.CanRead(Request, Message.From, this.CanReadResponse, new object[] { Message.From, Session });
                    }
                }
                else if ((i = s.IndexOfAny(controlDelimiters)) > 0)
                {
                    IControlParameter Parameter;

                    if (this.provisioning == null)
                    {
                        this.SendErrorMessage(Message.From, "No provisioning server has been found, so control operations through the chat interface is not allowed.", Session);
                    }
                    else if (this.control == null)
                    {
                        this.SendErrorMessage(Message.From, "No control interface provided.", Session);
                    }
                    else if ((Parameter = this.control [s2 = s.Substring(0, i).Trim()]) == null)
                    {
                        this.SendErrorMessage(Message.From, "No control parameter named '" + s2 + "' found.", Session);
                    }
                    else
                    {
                        this.provisioning.CanControl(Message.From, this.CanControlParameterResponse, new object[] {
                            Message.From,
                            Session,
                            Parameter,
                            s2,
                            s.Substring(i + 1).Trim()
                        }, null, null, null, new string[] { s2 }, null);
                    }
                }
                else
                {
                    this.SendMenu(Client, Message.From, true, "Hello. Following is a list of commands you can use when chatting with me.\r\n\r\n", Session);
                }
                break;
            }
        }
 public void RemoveUserRole(UserRole model)
 {
     ToRemove.Add(model.RoleId);
 }