コード例 #1
1
        //this method is declared as static so it can be run in
        //another static method
        //I've changed this method a bit to read directly into a List<>
        //instead of just a string
        private static List<RosterItem> ReadFileToRosterList(string FileName)
        {
            //I always like to start my method by declaring the return
            //value when there is a value to be returned
            List<RosterItem> returnValue = new List<RosterItem>();

            //set up a counter and line variable
            int counter = 0;
            string line;

            //always be aware of what resources your program is using
            //The C# garbage collector does a pretty good job of maintaining program
            //resources, but you shouldn't count on it whe using librarys that
            //acces external resources sunch as files or databases

            //create a progress bar using a nuget package called ShellProgressBar
            //https://github.com/Mpdreamz/shellprogressbar
            //found this by googling "c# console app progress bar"
            //the max number of items to process
            var maxTicks = File.ReadLines(FileName).Count();

            //create a progress bar
            using (var pbar = new ProgressBar(maxTicks, "Starting", ConsoleColor.DarkGreen))
            {
                //we use a "using" statement to make sure the file resource is released from
                //memory. A try..catch..finally can be used but a "using" statement is easier.
                using (System.IO.StreamReader file = new System.IO.StreamReader(FileName))
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        //update the progress bar
                        pbar.Tick("Currently processing " + counter);

                        //skip the first line
                        if (counter > 0)
                        {
                            //returnValue += line;
                            RosterItem myRosterItem = new RosterItem();

                            string[] myLineArray = line.Split(',');

                            myRosterItem.ID = Convert.ToInt32(myLineArray[0]);
                            myRosterItem.FirstName = myLineArray[1];
                            myRosterItem.LastName = myLineArray[2];
                            myRosterItem.Email = myLineArray[3];
                            myRosterItem.TeamColor = myLineArray[4];
                            myRosterItem.Gender = myLineArray[5];
                            myRosterItem.Position = myLineArray[6];

                            //now that we have a completed object
                            //add it to the returnvalue (Remember the special List<> gives us the ad method automatically)
                            returnValue.Add(myRosterItem);

                            //artifically add a little time to the process
                            System.Threading.Thread.Sleep(250);
                        }

                        counter++;
                    }
                }
            }
            return returnValue;
        }
コード例 #2
0
		/// <summary>
		/// Removes a Rosteritem from the Roster
		/// </summary>
		/// <param name="jid">The BARE jid of the rosteritem that should be removed</param>
		public void RemoveRosterItem(Jid jid)
		{
			RosterIq riq = new RosterIq();
			riq.Type = IqType.set;
				
			RosterItem ri = new RosterItem();
			ri.Jid = jid;
			ri.Subscription = SubscriptionType.remove;

			riq.Query.AddRosterItem(ri);
				
			m_connection.Send(riq);
		}
コード例 #3
0
        void viewModel_OnMessagesRecieved(object sender, object rosterItem)
        {
            try
            {
                RosterItem          current      = rosterItem as RosterItem;
                MainWindowViewModel currentModel = (MainWindowViewModel)sender;


                //MainNotifyWindow nWindow = null;

                //if (this.WindowState == System.Windows.WindowState.Minimized)
                //{
                //    if (lstNotificationWindows == null)
                //        lstNotificationWindows = new List<MainNotifyWindow>();
                //    else
                //        nWindow = lstNotificationWindows.Where(win => win.WindowTitle == current.Name).FirstOrDefault();

                //    if (nWindow == null)
                //    {
                //        nWindow = new MainNotifyWindow()
                //        {
                //            WindowTitle = current.Name,
                //            Messages = current.Messages,
                //            NotificationIcon = ni
                //        };
                //        lstNotificationWindows.Add(nWindow);
                //        nWindow.ShowWindow();
                //    }
                //    else
                //    {
                //        nWindow.Messages = currentModel.CurrentRosterMessages;
                //        if (!((nWindow.PinButton.IsChecked != null) && ((bool)nWindow.PinButton.IsChecked)))
                //            nWindow.ShowWindow();
                //    }
                //}
            }
            catch (Exception)
            {
                Dispatcher.Invoke(new Action(OnErrorOccured));
            }
        }
コード例 #4
0
        private void CheckIfFriendCallback(object Sender, IsFriendResponseEventArgs e2)
        {
            PresenceEventArgs e = (PresenceEventArgs)e2.State;

            if (e2.Ok && e2.Friend)
            {
                Log.Informational("Presence subscription accepted.", e.FromBareJID, this.provisioningServerAddress);
                e.Accept();

                RosterItem Item = this.client.GetRosterItem(e.FromBareJID);
                if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                {
                    this.client.RequestPresenceSubscription(e.FromBareJID);
                }
            }
            else
            {
                Log.Notice("Presence subscription declined.", e.FromBareJID, this.provisioningServerAddress);
                e.Decline();
            }
        }
コード例 #5
0
ファイル: App.xaml.cs プロジェクト: VRDate/MIoT
		private void FriendshipLost(RosterItem Item)
		{
			bool UpdateRegistration = false;

			if (string.Compare(Item.BareJid, this.sensorJid, true) == 0)
			{
				this.sensorJid = null;
				this.sensor = null;
				UpdateRegistration = true;
			}

			if (string.Compare(Item.BareJid, this.actuatorJid, true) == 0)
			{
				this.actuatorJid = null;
				this.actuator = null;
				UpdateRegistration = true;
			}

			if (UpdateRegistration)
				Task.Run(this.RegisterDevice);
		}
コード例 #6
0
        private void contextMenu_Opening(object sender, CancelEventArgs e)
        {
            // 当前的 Link (好友) 不为空
            if (hintLink != null)
            {
                NavBarItem navBarItem = hintLink.Item as NavBarItem;
                RosterItem roster     = navBarItem.Tag as RosterItem;
                moveToToolStripMenuItem.Text = "移动“" + navBarItem.Caption + "”到";
                SetMenuItem(true);

                String jid          = roster.Jid.Bare;
                int    mobileStatus = -1;
                int    status       = -1;
                String mobileRes    = null;
                //wei=>PresenceManager.Instance.GetUserStatus(jid, out mobileStatus,out mobileRes, out status);

                //wei=>if (mobileStatus == ResManager.STATUS_AWAY ||
                //wei=>    mobileStatus == ResManager.STATUS_DND ||
                //wei=>    mobileStatus == ResManager.STATUS_ONLINE ||
                //wei=>    mobileStatus == ResManager.STATUS_XA)
                //wei=>{
                locReqToolStripMenuItem.Enabled = true;
                //wei=>}
                //wei=> else
                //wei=> {
                //wei=>     locReqToolStripMenuItem.Enabled = false;
                //wei=> }

                return;
            }
            else if (hintGroup != null) // 当前的组不为空
            {
                moveToToolStripMenuItem.Text = "移动好友到";
                SetMenuItem(false);
                return;
            }

            e.Cancel = true;
            return;
        }
コード例 #7
0
        /// <summary>
        /// 更新组名(未实现)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void renameGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RosterItem item = GetCurrentRosterItem();

            if (item == null)
            {
                return;
            }
            String        newName = item.Name;
            List <String> groups  = new List <string>();

            foreach (Element elm in item.GetGroups())
            {
                groups.Add(elm.Value);
            }

            //wei=> InputValueForm form = new InputValueForm();
            //wei=> form.InputText = item.Name;
            //wei=> if (form.ShowDialog(this.FindForm(),"重命名","好友名称") == DialogResult.Cancel)
            //wei=> {
            //wei=>    return;
            //wei=> }
            //wei=>else
            //wei=> {
            // 新建组的名称
            //wei=>    newName = form.InputText;
            //wei=>  }


            // 需要移动好友的JID赋值给变量 movingJid
            movingJid = item.Jid;
            // 设置同步标记为阻塞状态
            movingJidFlag.Reset();

            // 更新好友的组信息
            //wei=>xmppClient.ClientConnection.RosterManager.UpdateRosterItem(movingJid, newName, groups.ToArray());

            // 线程中等待移动好友到其他组成功
            //wei=>ThreadUtils.Run(WaitUpdateRosterItem);
        }
コード例 #8
0
        /// <summary>
        /// 统计组在线的人数,格式为:3/12
        /// </summary>
        /// <param name="group"></param>
        private String GroupStatusCount(String name)
        {
            int         count       = 0;
            int         onlineCount = 0;
            NavBarGroup group       = this.navBar.Groups[name];

            if (group != null)
            {
                foreach (NavBarItemLink link in group.ItemLinks)
                {
                    count++;
                    RosterItem rosterItem = link.Item.Tag as RosterItem;
                    //wei=>if (link.Item.SmallImageIndex != ResManager.STATUS_UNSUBSCRIBED &&
                    //wei=>     link.Item.SmallImageIndex != ResManager.STATUS_OFFLINE)
                    //wei=> {
                    //wei=>     onlineCount++;
                    //wei=>}
                }
            }

            return(String.Format(" [{0}/{1}]", onlineCount, count));
        }
コード例 #9
0
        public override bool NewMessage(Message iq)
        {
            /// See if this is a standard text message
            ///
            if (iq is ChatMessage)
            {
                ChatMessage chatmsg = iq as ChatMessage;
                RosterItem  item    = XMPPClient.FindRosterItem(chatmsg.From);
                if (item != null)
                {
                    if (chatmsg.Body != null)
                    {
                        TextMessage txtmsg = new TextMessage();
                        txtmsg.From     = chatmsg.From;
                        txtmsg.To       = chatmsg.To;
                        txtmsg.Received = DateTime.Now;
                        if (chatmsg.Delivered.HasValue == true)
                        {
                            txtmsg.Received = chatmsg.Delivered.Value; /// May have been a server stored message
                        }
                        txtmsg.Message = chatmsg.Body;
                        txtmsg.Sent    = false;
                        item.AddRecvTextMessage(txtmsg);
                        item.HasNewMessages = true;

                        // Notify XMPPClient that a new conversation item has been added
                        XMPPClient.FireNewConversationItem(item, true, txtmsg);
                    }
                    if (chatmsg.ConversationState != ConversationState.none)// A conversation message
                    {
                        item.Conversation.ConversationState = chatmsg.ConversationState;
                        XMPPClient.FireNewConversationState(item, item.Conversation.ConversationState);
                    }
                }
                return(true);
            }

            return(false);
        }
コード例 #10
0
        private void Client_OnRosterItemUpdated(object Sender, RosterItem Item)
        {
            if (this.children == null)
            {
                this.CheckRoster();
            }
            else
            {
                XmppContact Contact;
                bool        Added = false;

                lock (this.children)
                {
                    if (this.children.TryGetValue(Item.BareJid, out TreeNode Node))
                    {
                        if ((Contact = Node as XmppContact) != null)
                        {
                            Contact.RosterItem = Item;
                        }
                    }
                    else
                    {
                        Contact = new XmppContact(this, this.client, Item.BareJid);
                        this.children[Item.BareJid] = Contact;
                        Added = true;
                    }
                }

                if (Added)
                {
                    this.connections.Owner.MainView.NodeAdded(this, Contact);
                    this.OnUpdated();
                }
                else
                {
                    Contact.OnUpdated();
                }
            }
        }
コード例 #11
0
        public XmppHandlerResult ProcessElement(Presence element, XmppSession session, XmppHandlerContext context)
        {
            var result = Component();

            var userItem = context.Storages.Users.GetRosterItem(element.To, session.Jid);

            if (userItem != null && !userItem.HasToSubscription() && userItem.Ask == AskType.subscribe)
            {
                var contactItem = context.Storages.Users.GetRosterItem(session.Jid, element.To);
                if (contactItem == null)
                {
                    contactItem = new RosterItem(element.To);
                    if (element.Nickname != null && !string.IsNullOrEmpty(element.Nickname.Value))
                    {
                        contactItem.Name = element.Nickname.Value;
                    }
                }
                if (!contactItem.HasFromSubscription())
                {
                    contactItem.SetFromSubscription(true);
                    context.Storages.Users.SaveRosterItem(session.Jid, contactItem);
                    result.Add(new RosterPush(session.Jid, contactItem, context));
                }

                userItem.SetToSubscription(true);
                userItem.Ask = AskType.NONE;
                context.Storages.Users.SaveRosterItem(element.To, userItem);

                result.Add(Send(context.Sessions.GetSessions(element.To.BareJid), element));
                result.Add(new RosterPush(element.To, userItem, context));
                foreach (var s in context.Sessions.GetSessions(session.Jid.BareJid))
                {
                    // available
                    result.Add(Send(context.Sessions.GetSessions(element.To.BareJid), Presence.Available(s.Jid, element.To)));
                }
            }

            return(result);
        }
コード例 #12
0
        /// <summary>
        /// NavBar 双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBar_DoubleClick(object sender, EventArgs e)
        {
            // 如果是 Link (选中的是用户)
            if (hintLink != null)
            {
                NavBarItem navBarItem = hintLink.Item as NavBarItem;
                RosterItem item       = navBarItem.Tag as RosterItem;

                //wei=>ChatManagerForm.Instance.StartChat(item.Jid);
            } // 如果选中的是组
            else if (hintGroup != null)
            {
                hintGroup.Expanded = !hintGroup.Expanded;
                //for (int i = 0; i < hintGroup.ItemLinks.Count; i++)
                //{
                //    NavBarItemLink link = hintGroup.ItemLinks[i];
                //    NavBarItem navBarItem = link.Item as NavBarItem;
                //    RosterItem item = navBarItem.Tag as RosterItem;
                //}
                // 群发
            }
        }
コード例 #13
0
ファイル: IQs.cs プロジェクト: ArsenShnurkov/NetTalk-Server
 public static void ProcessRosterIQSet(string username, IQ iq)
 {
     if (iq.Query.HasChildElements)
     {
         BLL.Users api = new BLL.Users();
         foreach (Node r in iq.Query.ChildNodes)
         {
             Element el = r as Element;
             if (el != null)
             {
                 RosterItem ri = el as RosterItem;
                 if (el.HasAttribute("subscription"))
                 {
                     if (ri.Subscription == SubscriptionType.remove)
                     {
                         api.DeleteFriend(username, ri.Jid.User);
                     }
                 }
                 if (el.HasChildElements)
                 {
                     NodeList    li        = el.ChildNodes;
                     ElementList eli       = ri.GetGroups();
                     string      groupName = null;
                     if (eli.Count > 0)
                     {
                         groupName = eli.Item(0).Value;
                     }
                     if (li.Count > 0)
                     {
                         api.ChangeFriendStatus(username, ri.Jid.User, groupName, null, true);
                     }
                 }
             }
         }
         iq.Type = IqType.get;
         ProcessRosterIQGet(username, iq);
     }
 }
コード例 #14
0
        private ThingReference GetReference(RosterItem Item, string Prefix)
        {
            string NodeId    = string.Empty;
            string SourceId  = string.Empty;
            string Partition = string.Empty;

            Prefix += ".";

            foreach (string Group in Item.Groups)
            {
                if (Group.StartsWith(Prefix))
                {
                    string s = Group.Substring(Prefix.Length);
                    int    i = s.IndexOf(':');
                    if (i < 0)
                    {
                        continue;
                    }

                    switch (s.Substring(0, i).ToLower())
                    {
                    case "nid":
                        NodeId = s.Substring(i + 1);
                        break;

                    case "sid":
                        SourceId = s.Substring(i + 1);
                        break;

                    case "prt":
                        Partition = s.Substring(i + 1);
                        break;
                    }
                }
            }

            return(new ThingReference(NodeId, SourceId, Partition));
        }
コード例 #15
0
ファイル: ChatPage.xaml.cs プロジェクト: quangfox/Voip
        void DoOnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
        {
            if (item.JID.BareJID == OurRosterItem.JID.BareJID)
            {
                /// Clear our new message flag for this roster user as long as this window is open
                item.HasNewMessages = false;

                AddInlinesForMessage(msg);

                this.TextBlockChat.Focus();


                //TextPointer myTextPointer1 = MainParagraph.ContentStart.GetPositionAtOffset(20);
                //TextPointer myTextPointer1 = MainParagraph.ContentEnd.GetPositionAtOffset(0, LogicalDirection.Backward);
                //TextPointer myTextPointer2 = MainParagraph.ContentEnd.GetPositionAtOffset(0, LogicalDirection.Backward);
                this.TextBlockChat.Selection.Select(this.TextBlockChat.ContentEnd, this.TextBlockChat.ContentEnd);

                ScrollChat.ScrollToVerticalOffset(this.TextBlockChat.ActualHeight + 100);
                //this.ListBoxConversation.UpdateLayout();
                //if (this.ListBoxConversation.Items.Count > 0)
                //   this.ListBoxConversation.ScrollIntoView(this.ListBoxConversation.Items[this.ListBoxConversation.Items.Count - 1]);
            }
        }
コード例 #16
0
        private void ProcessRosterIq(Iq iq)
        {
            if (iq.Type == IqType.Get)
            {
                // Send the roster
                // we send a dummy roster here, you should retrieve it from a
                // database or some kind of directory (LDAP, AD etc...)
                iq.SwitchDirection();
                iq.Type = IqType.Result;
                String[] contact = new string[3];
                contact[0] = "krishna";
                contact[1] = "madu";
                contact[2] = "madu2";
                for (int i = 0; i < contact.Length; i++)
                {
                    // don't add yourself to the contact list (aka roster)
                    if (contact[i].Equals(Jid.User))
                    {
                        continue;
                    }

                    var ri = new RosterItem
                    {
                        Jid          = new Jid(contact[i] + "@" + XmppDomain),
                        Name         = contact[i],
                        Subscription = Subscription.Both
                    };
                    ri.AddGroup("Group 1");
                    iq.Query.Add(ri);
                }
                Send(iq);
            }
            else if (iq.Type == IqType.Set)
            {
                // TODO, handle roster add, remove and update here.
            }
        }
コード例 #17
0
    public override bool TryChangeGameElementValue(string name, int change)
    {
        RosterItem ele = unitList.Find(x => x.name == name) as RosterItem;

        if (ele != null)
        {
            int newValue = ele.value + change;
            if (currTeamNum + change > maxTeamNum)
            {
                Toast.Pop("队伍无法容纳更多的人");
            }
            else if (newValue > ele.maxValue)
            {
                Toast.Pop("你缺少" + ele.name);
            }
            else if (newValue >= 0)
            {
                ele.value = newValue;
                //Notify();
                return(true);
            }
        }
        return(false);
    }
コード例 #18
0
ファイル: XmppContact.cs プロジェクト: MustafaUzumcuCom/Hanoi
        /// <summary>
        ///   Adds to group.
        /// </summary>
        /// <param name = "groupName">Name of the group.</param>
        public void AddToGroup(string groupName)
        {
            var iq    = new IQ();
            var query = new RosterQuery();
            var item  = new RosterItem();

            if (!Groups.Contains(groupName))
            {
                Groups.Add(groupName);
            }

            iq.Type = IQType.Set;

            item.Jid          = ContactId.BareIdentifier;
            item.Name         = Name;
            item.Subscription = (RosterSubscriptionType)Subscription;

            item.Groups.Add(groupName);

            query.Items.Add(item);
            iq.Items.Add(query);

            session.Send(iq);
        }
コード例 #19
0
        public void SendChatMessage(TextMessage txtmsg)
        {
            txtmsg.Sent = true;
            ChatMessage msg = new ChatMessage(null);

            msg.From = txtmsg.From;
            msg.To   = txtmsg.To;
            msg.Type = "chat";
            msg.Body = txtmsg.Message;
            //msg.InnerXML = string.Format(@"<body>{0}</body>", txtmsg.Message);

            /// Find the roster guy for this message and add it to their conversation
            ///
            RosterItem item = XMPPClient.FindRosterItem(txtmsg.To);

            if (item != null)
            {
                item.AddSendTextMessage(txtmsg);
                // Notify XMPPClient that a new conversation item has been added
                XMPPClient.FireNewConversationItem(item, false, txtmsg);
            }

            XMPPClient.SendXMPP(msg);
        }
コード例 #20
0
        /// <summary>
        /// Add a Rosteritem to the Roster
        /// </summary>
        /// <param name="jid">The BARE jid of the rosteritem that should be removed</param>
        /// <param name="nickname">Nickname for the RosterItem</param>
        /// <param name="group">An Array of groups when you want to add the Rosteritem to multiple groups</param>
        public void AddRosterItem(Jid jid, string nickname, string[] group)
        {
            RosterIq riq = new RosterIq();

            riq.Type = IqType.set;

            RosterItem ri = new RosterItem();

            ri.Jid = jid;

            if (nickname != null)
            {
                ri.Name = nickname;
            }

            foreach (string g in group)
            {
                ri.AddGroup(g);
            }

            riq.Query.AddRosterItem(ri);

            m_connection.Send(riq);
        }
コード例 #21
0
ファイル: ChatPage.xaml.cs プロジェクト: quangfox/Voip
        public static void SaveConversation(RosterItem item)
        {
            /// Save this conversation so it can be restored later... save it under the JID name

            string strFilename = string.Format("{0}_conversation.item", item.JID.BareJID);



            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Load from storage
                IsolatedStorageFileStream location = new IsolatedStorageFileStream(strFilename, System.IO.FileMode.Create, storage);
                DataContractSerializer    ser      = new DataContractSerializer(typeof(System.Net.XMPP.Conversation));

                try
                {
                    ser.WriteObject(location, item.Conversation);
                }
                catch (Exception)
                {
                }
                location.Close();
            }
        }
コード例 #22
0
        /// <summary>
        ///   Deletes a user from the roster list
        /// </summary>
        public XmppRoster RemoveContact(XmppJid jid)
        {
            var query = new RosterQuery();
            var iq    = new IQ();

            iq.ID   = XmppIdentifierGenerator.Generate();
            iq.Type = IQType.Set;
            iq.From = connection.UserId;

            var item = new RosterItem();

            item.Jid          = jid.BareIdentifier;
            item.Subscription = RosterSubscriptionType.Remove;

            query.Items.Add(item);

            iq.Items.Add(query);

            pendingMessages.Add(iq.ID);

            connection.Send(iq);

            return(this);
        }
コード例 #23
0
 public int Add(RosterItem value)
 {
     return (List.Add(value));
 }
コード例 #24
0
        private async void Request(string Method, HttpRequest Request, HttpResponse Response)
        {
            try
            {
                string Url = Request.SubPath;
                if (Url.StartsWith("/"))
                {
                    Url = Url.Substring(1);
                }

                if (!Url.StartsWith("httpx://", StringComparison.OrdinalIgnoreCase))
                {
                    throw new BadRequestException();
                }

                int i = Url.IndexOf('/', 8);
                if (i < 0)
                {
                    throw new BadRequestException();
                }

                string BareJID  = Url.Substring(8, i - 8);
                string LocalUrl = Url.Substring(i);

                IHttpxCachedResource CachedResource;

                if (Method == "GET" && this.httpxCache != null)
                {
                    if ((CachedResource = await this.httpxCache.TryGetCachedResource(BareJID, LocalUrl)) != null)
                    {
                        if (Request.Header.IfNoneMatch != null)
                        {
                            if (CachedResource.ETag != null && Request.Header.IfNoneMatch.Value == CachedResource.ETag)
                            {
                                throw new NotModifiedException();
                            }
                        }
                        else if (Request.Header.IfModifiedSince != null)
                        {
                            DateTimeOffset?Limit;

                            if ((Limit = Request.Header.IfModifiedSince.Timestamp).HasValue &&
                                HttpFolderResource.LessOrEqual(CachedResource.LastModified.UtcDateTime, Limit.Value.ToUniversalTime()))
                            {
                                throw new NotModifiedException();
                            }
                        }

                        HttpFolderResource.SendResponse(CachedResource.FileName, CachedResource.ContentType, CachedResource.ETag,
                                                        CachedResource.LastModified.UtcDateTime, Response);

                        return;
                    }
                }

                RosterItem Item = this.defaultXmppClient.GetRosterItem(BareJID);
                if (Item == null)
                {
                    if (!XmppClient.BareJidRegEx.IsMatch(BareJID))
                    {
                        throw new BadRequestException();
                    }

                    // TODO: Request presence subscription, if user authenticated and request valid.

                    throw new ConflictException();                      // TODO: Provide body describing error.
                }
                else
                {
                    foreach (PresenceEventArgs e in Item.Resources)
                    {
                        // TODO: Select one based on features.

                        if (this.serverlessMessaging != null)
                        {
                            this.serverlessMessaging.GetPeerConnection(e.From, this.SendP2P, new SendP2pRec()
                            {
                                item     = Item,
                                method   = Method,
                                fullJID  = e.From,
                                localUrl = LocalUrl,
                                request  = Request,
                                response = Response
                            });
                        }
                        else
                        {
                            this.SendRequest(this.httpxClient, e.From, Method, BareJID, LocalUrl, Request, Response);
                        }

                        return;
                    }

                    throw new ServiceUnavailableException();
                }
            }
            catch (Exception ex)
            {
                Response.SendResponse(ex);
            }
        }
コード例 #25
0
 public bool Contains(RosterItem value)
 {
     return(List.Contains(value));
 }
コード例 #26
0
ファイル: ChatPage.xaml.cs プロジェクト: Hitchhikrr/Voip
 void XMPPClient_OnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
 {
     Dispatcher.BeginInvoke(new System.Net.XMPP.XMPPClient.DelegateNewConversationItem(DoOnNewConversationItem), item, bReceived, msg);
 }
コード例 #27
0
ファイル: XmppContact.cs プロジェクト: tshwangq/Hanoi
        /// <summary>
        ///   Adds to group.
        /// </summary>
        /// <param name = "groupName">Name of the group.</param>
        public void AddToGroup(string groupName)
        {
            var iq = new IQ();
            var query = new RosterQuery();
            var item = new RosterItem();

            if (!Groups.Contains(groupName))
            {
                Groups.Add(groupName);
            }

            iq.Type = IQType.Set;

            item.Jid = ContactId.BareIdentifier;
            item.Name = Name;
            item.Subscription = (RosterSubscriptionType)Subscription;

            item.Groups.Add(groupName);

            query.Items.Add(item);
            iq.Items.Add(query);

            session.Send(iq);
        }
コード例 #28
0
ファイル: App.xaml.cs プロジェクト: Hitchhikrr/Voip
 void SafeOnNewIncomingFileTransferRequest(FileTransfer trans, RosterItem itemfrom)
 {
     this.RootFrame.Navigate(new Uri("/FileTransferPage.xaml", UriKind.Relative));
 }
コード例 #29
0
 void FileTransferManager_OnNewIncomingFileTransferRequest(FileTransfer trans, RosterItem itemfrom)
 {
     Dispatcher.BeginInvoke(new FileTransferManager.DelegateIncomingFile(SafeOnNewIncomingFileTransferRequest), trans, itemfrom);
 }
コード例 #30
0
ファイル: frmMain.cs プロジェクト: vanloc0301/mychongchong
 private void XmppCon_OnRosterItem(object sender, RosterItem item)
 {
     if (base.InvokeRequired)
     {
         base.BeginInvoke(new XmppClientConnection.RosterHandler(this, (IntPtr) this.XmppCon_OnRosterItem), new object[] { this, item });
     }
     else if (item.get_Subscription() != 4)
     {
         this.rosterControl.AddRosterItem(item);
     }
     else
     {
         this.rosterControl.RemoveRosterItem(item);
     }
 }
コード例 #31
0
ファイル: Client.cs プロジェクト: nagysa1313/pvpnetwpchat
 public ConversationItem(RosterItem rosterItem, TextMessage message)
     : base()
 {
     RosterItem = rosterItem;
     Message = message;
     OnPropertyChanged("RosterItem");
     OnPropertyChanged("Message");
 }
コード例 #32
0
ファイル: Client.cs プロジェクト: nagysa1313/pvpnetwpchat
 void XMPPClient_OnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
 {
     if (bReceived)
     {
         var key = Guid.NewGuid();
         ConversationItems.Add(key, new ConversationItem(item, msg));
         if (NewConversationItem != null)
             NewConversationItem(this, new ConversationItemEventArgs(key));
     }
 }
コード例 #33
0
ファイル: RosterWidget.cs プロジェクト: goto/synapse
 void on_rosterGrid_customContextMenuRequested(QPoint point)
 {
     m_MenuDownItem = rosterGrid.HoverItem;
     if (m_MenuDownItem != null) {
         m_InviteActions.ForEach(a => m_InviteMenu.RemoveAction(a));
         if (m_MenuDownItem.Account.ConferenceManager.Count > 0) {
             m_InviteActions.Add(m_InviteMenu.AddSeparator());
             foreach (var conference in m_MenuDownItem.Account.ConferenceManager.Rooms) {
                 QAction action = m_InviteMenu.AddAction(conference.JID);
                 m_InviteActions.Add(action);
             }
         }
         m_RosterItemMenu.Popup(rosterGrid.MapToGlobal(point));
     }
 }
コード例 #34
0
ファイル: RosterWidget.cs プロジェクト: goto/synapse
 void HandleItemActivated(AvatarGrid<RosterItem> grid, RosterItem item)
 {
     Gui.TabbedChatsWindow.StartChat(item.Account, item.Item.JID);
 }
コード例 #35
0
 public int IndexOf(RosterItem value)
 {
     return (List.IndexOf(value));
 }
コード例 #36
0
        public static void Main(string[] _)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.White;

                Console.Out.WriteLine("Welcome to the PC Sensor application.");
                Console.Out.WriteLine(new string('-', 79));
                Console.Out.WriteLine("This application will publish performace couters as sensor values.");
                Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions.");

                Log.Register(new ConsoleEventSink(false));
                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                        Environment.MachineName,                              // Default user name.
                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                        typeof(Program).Assembly);

                using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly))
                {
                    if (credentials.Sniffer)
                    {
                        Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces));
                    }

                    if (!string.IsNullOrEmpty(credentials.Events))
                    {
                        Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false));
                    }

                    if (!string.IsNullOrEmpty(credentials.ThingRegistry))
                    {
                        thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry);

                        thingRegistryClient.Claimed += (sender, e) =>
                        {
                            ownerJid = e.JID;
                            Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Disowned += (sender, e) =>
                        {
                            Log.Informational("Thing has been disowned.", ownerJid);
                            ownerJid = string.Empty;
                            Register();
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Removed += (sender, e) =>
                        {
                            Log.Informational("Thing has been removed from the public registry.", ownerJid);
                            return(Task.CompletedTask);
                        };
                    }

                    ProvisioningClient ProvisioningClient = null;
                    if (!string.IsNullOrEmpty(credentials.Provisioning))
                    {
                        ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning);
                    }

                    Timer ConnectionTimer = new Timer((P) =>
                    {
                        if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating)
                        {
                            try
                            {
                                Client.Reconnect();
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }
                    }, null, 60000, 60000);

                    bool Connected = false;
                    bool ImmediateReconnect;

                    Client.OnStateChanged += (sender, NewState) =>
                    {
                        switch (NewState)
                        {
                        case XmppState.Connected:
                            Connected = true;

                            if (!registered && thingRegistryClient != null)
                            {
                                Register();
                            }
                            break;

                        case XmppState.Offline:
                            ImmediateReconnect = Connected;
                            Connected          = false;

                            if (ImmediateReconnect)
                            {
                                Client.Reconnect();
                            }
                            break;
                        }

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceSubscribe += (sender, e) =>
                    {
                        e.Accept();                             // TODO: Provisioning

                        RosterItem Item = Client.GetRosterItem(e.FromBareJID);
                        if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                        {
                            Client.RequestPresenceSubscription(e.FromBareJID);
                        }

                        Client.SetPresence(Availability.Chat);

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceUnsubscribe += (sender, e) =>
                    {
                        e.Accept();
                        return(Task.CompletedTask);
                    };

                    Client.OnRosterItemUpdated += (sender, e) =>
                    {
                        if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                        {
                            Client.RemoveRosterItem(e.BareJid);
                        }

                        return(Task.CompletedTask);
                    };

                    SortedDictionary <string, string[]> CategoryIncluded = new SortedDictionary <string, string[]>();

                    List <string> Instances = new List <string>();
                    XmlDocument   Doc       = new XmlDocument()
                    {
                        PreserveWhitespace = true
                    };
                    Doc.Load("categories.xml");

                    XSL.Validate("categories.xml", Doc, "Categories", "http://waher.se/Schema/PerformanceCounterCategories.xsd",
                                 XSL.LoadSchema("Waher.Service.PcSensor.Schema.PerformanceCounterCategories.xsd"));

                    foreach (XmlNode N in Doc.DocumentElement.ChildNodes)
                    {
                        if (N.LocalName == "Category")
                        {
                            XmlElement E       = (XmlElement)N;
                            string     Name    = XML.Attribute(E, "name");
                            bool       Include = XML.Attribute(E, "include", false);

                            if (Include)
                            {
                                Instances.Clear();

                                foreach (XmlNode N2 in N.ChildNodes)
                                {
                                    if (N2.LocalName == "Instance")
                                    {
                                        E = (XmlElement)N2;
                                        Instances.Add(XML.Attribute(E, "name"));
                                    }
                                }

                                CategoryIncluded[Name] = Instances.ToArray();
                            }
                            else
                            {
                                CategoryIncluded[Name] = null;
                            }
                        }
                    }

                    SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, false);
                    SensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                    {
                        Log.Informational("Readout requested", string.Empty, Request.Actor);

                        List <Field> Fields = new List <Field>();
                        DateTime     Now    = DateTime.Now;

                        Fields.Add(new StringField(ThingReference.Empty, Now, "Machine Name", Environment.MachineName, FieldType.Identity, FieldQoS.AutomaticReadout));
                        Fields.Add(new StringField(ThingReference.Empty, Now, "OS Platform", Environment.OSVersion.Platform.ToString(), FieldType.Identity, FieldQoS.AutomaticReadout));
                        Fields.Add(new StringField(ThingReference.Empty, Now, "OS Service Pack", Environment.OSVersion.ServicePack, FieldType.Identity, FieldQoS.AutomaticReadout));
                        Fields.Add(new StringField(ThingReference.Empty, Now, "OS Version", Environment.OSVersion.VersionString, FieldType.Identity, FieldQoS.AutomaticReadout));
                        Fields.Add(new Int32Field(ThingReference.Empty, Now, "Processor Count", Environment.ProcessorCount, FieldType.Status, FieldQoS.AutomaticReadout));

                        string[] InstanceNames;
                        string   FieldName;
                        string   Unit;
                        double   Value;
                        byte     NrDec;
                        bool     Updated = false;

                        foreach (PerformanceCounterCategory Category in PerformanceCounterCategory.GetCategories())
                        {
                            FieldName = Category.CategoryName;
                            lock (CategoryIncluded)
                            {
                                if (CategoryIncluded.TryGetValue(FieldName, out InstanceNames))
                                {
                                    if (InstanceNames is null)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    CategoryIncluded[FieldName] = null;
                                    Updated = true;
                                    continue;
                                }
                            }

                            if (Category.CategoryType == PerformanceCounterCategoryType.MultiInstance)
                            {
                                foreach (string InstanceName in Category.GetInstanceNames())
                                {
                                    if (InstanceNames.Length > 0 && Array.IndexOf <string>(InstanceNames, InstanceName) < 0)
                                    {
                                        continue;
                                    }

                                    foreach (PerformanceCounter Counter in Category.GetCounters(InstanceName))
                                    {
                                        FieldName = Category.CategoryName + ", " + InstanceName + ", " + Counter.CounterName;
                                        Value     = Counter.NextValue();
                                        GetUnitPrecision(ref FieldName, Value, out NrDec, out Unit);

                                        if (Fields.Count >= 100)
                                        {
                                            Request.ReportFields(false, Fields);
                                            Fields.Clear();
                                        }

                                        Fields.Add(new QuantityField(ThingReference.Empty, Now, FieldName, Value, NrDec, Unit, FieldType.Momentary, FieldQoS.AutomaticReadout));
                                    }
                                }
                            }
                            else
                            {
                                foreach (PerformanceCounter Counter in Category.GetCounters())
                                {
                                    FieldName = Category.CategoryName + ", " + Counter.CounterName;
                                    Value     = Counter.NextValue();
                                    GetUnitPrecision(ref FieldName, Value, out NrDec, out Unit);

                                    if (Fields.Count >= 100)
                                    {
                                        Request.ReportFields(false, Fields);
                                        Fields.Clear();
                                    }

                                    Fields.Add(new QuantityField(ThingReference.Empty, Now, FieldName, Value, NrDec, Unit, FieldType.Momentary, FieldQoS.AutomaticReadout));
                                }
                            }
                        }

                        Request.ReportFields(true, Fields);

                        if (Updated)
                        {
                            using (StreamWriter s = File.CreateText("categories.xml"))
                            {
                                using (XmlWriter w = XmlWriter.Create(s, XML.WriterSettings(true, false)))
                                {
                                    w.WriteStartElement("Categories", "http://waher.se/Schema/PerformanceCounterCategories.xsd");

                                    lock (CategoryIncluded)
                                    {
                                        foreach (KeyValuePair <string, string[]> P in CategoryIncluded)
                                        {
                                            w.WriteStartElement("Category");
                                            w.WriteAttributeString("name", P.Key);
                                            w.WriteAttributeString("include", CommonTypes.Encode(P.Value != null));

                                            if (P.Value != null)
                                            {
                                                foreach (string InstanceName in P.Value)
                                                {
                                                    w.WriteStartElement("Instance");
                                                    w.WriteAttributeString("name", P.Key);
                                                    w.WriteEndElement();
                                                }
                                            }

                                            w.WriteEndElement();
                                        }
                                    }

                                    w.WriteEndElement();
                                    w.Flush();
                                }
                            }
                        }

                        return(Task.CompletedTask);
                    };

                    BobClient  BobClient  = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                    ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ProvisioningClient);

                    Client.Connect();

                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Out.WriteLine(ex.Message);
            }
            finally
            {
                Log.Terminate();
            }
        }
コード例 #37
0
		/// <summary>
		/// Add a Rosteritem to the Roster
		/// </summary>
		/// <param name="jid">The BARE jid of the rosteritem that should be removed</param>
		/// <param name="nickname">Nickname for the RosterItem</param>
		/// <param name="group">An Array of groups when you want to add the Rosteritem to multiple groups</param>
		public void AddRosterItem(Jid jid, string nickname, string[] group)
		{
			RosterIq riq = new RosterIq();
			riq.Type = IqType.set;
				
			RosterItem ri = new RosterItem();
			ri.Jid	= jid;
			
			if (nickname != null)
				ri.Name	= nickname;
			
			foreach (string g in group)
			{
				ri.AddGroup(g);			
			}

			riq.Query.AddRosterItem(ri);
				
			m_connection.Send(riq);
		}
コード例 #38
0
        void XMPPClient_OnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
        {
            if (msg.Message.IndexOf("Call from ") == 0 && this.hack == false)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => ButtonStartVoice.Content = "Accept Voice Call");
                string ipen = msg.Message.Substring(10);
                int pos = ipen.IndexOf(':');
                me = new MediaPart(AudioStream, null);
                me.remote = new IPEndPoint(IPAddress.Parse(ipen.Substring(0, pos)), Convert.ToInt32(ipen.Substring(pos + 1)));
            }
            else if (msg.Message.IndexOf("Call ok") == 0 && this.hack == true)
            {
                string ipen = msg.Message.Substring(8);
                int pos = ipen.IndexOf(':');
                me.remote = new IPEndPoint(IPAddress.Parse(ipen.Substring(0, pos)), Convert.ToInt32(ipen.Substring(pos + 1)));
                Deployment.Current.Dispatcher.BeginInvoke(() => { ButtonStartVoice.Content = "End Voice Call"; });
                Datastore.Add(me.localEp, "localEp");
                Datastore.Add(me.stream, "stream");
                Datastore.Add(me.remote, "remoteEp");
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                this.NavigationService.Navigate(new Uri("/TestPAge.xaml?", UriKind.Relative)));

            }

            Dispatcher.BeginInvoke(new System.Net.XMPP.XMPPClient.DelegateNewConversationItem(DoOnNewConversationItem), item, bReceived, msg);
        }
コード例 #39
0
ファイル: Packet.cs プロジェクト: yuechuanbingzhi163/GJTalk
 void ProcessBindIq(XmppBase.Iq iq)
 {
     iq.SwitchDirection();
     iq.Type = IqType.result;
     var roster = new RosterItem();
     Bind bind = iq.Query as Bind;
     bind.RemoveAll();
     bind.Jid = Session.SessionUser.Username + "@gjtalk.com";
     Session.Send(iq);
 }
コード例 #40
0
        public override bool NewMessage(Message iq)
        {
            /// Look for pubsub events
            ///
            if (iq is PubSubEventMessage)
            {
                PubSubEventMessage psem = iq as PubSubEventMessage;
                if (psem.Event != null)
                {
                    if ((psem.Event.Items != null) && (psem.Event.Items.Items != null) && (psem.Event.Items.Items.Length > 0))
                    {
                        PubSubItem psitem = psem.Event.Items.Items[0];
                        XElement   elem   = psitem.InnerItemXML as XElement;

                        if (psem.Event.Items.Node == "http://jabber.org/protocol/tune")
                        {
                            TuneItem item = psitem.GetObjectFromXML <TuneItem>();
                            if (item != null)
                            {
                                /// find the roster item, set the tune item
                                RosterItem rosteritem = XMPPClient.FindRosterItem(iq.From);
                                if (rosteritem != null)
                                {
                                    rosteritem.Tune = item;
                                }
                            }
                        }
                        else if (psem.Event.Items.Node == "http://jabber.org/protocol/geoloc")
                        {
                            geoloc item = psitem.GetObjectFromXML <geoloc>();
                            if (item != null)
                            {
                                /// find the roster item, set the tune item
                                RosterItem rosteritem = XMPPClient.FindRosterItem(iq.From);
                                if (rosteritem != null)
                                {
                                    rosteritem.GeoLoc = item;
                                }
                            }
                        }
                        else if (psem.Event.Items.Node == "http://jabber.org/protocol/mood")
                        {
                        }
                        else if (psem.Event.Items.Node == "urn:xmpp:avatar:metadata") /// item avatar metadata
                        {
                            /// We have update avatar info for this chap, we should then proceed to get the avatar data
                            ///
                            foreach (PubSubItem objItem in psem.Event.Items.Items)
                            {
                                avatarmetadata meta = psitem.GetObjectFromXML <avatarmetadata>();
                                if (meta != null)
                                {
                                    /// Request this node ? maybe we get it automatically?
                                    ///
                                }
                                /// Not sure why they would have more than 1 avatar item, so we'll ignore fom now
                                ///
                                break;
                            }
                        }
                        else if (psem.Event.Items.Node == "urn:xmpp:avatar:data") /// item avatar
                        {
                            /// We have update avatar info for this chap, we should then proceed to get the avatar data
                            ///
                            /// Works, but let's comment out for now to focus on more supported avatar methods
                            //foreach (PubSubItem objItem in psem.Items)
                            //{
                            //    avatardata data = Utility.ParseObjectFromXMLString(objItem.InnerItemXML, typeof(avatardata)) as avatardata;
                            //    if (data != null)
                            //    {
                            //        string strHash = XMPPClient.AvatarStorage.WriteAvatar(data.ImageData);
                            //        RosterItem item = XMPPClient.FindRosterItem(psem.From);
                            //        if (item != null)
                            //        {
                            //            item.AvatarImagePath = strHash;
                            //        }
                            //    }
                            //    /// Not sure why they would have more than 1 avatar item, so we'll ignore fom now
                            //    ///
                            //    break;
                            //}
                        }
                    }
                }
            }

            return(base.NewMessage(iq));
        }
コード例 #41
0
 public int IndexOf(RosterItem value)
 {
     return(List.IndexOf(value));
 }
コード例 #42
0
ファイル: XmppContact.cs プロジェクト: tshwangq/Hanoi
        /// <summary>
        ///   Updates the contact data.
        /// </summary>
        public void Update()
        {
            var iq = new IQ();
            var query = new RosterQuery();
            var item = new RosterItem();

            iq.Type = IQType.Set;

            item.Jid = ContactId.BareIdentifier;
            item.Name = DisplayName;
            item.Subscription = (RosterSubscriptionType)Subscription;

            item.Groups.AddRange(Groups);

            query.Items.Add(item);
            iq.Items.Add(query);

            session.Send(iq);
        }
コード例 #43
0
 void SafeOnNewIncomingFileTransferRequest(FileTransfer trans, RosterItem itemfrom)
 {
     this.ListBoxFileTransfers.ItemsSource = null;
     this.ListBoxFileTransfers.ItemsSource = App.XMPPClient.FileTransferManager.FileTransfers;
 }
コード例 #44
0
 public int Add(RosterItem value)
 {
     return(List.Add(value));
 }
コード例 #45
0
        private static RosterItem GetRosterItem(int NextId)
        {
            RosterItem returnValue = new RosterItem();

            //were only collecting 3 of the properties
            string FirstName = "";
            string LastName = "";
            string Gender = "";

            //create a validator with our new fluent validator class
            //take alook at the comments in the RosterItemValidator class
            RosterItemValidator validator = new RosterItemValidator();

            //start with the object as invalid
            bool IsValid = false;

            //this condition should always be triggered the first time through
            //then only triggered if a property is invalid
            while (!IsValid)
            {
                //this prevents a user having to re-enter valid values
                //if the field has an error we blank it out
                if (String.IsNullOrEmpty(FirstName))
                {
                    //get the first name
                    Console.WriteLine("Enter a FirstName: ");
                    FirstName = Console.ReadLine();
                }

                if (String.IsNullOrEmpty(LastName))
                {
                    //get the lastname
                    Console.WriteLine("Enter a LastName:");
                    LastName = Console.ReadLine();
                }

                if (String.IsNullOrEmpty(Gender))
                {
                    //get the gender
                    Console.WriteLine("Enter a Gender:");
                    Gender = Console.ReadLine();
                }

                //assign our values to the roster item
                returnValue = new RosterItem
                {
                    ID = NextId,
                    FirstName = FirstName,
                    LastName = LastName,
                    Gender = Gender
                };

                //check to see if the values are valid
                ValidationResult results = validator.Validate(returnValue);

                //set the variable for the loop
                IsValid = results.IsValid;

                //loop through all of the errors and display
                //an error message for each error
                foreach (var failure in results.Errors)
                {
                    //change the foreground color to red
                    Console.ForegroundColor = ConsoleColor.Red;

                    //display the error (blank line in front and behind)
                    Console.WriteLine("");
                    Console.WriteLine($"Property {failure.PropertyName} failed validation. \r\nError was: {failure.ErrorMessage}");
                    Console.WriteLine("");

                    //reset the console color
                    Console.ResetColor();

                    //blank out the bad value so it will be repeated to the user
                    switch (failure.PropertyName)
                    {
                        case "FirstName":
                            FirstName = "";
                            break;
                        case "LastName":
                            LastName = "";
                            break;
                        case "LastName.Length":
                            LastName = "";
                            break;
                        case "Gender":
                            Gender = "";
                            break;
                    }
                }
            }

            return returnValue;
        }
コード例 #46
0
 public void Remove(RosterItem value)
 {
     List.Remove(value);
 }
コード例 #47
0
ファイル: App.xaml.cs プロジェクト: Hitchhikrr/Voip
        //void DoOnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
        void XMPPClient_OnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
        {
            /// Save the conversation first
            ChatPage.SaveConversation(item);

            //Microsoft.Phone.PictureDecoder.DecodeJpeg(

            if (bReceived == true)
            {
                if (msg.Message != null)
                {
                    Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
                    toast.Title = msg.Message;
                    //toast.NavigationUri = new Uri(string.Format("/ChatPage.xaml?JID={0}", msg.From.BareJID));
                    toast.Show();

                    if (App.Options.PlaySoundOnNewMessage == true)
                    {

                        Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.Instance.Track = newmessagetrack;
                        Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.Instance.Play();

                        //System.IO.Stream stream = TitleContainer.OpenStream("sounds/ding.wav");
                        //SoundEffect effect = SoundEffect.FromStream(stream);
                        //FrameworkDispatcher.Update();
                        //effect.Play();
                        //stream.Close();
                    }
                    if (App.Options.VibrateOnNewMessage == true)
                        Microsoft.Devices.VibrateController.Default.Start(TimeSpan.FromMilliseconds(200));
                }
            }
        }
コード例 #48
0
ファイル: Program.cs プロジェクト: live0717/IoTGateway
        /// <summary>
        /// Analyzes the difference between the clock on the local machine with the clock on
        /// another machine, connected to the XMPP network, and compatible with the IEEE
        /// XMPP IoT extensions.
        ///
        /// Command line switches:
        ///
        /// -h HOST               XMPP Server host name.
        /// -p PORT               XMPP Port number, if different from 5222
        /// -a ACCOUNT            XMPP Account name to use when connecting to the server.
        /// -pwd PASSWORD         PASSWORD to use when authenticating with the server.
        /// -i INTERVAL           Interval (in milliseconds) used to check clocks.
        /// -j JID                JID of clock source to monitor.
        ///                       Default=5000.
        /// -r RECORDS            Number of measurements to collect.
        /// -n HISTORY            Number of records in history. Averages are calculated
        ///                       on records in this history. Default=100
        /// -w WINDOW             Filter window size. The window is used to detect
        ///                       and eliminate bad measurements. Default=16
        /// -s SPIKE_POS          Spike position. Where spikes are detected, in
        ///                       window. Default=6
        /// -sw SPIKE_WIDTH       Spike width. Number of measurements in a row that can
        ///                       constitute a spike. Default=3
        /// -o OUTPUT_FILE        File name of report file.
        /// -enc ENCODING         Text encoding. Default=UTF-8
        /// -t TRANSFORM_FILE     XSLT transform to use.
        /// -?                    Help.
        /// </summary>
        static int Main(string[] args)
        {
            try
            {
                Encoding Encoding       = Encoding.UTF8;
                string   OutputFileName = null;
                string   XsltPath       = null;
                string   Host           = null;
                string   Account        = null;
                string   Password       = null;
                string   Jid            = null;
                string   s;
                int      Port       = 5222;
                int      Records    = 0;
                int      Interval   = 5000;
                int      History    = 100;
                int      Window     = 16;
                int      SpikePos   = 6;
                int      SpikeWidth = 3;
                int      i          = 0;
                int      c          = args.Length;
                bool     Help       = false;

                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-o":
                        if (i >= c)
                        {
                            throw new Exception("Missing output file name.");
                        }

                        if (string.IsNullOrEmpty(OutputFileName))
                        {
                            OutputFileName = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one output file name allowed.");
                        }
                        break;

                    case "-h":
                        if (i >= c)
                        {
                            throw new Exception("Missing host name.");
                        }

                        if (string.IsNullOrEmpty(Host))
                        {
                            Host = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one host name allowed.");
                        }
                        break;

                    case "-p":
                        if (i >= c)
                        {
                            throw new Exception("Missing port number.");
                        }

                        if (!int.TryParse(args[i++], out Port) || Port <= 0 || Port > 65535)
                        {
                            throw new Exception("Invalid port number.");
                        }
                        break;

                    case "-j":
                        if (i >= c)
                        {
                            throw new Exception("Missing JID.");
                        }

                        if (string.IsNullOrEmpty(Jid))
                        {
                            Jid = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one JID allowed.");
                        }
                        break;

                    case "-i":
                        if (i >= c)
                        {
                            throw new Exception("Missing interval.");
                        }

                        if (!int.TryParse(args[i++], out Interval) || Interval < 1000)
                        {
                            throw new Exception("Invalid interval.");
                        }
                        break;

                    case "-r":
                        if (i >= c)
                        {
                            throw new Exception("Missing number of records to collect.");
                        }

                        if (!int.TryParse(args[i++], out Records) || Records <= 0)
                        {
                            throw new Exception("Invalid number of records to collect.");
                        }
                        break;

                    case "-n":
                        if (i >= c)
                        {
                            throw new Exception("Missing number of history records.");
                        }

                        if (!int.TryParse(args[i++], out History) || History <= 0)
                        {
                            throw new Exception("Invalid number of history records.");
                        }
                        break;

                    case "-w":
                        if (i >= c)
                        {
                            throw new Exception("Missing window size.");
                        }

                        if (!int.TryParse(args[i++], out Window) || Window <= 0)
                        {
                            throw new Exception("Invalid window size.");
                        }
                        break;

                    case "-s":
                        if (i >= c)
                        {
                            throw new Exception("Missing spike position.");
                        }

                        if (!int.TryParse(args[i++], out SpikePos) || SpikePos <= 0)
                        {
                            throw new Exception("Invalid spike position.");
                        }
                        break;

                    case "-sw":
                        if (i >= c)
                        {
                            throw new Exception("Missing spike width.");
                        }

                        if (!int.TryParse(args[i++], out SpikeWidth) || SpikeWidth <= 0)
                        {
                            throw new Exception("Invalid spike width.");
                        }
                        break;

                    case "-a":
                        if (i >= c)
                        {
                            throw new Exception("Missing account name.");
                        }

                        if (string.IsNullOrEmpty(Account))
                        {
                            Account = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one account name allowed.");
                        }
                        break;

                    case "-pwd":
                        if (i >= c)
                        {
                            throw new Exception("Missing password.");
                        }

                        if (string.IsNullOrEmpty(Password))
                        {
                            Password = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one password allowed.");
                        }
                        break;

                    case "-enc":
                        if (i >= c)
                        {
                            throw new Exception("Text encoding missing.");
                        }

                        Encoding = Encoding.GetEncoding(args[i++]);
                        break;

                    case "-t":
                        if (i >= c)
                        {
                            throw new Exception("XSLT transform missing.");
                        }

                        XsltPath = args[i++];
                        break;

                    case "-?":
                        Help = true;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Analyzes the difference between the clock on the local machine with the clock on");
                    Console.Out.WriteLine("another machine, connected to the XMPP network, and compatible with the IEEE");
                    Console.Out.WriteLine("XMPP IoT extensions.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-h HOST               XMPP Server host name.");
                    Console.Out.WriteLine("-p PORT               XMPP Port number, if different from 5222");
                    Console.Out.WriteLine("-a ACCOUNT            XMPP Account name to use when connecting to the server.");
                    Console.Out.WriteLine("-pwd PASSWORD         PASSWORD to use when authenticating with the server.");
                    Console.Out.WriteLine("-j JID                JID of clock source to monitor.");
                    Console.Out.WriteLine("-i INTERVAL           Interval (in milliseconds) used to check clocks.");
                    Console.Out.WriteLine("                      Default=5000.");
                    Console.Out.WriteLine("-r RECORDS            Number of measurements to collect.");
                    Console.Out.WriteLine("-n HISTORY            Number of records in history. Averages are calculated");
                    Console.Out.WriteLine("                      on records in this history. Default=100");
                    Console.Out.WriteLine("-w WINDOW             Filter window size. The window is used to detect");
                    Console.Out.WriteLine("                      and eliminate bad measurements. Default=16");
                    Console.Out.WriteLine("-s SPIKE_POS          Spike position. Where spikes are detected, in");
                    Console.Out.WriteLine("                      window. Default=6");
                    Console.Out.WriteLine("-sw SPIKE_WIDTH       Spike width. Number of measurements in a row that can");
                    Console.Out.WriteLine("                      constitute a spike. Default=3");
                    Console.Out.WriteLine("-o OUTPUT_FILE        File name of report file.");
                    Console.Out.WriteLine("-enc ENCODING         Text encoding. Default=UTF-8");
                    Console.Out.WriteLine("-t TRANSFORM_FILE     XSLT transform to use.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                if (string.IsNullOrEmpty(Host))
                {
                    throw new Exception("No host name specified.");
                }

                if (string.IsNullOrEmpty(Account))
                {
                    throw new Exception("No account name specified.");
                }

                if (string.IsNullOrEmpty(Password))
                {
                    throw new Exception("No password specified.");
                }

                if (string.IsNullOrEmpty(Jid))
                {
                    throw new Exception("No clock source JID specified.");
                }

                if (Records <= 0)
                {
                    throw new Exception("Number of records to collect not specified.");
                }

                if (string.IsNullOrEmpty(OutputFileName))
                {
                    throw new Exception("No output filename specified.");
                }

                XmppCredentials Credentials = new XmppCredentials()
                {
                    Host              = Host,
                    Port              = Port,
                    Account           = Account,
                    Password          = Password,
                    AllowCramMD5      = true,
                    AllowEncryption   = true,
                    AllowDigestMD5    = true,
                    AllowPlain        = true,
                    AllowScramSHA1    = true,
                    AllowScramSHA256  = true,
                    AllowRegistration = false
                };

                using (XmppClient Client = new XmppClient(Credentials, "en", typeof(Program).Assembly))
                {
                    ManualResetEvent Done  = new ManualResetEvent(false);
                    ManualResetEvent Error = new ManualResetEvent(false);

                    Client.OnStateChanged += (sender, NewState) =>
                    {
                        switch (NewState)
                        {
                        case XmppState.Connected:
                            Done.Set();
                            break;

                        case XmppState.Error:
                        case XmppState.Offline:
                            Error.Set();
                            break;
                        }
                    };

                    Client.Connect();

                    i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error });
                    if (i == 1)
                    {
                        throw new Exception("Unable to connect to broker.");
                    }

                    if (Jid.Contains("@") && !Jid.Contains("/"))
                    {
                        RosterItem Contact = Client.GetRosterItem(Jid);
                        if (Contact is null || (Contact.State != SubscriptionState.Both && Contact.State != SubscriptionState.To))
                        {
                            Done.Reset();

                            Client.OnPresenceSubscribed += (sender, e) =>
                            {
                                if (string.Compare(e.FromBareJID, Jid, true) == 0)
                                {
                                    Done.Set();
                                }
                            };

                            Client.OnPresenceUnsubscribed += (sender, e) =>
                            {
                                if (string.Compare(e.FromBareJID, Jid, true) == 0)
                                {
                                    Error.Set();
                                }
                            };

                            Console.WriteLine("Requesting presence subscription to " + Jid);

                            Client.RequestPresenceSubscription(Jid);

                            i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error });
                            if (i == 1)
                            {
                                throw new Exception("Unable to obtain presence subscription.");
                            }

                            Console.WriteLine("Presence subscription obtained.");
                        }
                    }

                    ManualResetEvent Done2 = new ManualResetEvent(false);

                    using (StreamWriter f = File.CreateText(OutputFileName))
                    {
                        XmlWriterSettings Settings = new XmlWriterSettings()
                        {
                            Encoding                = Encoding,
                            Indent                  = true,
                            IndentChars             = "\t",
                            NewLineChars            = Console.Out.NewLine,
                            OmitXmlDeclaration      = false,
                            WriteEndDocumentOnClose = true
                        };

                        using (XmlWriter w = XmlWriter.Create(f, Settings))
                        {
                            w.WriteStartDocument();

                            if (!string.IsNullOrEmpty(XsltPath))
                            {
                                w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + XML.Encode(XsltPath) + "\"");
                            }

                            w.WriteStartElement("ClockStatistics", "http://waher.se/Schema/Networking/ClockStatistics.xsd");

                            w.WriteStartElement("Parameters");
                            w.WriteAttributeString("clientJid", Client.BareJID);
                            w.WriteAttributeString("sourceJid", Jid);
                            w.WriteAttributeString("records", Records.ToString());
                            w.WriteAttributeString("interval", Interval.ToString());
                            w.WriteAttributeString("history", History.ToString());
                            w.WriteAttributeString("window", Window.ToString());
                            w.WriteAttributeString("spikePos", SpikePos.ToString());
                            w.WriteAttributeString("spikeWidth", SpikeWidth.ToString());
                            w.WriteAttributeString("hfFreq", System.Diagnostics.Stopwatch.Frequency.ToString());
                            w.WriteEndElement();

                            w.WriteStartElement("Samples");

                            using (SynchronizationClient SynchClient = new SynchronizationClient(Client))
                            {
                                SynchClient.OnUpdated += (sender, e) =>
                                {
                                    DateTime TP = DateTime.Now;
                                    double?  StdDev;

                                    w.WriteStartElement("Sample");
                                    w.WriteAttributeString("timestamp", XML.Encode(TP));

                                    if (SynchClient.RawLatency100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("rawLatencyMs", CommonTypes.Encode(SynchClient.RawLatency100Ns.Value * 1e-4));
                                    }

                                    if (SynchClient.LatencySpikeRemoved.HasValue)
                                    {
                                        w.WriteAttributeString("spikeLatencyRemoved", CommonTypes.Encode(SynchClient.LatencySpikeRemoved.Value));
                                    }

                                    if (SynchClient.RawClockDifference100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("rawDifferenceMs", CommonTypes.Encode(SynchClient.RawClockDifference100Ns.Value * 1e-4));
                                    }

                                    if (SynchClient.ClockDifferenceSpikeRemoved.HasValue)
                                    {
                                        w.WriteAttributeString("spikeDifferenceRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceSpikeRemoved.Value));
                                    }

                                    if (SynchClient.FilteredLatency100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("filteredLatencyMs", CommonTypes.Encode(SynchClient.FilteredLatency100Ns.Value * 1e-4));
                                    }

                                    if (SynchClient.FilteredClockDifference100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("filteredDifferenceMs", CommonTypes.Encode(SynchClient.FilteredClockDifference100Ns.Value * 1e-4));
                                    }

                                    if (SynchClient.AvgLatency100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("avgLatencyMs", CommonTypes.Encode(SynchClient.AvgLatency100Ns.Value * 1e-4));
                                    }

                                    if (SynchClient.AvgClockDifference100Ns.HasValue)
                                    {
                                        w.WriteAttributeString("avgDifferenceMs", CommonTypes.Encode(SynchClient.AvgClockDifference100Ns.Value * 1e-4));
                                    }

                                    StdDev = SynchClient.CalcStdDevLatency100Ns();
                                    if (StdDev.HasValue)
                                    {
                                        w.WriteAttributeString("stdDevLatencyMs", CommonTypes.Encode(StdDev.Value * 1e-4));
                                    }

                                    StdDev = SynchClient.CalcStdDevClockDifference100Ns();
                                    if (StdDev.HasValue)
                                    {
                                        w.WriteAttributeString("stdDevDifferenceMs", CommonTypes.Encode(StdDev.Value * 1e-4));
                                    }

                                    if (SynchClient.RawLatencyHf.HasValue)
                                    {
                                        w.WriteAttributeString("rawLatencyHf", SynchClient.RawLatencyHf.Value.ToString());
                                    }

                                    if (SynchClient.LatencyHfSpikeRemoved.HasValue)
                                    {
                                        w.WriteAttributeString("spikeLatencyHfRemoved", CommonTypes.Encode(SynchClient.LatencyHfSpikeRemoved.Value));
                                    }

                                    if (SynchClient.RawClockDifferenceHf.HasValue)
                                    {
                                        w.WriteAttributeString("rawDifferenceHf", SynchClient.RawClockDifferenceHf.Value.ToString());
                                    }

                                    if (SynchClient.ClockDifferenceHfSpikeRemoved.HasValue)
                                    {
                                        w.WriteAttributeString("spikeDifferenceHfRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceHfSpikeRemoved.Value));
                                    }

                                    if (SynchClient.FilteredLatencyHf.HasValue)
                                    {
                                        w.WriteAttributeString("filteredLatencyHf", SynchClient.FilteredLatencyHf.ToString());
                                    }

                                    if (SynchClient.FilteredClockDifferenceHf.HasValue)
                                    {
                                        w.WriteAttributeString("filteredDifferenceHf", SynchClient.FilteredClockDifferenceHf.ToString());
                                    }

                                    if (SynchClient.AvgLatencyHf.HasValue)
                                    {
                                        w.WriteAttributeString("avgLatencyHf", SynchClient.AvgLatencyHf.ToString());
                                    }

                                    if (SynchClient.AvgClockDifferenceHf.HasValue)
                                    {
                                        w.WriteAttributeString("avgDifferenceHf", SynchClient.AvgClockDifferenceHf.ToString());
                                    }

                                    StdDev = SynchClient.CalcStdDevLatencyHf();
                                    if (StdDev.HasValue)
                                    {
                                        w.WriteAttributeString("stdDevLatencyHf", CommonTypes.Encode(StdDev.Value));
                                    }

                                    StdDev = SynchClient.CalcStdDevClockDifferenceHf();
                                    if (StdDev.HasValue)
                                    {
                                        w.WriteAttributeString("stdDevDifferenceHf", CommonTypes.Encode(StdDev.Value));
                                    }

                                    w.WriteEndElement();

                                    Console.Out.Write(".");

                                    if (--Records <= 0)
                                    {
                                        Done2.Set();
                                    }
                                };

                                SynchClient.MonitorClockDifference(Jid, Interval, History, Window, SpikePos, SpikeWidth, true);

                                Done2.WaitOne();
                            }

                            w.WriteEndElement();
                            w.WriteEndElement();
                            w.WriteEndDocument();

                            w.Flush();

                            Console.Out.WriteLine();
                        }
                    }
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
        }
コード例 #49
0
 public ListViewRosterItem(RosterItem ri)
     : this()
 {
     _rosterItem = ri;
     buildSubItemsFromRosterItem();
 }
コード例 #50
0
        public static void Main(string[] args)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.White;

                Console.Out.WriteLine("Welcome to the Mock Temperature sensor application.");
                Console.Out.WriteLine(new string('-', 79));
                Console.Out.WriteLine("This application will simulate an outside temperature sensor.");
                Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions.");
                Console.Out.WriteLine("You can also chat with the sensor.");

                Log.Register(new ConsoleEventSink());
                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                              Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                              Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                              FormSignatureKey, FormSignatureSecret, typeof(Program).Assembly);

                using (XmppClient Client = xmppConfiguration.GetClient("en", typeof(Program).Assembly, false))
                {
                    Client.AllowRegistration(FormSignatureKey, FormSignatureSecret);

                    if (xmppConfiguration.Sniffer)
                    {
                        Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces));
                    }

                    if (!string.IsNullOrEmpty(xmppConfiguration.Events))
                    {
                        Log.Register(new XmppEventSink("XMPP Event Sink", Client, xmppConfiguration.Events, false));
                    }

                    if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry))
                    {
                        thingRegistryClient = new ThingRegistryClient(Client, xmppConfiguration.ThingRegistry);

                        thingRegistryClient.Claimed += (sender, e) =>
                        {
                            ownerJid = e.JID;
                            Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                        };

                        thingRegistryClient.Disowned += (sender, e) =>
                        {
                            Log.Informational("Thing has been disowned.", ownerJid);
                            ownerJid = string.Empty;
                            Register();
                        };

                        thingRegistryClient.Removed += (sender, e) =>
                        {
                            Log.Informational("Thing has been removed from the public registry.", ownerJid);
                        };
                    }

                    ProvisioningClient ProvisioningClient = null;
                    if (!string.IsNullOrEmpty(xmppConfiguration.Provisioning))
                    {
                        ProvisioningClient = new ProvisioningClient(Client, xmppConfiguration.Provisioning);
                    }

                    Timer ConnectionTimer = new Timer((P) =>
                    {
                        if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating)
                        {
                            try
                            {
                                Client.Reconnect();
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }
                    }, null, 60000, 60000);

                    bool Connected = false;
                    bool ImmediateReconnect;

                    Client.OnStateChanged += (sender, NewState) =>
                    {
                        switch (NewState)
                        {
                        case XmppState.Connected:
                            Connected = true;

                            if (!registered && thingRegistryClient != null)
                            {
                                Register();
                            }
                            break;

                        case XmppState.Offline:
                            ImmediateReconnect = Connected;
                            Connected          = false;

                            if (ImmediateReconnect)
                            {
                                Client.Reconnect();
                            }
                            break;
                        }
                    };

                    Client.OnPresenceSubscribe += (sender, e) =>
                    {
                        e.Accept();                             // TODO: Provisioning

                        RosterItem Item = Client.GetRosterItem(e.FromBareJID);
                        if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                        {
                            Client.RequestPresenceSubscription(e.FromBareJID);
                        }

                        Client.SetPresence(Availability.Chat);
                    };

                    Client.OnPresenceUnsubscribe += (sender, e) =>
                    {
                        e.Accept();
                    };

                    Client.OnRosterItemUpdated += (sender, e) =>
                    {
                        if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                        {
                            Client.RemoveRosterItem(e.BareJid);
                        }
                    };

                    LinkedList <DayHistoryRecord>    DayHistoricalValues    = new LinkedList <DayHistoryRecord>();
                    LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>();
                    DateTime SampleTime  = DateTime.Now;
                    DateTime PeriodStart = SampleTime.Date;
                    DateTime Now;
                    DateTime MinTime            = SampleTime;
                    DateTime MaxTime            = SampleTime;
                    double   CurrentTemperature = ReadTemp();
                    double   MinTemp            = CurrentTemperature;
                    double   MaxTemp            = CurrentTemperature;
                    double   SumTemp            = CurrentTemperature;
                    int      NrTemp             = 1;
                    int      NrDayRecords       = 0;
                    int      NrMinuteRecords    = 0;
                    object   SampleSynch        = new object();

                    SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, true);
                    SensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                    {
                        Log.Informational("Readout requested", string.Empty, Request.Actor);

                        List <Field> Fields          = new List <Field>();
                        bool         IncludeTemp     = Request.IsIncluded("Temperature");
                        bool         IncludeTempMin  = Request.IsIncluded("Temperature, Min");
                        bool         IncludeTempMax  = Request.IsIncluded("Temperature, Max");
                        bool         IncludeTempAvg  = Request.IsIncluded("Temperature, Average");
                        bool         IncludePeak     = Request.IsIncluded(FieldType.Peak);
                        bool         IncludeComputed = Request.IsIncluded(FieldType.Computed);

                        lock (SampleSynch)
                        {
                            if (IncludeTemp && Request.IsIncluded(FieldType.Momentary))
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C",
                                                             FieldType.Momentary, FieldQoS.AutomaticReadout));
                            }

                            if (IncludePeak)
                            {
                                if (IncludeTempMin)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C",
                                                                 FieldType.Peak, FieldQoS.AutomaticReadout));
                                }

                                if (IncludeTempMax)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C",
                                                                 FieldType.Peak, FieldQoS.AutomaticReadout));
                                }
                            }

                            if (IncludeTempAvg && IncludeComputed)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C",
                                                             FieldType.Computed, FieldQoS.AutomaticReadout));
                            }

                            if (Request.IsIncluded(FieldType.Historical))
                            {
                                foreach (DayHistoryRecord Rec in DayHistoricalValues)
                                {
                                    if (!Request.IsIncluded(Rec.PeriodStart))
                                    {
                                        continue;
                                    }

                                    if (Fields.Count >= 100)
                                    {
                                        Request.ReportFields(false, Fields);
                                        Fields.Clear();
                                    }

                                    if (IncludePeak)
                                    {
                                        if (IncludeTempMin)
                                        {
                                            Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C",
                                                                         FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                        }

                                        if (IncludeTempMax)
                                        {
                                            Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C",
                                                                         FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                        }
                                    }

                                    if (IncludeTempAvg && IncludeComputed)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C",
                                                                     FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }

                                foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues)
                                {
                                    if (!Request.IsIncluded(Rec.Timestamp))
                                    {
                                        continue;
                                    }

                                    if (IncludeTemp)
                                    {
                                        if (Fields.Count >= 100)
                                        {
                                            Request.ReportFields(false, Fields);
                                            Fields.Clear();
                                        }

                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C",
                                                                     FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }
                            }
                        }

                        Request.ReportFields(true, Fields);
                    };

                    Timer SampleTimer = new Timer((P) =>
                    {
                        lock (SampleSynch)
                        {
                            Now = DateTime.Now;

                            if (Now.Date != PeriodStart.Date)
                            {
                                DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1),
                                                                            MinTemp, MaxTemp, SumTemp / NrTemp);

                                DayHistoricalValues.AddFirst(Rec);

                                if (NrDayRecords < MaxRecordsPerPeriod)
                                {
                                    NrDayRecords++;
                                }
                                else
                                {
                                    DayHistoricalValues.RemoveLast();
                                }

                                // TODO: Persistence

                                PeriodStart = Now.Date;
                                SumTemp     = 0;
                                NrTemp      = 0;
                            }

                            CurrentTemperature = ReadTemp();

                            if (Now.Minute != SampleTime.Minute)
                            {
                                MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature);

                                MinuteHistoricalValues.AddFirst(Rec);

                                if (NrMinuteRecords < MaxRecordsPerPeriod)
                                {
                                    NrMinuteRecords++;
                                }
                                else
                                {
                                    MinuteHistoricalValues.RemoveLast();
                                }

                                // TODO: Persistence
                            }

                            SampleTime = Now;

                            if (CurrentTemperature < MinTemp)
                            {
                                MinTemp = CurrentTemperature;
                                MinTime = SampleTime;
                            }

                            if (CurrentTemperature > MaxTemp)
                            {
                                MaxTemp = CurrentTemperature;
                                MaxTime = SampleTime;
                            }

                            SumTemp += CurrentTemperature;
                            NrTemp++;
                        }

                        if (SensorServer.HasSubscriptions(ThingReference.Empty))
                        {
                            SensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature",
                                                                              CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout));
                        }
                    }, null, 1000 - PeriodStart.Millisecond, 1000);

                    BobClient  BobClient  = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                    ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer);

                    InteroperabilityServer InteroperabilityServer = new InteroperabilityServer(Client);
                    InteroperabilityServer.OnGetInterfaces += (sender, e) =>
                    {
                        e.Add("XMPP.IoT.Sensor.Temperature",
                              "XMPP.IoT.Sensor.Temperature.History",
                              "XMPP.IoT.Sensor.Temperature.Average",
                              "XMPP.IoT.Sensor.Temperature.Average.History",
                              "XMPP.IoT.Sensor.Temperature.Min",
                              "XMPP.IoT.Sensor.Temperature.Min.History",
                              "XMPP.IoT.Sensor.Temperature.Max",
                              "XMPP.IoT.Sensor.Temperature.Max.History");
                    };

                    Client.Connect();

                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Out.WriteLine(ex.Message);
            }
            finally
            {
                Log.Terminate();
            }
        }
コード例 #51
0
        public static void SaveConversation(RosterItem item)
        {
            /// Save this conversation so it can be restored later... save it under the JID name

            string strFilename = string.Format("{0}_conversation.item", item.JID.BareJID);

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                // Load from storage
                IsolatedStorageFileStream location = new IsolatedStorageFileStream(strFilename, System.IO.FileMode.Create, storage);
                DataContractSerializer ser = new DataContractSerializer(typeof(System.Net.XMPP.Conversation));

                try
                {
                    ser.WriteObject(location, item.Conversation);
                }
                catch (Exception)
                {
                }
                location.Close();
            }
        }
コード例 #52
0
 public bool Contains(RosterItem value)
 {
     return (List.Contains(value));
 }
コード例 #53
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string strJID = NavigationContext.QueryString["JID"];

            bool bQuery = false;
            try
            {
                if (NavigationContext.QueryString["Refresh"] != null)
                    bQuery = true;
            }
            catch (Exception)
            {
            }

            this.VoiceCall.RegisterXMPPClient();

            OurRosterItem = App.XMPPClient.FindRosterItem(new JID(strJID));

            if (this.InFileTransferMode == true)
            {
                this.NavigationService.Navigate(new Uri("/FileTransferPage.xaml", UriKind.Relative));
                this.InFileTransferMode = false;
            }

            if ((OurRosterItem == null) || (App.XMPPClient.XMPPState != XMPPState.Ready))
            {

                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                return;
            }

            if (bQuery == true)
                NavigationService.RemoveBackEntry();

            /// See if we have this conversation in storage if there are no messages
            if (OurRosterItem.Conversation.Messages.Count <= 0)
            {

                string strFilename = string.Format("{0}_conversation.item", OurRosterItem.JID.BareJID);

                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {

                    if (storage.FileExists(strFilename) == true)
                    {
                        // Load from storage
                        IsolatedStorageFileStream location = null;
                        try
                        {
                            location = new IsolatedStorageFileStream(strFilename, System.IO.FileMode.Open, storage);
                            if (location.Length > 0)
                            {
                                DataContractSerializer ser = new DataContractSerializer(typeof(System.Net.XMPP.Conversation));
                                OurRosterItem.Conversation = ser.ReadObject(location) as System.Net.XMPP.Conversation;
                            }
                        }
                        catch (Exception)
                        {
                        }
                        finally
                        {
                            if (location != null)
                                location.Close();
                        }
                    }

                }

            }

            OurRosterItem.HasNewMessages = false; /// We just viewed new messages
            ///

            this.DataContext = OurRosterItem;
            this.TextBlockConversationTitle.Text = OurRosterItem.Name;
            this.TextBlockConversationTitle.LayoutUpdated += ScrollRichTextBoxToBottom;

            if (this.TextBlockChat.Blocks.Count <= 0)
                TextBlockChat.Blocks.Add(MainParagraph);

            SetConversation();

            App.XMPPClient.OnNewConversationItem += new System.Net.XMPP.XMPPClient.DelegateNewConversationItem(XMPPClient_OnNewConversationItem);
        }
コード例 #54
0
 public void Remove(RosterItem value)
 {
     List.Remove(value);
 }
コード例 #55
0
        void DoOnNewConversationItem(RosterItem item, bool bReceived, TextMessage msg)
        {
            if (item.JID.BareJID == OurRosterItem.JID.BareJID)
            {
                /// Clear our new message flag for this roster user as long as this window is open
                item.HasNewMessages = false;

                AddInlinesForMessage(msg);

                this.TextBlockChat.Focus();

                //TextPointer myTextPointer1 = MainParagraph.ContentStart.GetPositionAtOffset(20);
                //TextPointer myTextPointer1 = MainParagraph.ContentEnd.GetPositionAtOffset(0, LogicalDirection.Backward);
                //TextPointer myTextPointer2 = MainParagraph.ContentEnd.GetPositionAtOffset(0, LogicalDirection.Backward);
                this.TextBlockChat.Selection.Select(this.TextBlockChat.ContentEnd, this.TextBlockChat.ContentEnd);

                ScrollChat.ScrollToVerticalOffset(this.TextBlockChat.ActualHeight + 100);
                //this.ListBoxConversation.UpdateLayout();
                //if (this.ListBoxConversation.Items.Count > 0)
                //   this.ListBoxConversation.ScrollIntoView(this.ListBoxConversation.Items[this.ListBoxConversation.Items.Count - 1]);

            }
        }
コード例 #56
0
        private async void StartSensor()
        {
            try
            {
                Log.Informational("Starting application.");

                XmppCredentials Credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                                        typeof(App).GetTypeInfo().Assembly);

                Log.Informational("Connecting to XMPP server.");

                xmppClient = new XmppClient(Credentials, "en", typeof(App).GetTypeInfo().Assembly);

                if (Credentials.Sniffer && MainPage.Sniffer != null)
                {
                    xmppClient.Add(MainPage.Sniffer);
                }

                if (!string.IsNullOrEmpty(Credentials.Events))
                {
                    Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, Credentials.Events, false));
                }

                if (!string.IsNullOrEmpty(Credentials.ThingRegistry))
                {
                    thingRegistryClient = new ThingRegistryClient(xmppClient, Credentials.ThingRegistry);

                    thingRegistryClient.Claimed += (sender, e) =>
                    {
                        ownerJid = e.JID;
                        Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                        this.RaiseOwnershipChanged();
                    };

                    thingRegistryClient.Disowned += (sender, e) =>
                    {
                        Log.Informational("Thing has been disowned.", ownerJid);
                        ownerJid = string.Empty;
                        this.Register();                            // Will call this.OwnershipChanged() after successful registration.
                    };

                    thingRegistryClient.Removed += (sender, e) =>
                    {
                        Log.Informational("Thing has been removed from the public registry.", ownerJid);
                    };
                }

                if (!string.IsNullOrEmpty(Credentials.Provisioning))
                {
                    provisioningClient = new ProvisioningClient(xmppClient, Credentials.Provisioning);
                }

                Timer ConnectionTimer = new Timer((P) =>
                {
                    if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating)
                    {
                        try
                        {
                            Log.Informational("Reconnecting.");
                            xmppClient.Reconnect();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }
                }, null, 60000, 60000);

                xmppClient.OnStateChanged += (sender, NewState) =>
                {
                    Log.Informational(NewState.ToString());

                    switch (NewState)
                    {
                    case XmppState.Connected:
                        connected = true;

                        if (!registered && thingRegistryClient != null)
                        {
                            this.Register();
                        }
                        break;

                    case XmppState.Offline:
                        immediateReconnect = connected;
                        connected          = false;

                        if (immediateReconnect)
                        {
                            xmppClient.Reconnect();
                        }
                        break;
                    }
                };

                xmppClient.OnPresenceSubscribe += (sender, e) =>
                {
                    Log.Informational("Subscription request received from " + e.From + ".");

                    e.Accept();                         // TODO: Provisioning

                    RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID);
                    if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                    {
                        xmppClient.RequestPresenceSubscription(e.FromBareJID);
                    }

                    xmppClient.SetPresence(Availability.Chat);
                };

                xmppClient.OnPresenceUnsubscribe += (sender, e) =>
                {
                    Log.Informational("Unsubscription request received from " + e.From + ".");
                    e.Accept();
                };

                xmppClient.OnRosterItemUpdated += (sender, e) =>
                {
                    if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                    {
                        xmppClient.RemoveRosterItem(e.BareJid);
                    }
                };

                LinkedList <DayHistoryRecord>    DayHistoricalValues    = new LinkedList <DayHistoryRecord>();
                LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>();
                DateTime SampleTime  = DateTime.Now;
                DateTime PeriodStart = SampleTime.Date;
                DateTime Now;
                DateTime MinTime            = SampleTime;
                DateTime MaxTime            = SampleTime;
                double   CurrentTemperature = this.ReadTemp();
                double   MinTemp            = CurrentTemperature;
                double   MaxTemp            = CurrentTemperature;
                double   SumTemp            = CurrentTemperature;
                int      NrTemp             = 1;
                int      NrDayRecords       = 0;
                int      NrMinuteRecords    = 0;
                object   SampleSynch        = new object();

                this.sampleTimer = new Timer((P) =>
                {
                    lock (SampleSynch)
                    {
                        Now = DateTime.Now;

                        if (Now.Date != PeriodStart.Date)
                        {
                            DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1),
                                                                        MinTemp, MaxTemp, SumTemp / NrTemp);

                            DayHistoricalValues.AddFirst(Rec);

                            if (NrDayRecords < MaxRecordsPerPeriod)
                            {
                                NrDayRecords++;
                            }
                            else
                            {
                                DayHistoricalValues.RemoveLast();
                            }

                            // TODO: Persistence

                            PeriodStart = Now.Date;
                            SumTemp     = 0;
                            NrTemp      = 0;
                        }

                        CurrentTemperature = this.ReadTemp();

                        if (Now.Minute != SampleTime.Minute)
                        {
                            MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature);

                            MinuteHistoricalValues.AddFirst(Rec);

                            if (NrMinuteRecords < MaxRecordsPerPeriod)
                            {
                                NrMinuteRecords++;
                            }
                            else
                            {
                                MinuteHistoricalValues.RemoveLast();
                            }

                            // TODO: Persistence
                        }

                        SampleTime = Now;

                        if (CurrentTemperature < MinTemp)
                        {
                            MinTemp = CurrentTemperature;
                            MinTime = SampleTime;
                        }

                        if (CurrentTemperature > MaxTemp)
                        {
                            MaxTemp = CurrentTemperature;
                            MaxTime = SampleTime;
                        }

                        SumTemp += CurrentTemperature;
                        NrTemp++;
                    }

                    if (this.sensorServer.HasSubscriptions(ThingReference.Empty))
                    {
                        this.sensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature",
                                                                               CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout));
                    }

                    this.UpdateMainWindow(CurrentTemperature, MinTemp, MaxTemp, SumTemp / NrTemp);
                }, null, 1000 - PeriodStart.Millisecond, 1000);

                this.sensorServer = new SensorServer(xmppClient, provisioningClient, true);
                this.sensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                {
                    Log.Informational("Readout requested by " + Request.From, string.Empty, Request.Actor);

                    List <Field> Fields          = new List <Field>();
                    bool         IncludeTemp     = Request.IsIncluded("Temperature");
                    bool         IncludeTempMin  = Request.IsIncluded("Temperature, Min");
                    bool         IncludeTempMax  = Request.IsIncluded("Temperature, Max");
                    bool         IncludeTempAvg  = Request.IsIncluded("Temperature, Average");
                    bool         IncludePeak     = Request.IsIncluded(FieldType.Peak);
                    bool         IncludeComputed = Request.IsIncluded(FieldType.Computed);

                    lock (SampleSynch)
                    {
                        if (IncludeTemp && Request.IsIncluded(FieldType.Momentary))
                        {
                            Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C",
                                                         FieldType.Momentary, FieldQoS.AutomaticReadout));
                        }

                        if (IncludePeak)
                        {
                            if (IncludeTempMin)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C",
                                                             FieldType.Peak, FieldQoS.AutomaticReadout));
                            }

                            if (IncludeTempMax)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C",
                                                             FieldType.Peak, FieldQoS.AutomaticReadout));
                            }
                        }

                        if (IncludeTempAvg && IncludeComputed)
                        {
                            Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C",
                                                         FieldType.Computed, FieldQoS.AutomaticReadout));
                        }

                        if (Request.IsIncluded(FieldType.Historical))
                        {
                            foreach (DayHistoryRecord Rec in DayHistoricalValues)
                            {
                                if (!Request.IsIncluded(Rec.PeriodStart))
                                {
                                    continue;
                                }

                                if (Fields.Count >= 100)
                                {
                                    Request.ReportFields(false, Fields);
                                    Fields.Clear();
                                }

                                if (IncludePeak)
                                {
                                    if (IncludeTempMin)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C",
                                                                     FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }

                                    if (IncludeTempMax)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C",
                                                                     FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }

                                if (IncludeTempAvg && IncludeComputed)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C",
                                                                 FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout));
                                }
                            }

                            foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues)
                            {
                                if (!Request.IsIncluded(Rec.Timestamp))
                                {
                                    continue;
                                }

                                if (IncludeTemp)
                                {
                                    if (Fields.Count >= 100)
                                    {
                                        Request.ReportFields(false, Fields);
                                        Fields.Clear();
                                    }

                                    Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C",
                                                                 FieldType.Historical, FieldQoS.AutomaticReadout));
                                }
                            }
                        }
                    }

                    Request.ReportFields(true, Fields);
                };

                this.bobClient  = new BobClient(this.xmppClient, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                this.chatServer = new ChatServer(this.xmppClient, this.bobClient, this.sensorServer, this.provisioningClient);

                this.interoperabilityServer = new InteroperabilityServer(xmppClient);
                this.interoperabilityServer.OnGetInterfaces += (sender, e) =>
                {
                    e.Add("XMPP.IoT.Sensor.Temperature",
                          "XMPP.IoT.Sensor.Temperature.History",
                          "XMPP.IoT.Sensor.Temperature.Average",
                          "XMPP.IoT.Sensor.Temperature.Average.History",
                          "XMPP.IoT.Sensor.Temperature.Min",
                          "XMPP.IoT.Sensor.Temperature.Min.History",
                          "XMPP.IoT.Sensor.Temperature.Max",
                          "XMPP.IoT.Sensor.Temperature.Max.History");
                };

                xmppClient.Connect();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await Dialog.ShowAsync();
            }
        }
コード例 #57
0
ファイル: RosterLogic.cs プロジェクト: Hitchhikrr/Voip
        public override bool NewIQ(IQ iq)
        {
            if (!(iq is RosterIQ))
                return false;

            RosterIQ rostiq = iq as RosterIQ;

            if (iq.ID == RosterIQ.ID)
            {
                //<iq type="result" id="aab8a" to="[email protected]/hypnotoad">
                   //<query xmlns="jabber:iq:roster">
                       ///<item jid="*****@*****.**" name="BrianBonnett" subscription="both">
                       ///    <group>Friends</group>
                       ///</item>
                   ///</query>
                ///</iq>
                ///

                this.Success = false;
                if (iq.Type == IQType.result.ToString())
                {
                    if ( (rostiq.Query != null) && (rostiq.Query.RosterItems != null) )
                    {
                        foreach (rosteritem item in rostiq.Query.RosterItems)
                        {
                            RosterItem ros = new RosterItem(XMPPClient, item.JID);

                            if (item.Ask == "subscribe")
                            {
                                /// Need to do subscribe to this user's presence some how
                                ///
                            }

                            /// See if we already have this roster item
                            ///
                            RosterItem existingitem = XMPPClient.FindRosterItem(ros.JID);
                            if (existingitem != null)
                            {
                                existingitem.Name = (item.Name != null) ? item.Name : ros.JID.BareJID;
                                existingitem.Subscription = (item.Subscription != null) ? item.Subscription : "";
                                existingitem.Node = item;
                                existingitem.Groups.Clear();
                                /// Get the group for this item
                                if (item.Groups != null)
                                {
                                    foreach (string strGroup in item.Groups)
                                    {
                                        ros.Group = strGroup;
                                        ros.Groups.Add(strGroup);
                                    }
                                }
                            }
                            else
                            {
                                ros.Name = (item.Name != null) ? item.Name : ros.JID.BareJID;
                                ros.Subscription = (item.Subscription != null) ? item.Subscription : "";
                                ros.Node = item;
                                XMPPClient.RosterItems.Add(ros);
                                /// Get the group for this item
                                if (item.Groups != null)
                                {
                                    foreach (string strGroup in item.Groups)
                                    {
                                        ros.Group = strGroup;
                                        if (ros.Groups.Contains(strGroup) == false)
                                            ros.Groups.Add(strGroup);
                                    }
                                }
                            }
                        }

                    }

                    this.Success = true;
                    XMPPClient.FireGotRoster();
                }

                this.IsCompleted = false;

                return true;
            }
            else if (iq.Type == "set")
            {
                //<iq type="set" id="640-356" to="[email protected]/phone"><query xmlns="jabber:iq:roster"><item jid="*****@*****.**" ask="subscribe" subscription="from"/></query></iq>

                if ( (rostiq.Query != null) && (rostiq.Query.RosterItems != null) )
                {
                    foreach (rosteritem item in rostiq.Query.RosterItems)
                    {
                        RosterItem ros = new RosterItem(XMPPClient, item.JID)
                        {
                            XMPPClient = XMPPClient,
                            Name = item.Name,
                            Subscription = item.Subscription,
                            Node = item,
                        };

                        if (XMPPClient.FindRosterItem(ros.JID) == null)
                        {

                            XMPPClient.RosterItems.Add(ros);

                            if (item.Groups != null)
                            {
                                foreach (string strGroup in item.Groups)
                                {
                                    ros.Group = strGroup;
                                    if (ros.Groups.Contains(strGroup) == false)
                                        ros.Groups.Add(strGroup);
                                }
                            }

                            XMPPClient.AsyncFireListChanged();
                        }

                        if (item.Subscription == subscription.from.ToString())  /// should only have a from subscription if we've added the roster item
                        {
                            //if (XMPPClient.AutoAcceptPresenceSubscribe
                            /// subscribe to presence of this one
                            XMPPClient.PresenceLogic.SubscribeToPresence(ros.JID.BareJID);
                        }

                    }

                    iq.Type = IQType.result.ToString();
                    iq.To = iq.From;
                    iq.From = XMPPClient.JID;
                    iq.InnerXML = null;
                    XMPPClient.SendXMPP(iq);

                    this.Success = true;
                    return true;
                }

            }

            return false;
        }