public void receiveAndSendHello(RingInfo ringInfo, Peer peer, Neighbor neighbor, 
            BinaryWriter writer)
        {
            if(!peer.node.syncCommunicationPoint.Address.Equals(neighbor.peer.node.syncCommunicationPoint.Address))
                //REVISIT: alert security system
                return;

            neighbor.peer.node.syncCommunicationPoint = peer.node.syncCommunicationPoint;
            neighbor.peer.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint;
            neighbor.peer.IE = peer.IE;

            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream;

            try
            {
                User user = User.getInstance();
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO);
                serializer.Serialize(stream, ringInfo.ring.ringID);
                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE));
                writer.Write(message);
                writer.Flush();
            }
            catch (Exception e)
            {
                int x = 2;
            }
        }
        public void sendAndReceiveHello(Peer neighbor, Ring ring)
        {
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            byte[] reply = new byte[Constants.READBUFFSIZE];
            MemoryStream stream;

            try
            {
                User user = User.getInstance();
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                RingInfo ringInfo = user.findRingInfo(ring.ringID);
                serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO);
                serializer.Serialize(stream, ring.ringID);
                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE));

                reply = NetLib.communicate(neighbor.node.syncCommunicationPoint, message, true);

                Debug.Assert(reply != null, "Neighbor did not reply to Hello");

                BinaryFormatter deserializer = new BinaryFormatter();
                stream = new MemoryStream(reply);
                NetLib.bypassEntropyHeader(deserializer, stream);
                Constants.MessageTypes replyMsg = (Constants.MessageTypes)deserializer.Deserialize(stream);
                switch(replyMsg)
                {
                    case Constants.MessageTypes.MSG_HELLO:
                        uint ringID = (uint)deserializer.Deserialize(stream);
                        if(ringID != ring.ringID)
                            return;

                        ulong token = (ulong)deserializer.Deserialize(stream);
                        Peer peer = (Peer)deserializer.Deserialize(stream);

                        IPEndPoint neighborIPEndPoint = peer.node.syncCommunicationPoint;
                        if(!neighborIPEndPoint.Address.Equals(neighbor.node.syncCommunicationPoint.Address))
                            //REVISIT: alert security system
                            return;

                        neighbor.node.syncCommunicationPoint = neighborIPEndPoint;
                        neighbor.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint;
                        neighbor.IE = peer.IE;
                        break;
                    case Constants.MessageTypes.MSG_DISCONNECT:
                        neighbor.IE = null;
                        break;
                    default:
                        neighbor.IE = null;
                        break;
                }
            }
            catch (Exception e)
            {
                int x = 2;
            }
        }
 public Download(Peer __peer, RingInfo __ringInfo, ResourceHeader __header, 
     UICallBack __UIHandler)
 {
     peer = __peer;
     ringInfo = __ringInfo;
     header = __header;
     //REVISIT: make sure there is enough room for meta data. Also if very large you want to split up into a list of
     //buffers or circular buffer where the buffer is written to temp file at milestones.
     buffer = new byte[header.size];
     bytesRead = 0;
     UIHandler = __UIHandler;
 }
 public bool Download(Peer peer, RingInfo ringInfo, ResourceHeader resourceHeader, 
     UICallBack UIHndlr)
 {
     Download download = new Download(peer, ringInfo, resourceHeader, UIHndlr);
     int downloadIndex = Add(download);
     if (downloadIndex < 0)
     {
         Queue(download);
         return false;
     }
     Download_Internal(download);
     return true;
 }
        public void addPeer(Peer newPeer)
        {
            RRLib.SortedList peers;

            foreach (InformationEntropy IE in newPeer.IE)
            {
                peers = (RRLib.SortedList)contentIndex.getInvertedList(IE.keyword);
                if (peers == null)
                {
                    peers = new RRLib.SortedList();
                    contentIndex.add(IE.keyword, peers);
                }

                peers.Add(new WeightedPeer(IE.weight, newPeer));
            }
        }
        public Peer[] getAdjacentPeers(Peer peer, int IEConsiderationLength, int peersConsiderationLength, int maxPeers)
        {
            int IEcount = 0, peerCount, matchIndex = 0;
            WeightedPeer[] matches = new WeightedPeer[IEConsiderationLength * peersConsiderationLength];
            RRLib.SortedList peers;
            IEnumerator peersWalker;
            Peer match;

            foreach (InformationEntropy IE in peer.IE)
            {
                if (++IEcount == IEConsiderationLength)
                    break;
                peers = (RRLib.SortedList)contentIndex.getInvertedList(IE.keyword);
                if (peers == null)
                    continue;
                peersWalker = peers.GetEnumerator();
                peerCount = 0;

                while(peersWalker.MoveNext() && peerCount++ < peersConsiderationLength)
                {
                    if(((WeightedPeer)peersWalker.Current).peer.token == peer.token)
                        continue;
                    matches[matchIndex++] = (WeightedPeer)peersWalker.Current;
                }
            }

            Array.Sort(matches, 0, matchIndex);

            Peer[] peerMatches = new Peer[matchIndex > maxPeers ? maxPeers : matchIndex];

            for (matchIndex = 0; matchIndex < peerMatches.Length; matchIndex++)
            {
                peerMatches[matchIndex] = matches[matchIndex].peer;
            }

            return peerMatches;
        }
        public Constants.LoginStatus logon(User user)
        {
            Constants.LoginStatus retval = Constants.LoginStatus.STATUS_SERVERNOTREACHED;
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            byte[] reply;
            MemoryStream stream = null;

            try
            {
                //Serialize data in memory so you can send them as a continuous stream
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);
                NetLib.insertEntropyHeader(serializer, stream);

                serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGIN);
                serializer.Serialize(stream, user.ringsInfo[0].userName);
                serializer.Serialize(stream, user.ringsInfo[0].password);
                serializer.Serialize(stream, user.node);
                reply = NetLib.communicate(Constants.SERVER,message, true);
                stream.Close();
                stream = new MemoryStream(reply);
                Constants.MessageTypes replyMsg = (Constants.MessageTypes)serializer.Deserialize(stream);

                switch(replyMsg)
                {
                    case Constants.MessageTypes.MSG_OK:
                        retval = Constants.LoginStatus.STATUS_LOGGEDIN;
                        ulong sessionID = (ulong)serializer.Deserialize(stream);
                        int numAdjPeers = (int)serializer.Deserialize(stream);
                        Peer[] adjPeers = null;
                        if(numAdjPeers > 0)
                        {
                            adjPeers = new Peer[numAdjPeers];
                            adjPeers = (Peer[])serializer.Deserialize(stream);
                        }

                        //add the adjacent peers reported to our list (callback to Client)
                        this.loginCallbackTable.addAdjacentPeers(adjPeers);
                        loggedIn = true;

                        //set the session ID (callback to ServerProxy)
                        this.loginCallbackTable.setSessionID(sessionID);
                        break;
                    case Constants.MessageTypes.MSG_NOTAMEMBER:
                        retval = Constants.LoginStatus.STATUS_NOTAMEMBER;
                        break;
                    case Constants.MessageTypes.MSG_ALREADYSIGNEDIN:
                        retval = Constants.LoginStatus.STATUS_ALREADYSIGNEDIN;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {

                int x = 2;
            }

            return retval;
        }
        public void sendQuery(Peer neighbor, RingInfo ringInfo, string[] columns, string[] query, 
            Node sender, int ttl)
        {
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream;

            if (ttl <= 0)
                return;

            try
            {
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                if (columns == null)
                    serializer.Serialize(stream, Constants.MessageTypes.MSG_SIMPLEQUERY);
                else
                    serializer.Serialize(stream, Constants.MessageTypes.MSG_COLUMNQUERY);

                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, ringInfo.ring.ringID);
                serializer.Serialize(stream, sender.asyncCommunicationPoint);
                serializer.Serialize(stream, ttl);  //TTL
                if (columns == null)
                    serializer.Serialize(stream, Constants.NULL_STRING_ARRAY);
                else
                    serializer.Serialize(stream, columns);
                serializer.Serialize(stream, query);

                NetLib.communicateAsync(neighbor.node.asyncCommunicationPoint, message, false);
            }
            catch (Exception e)
            {
                int x = 2;  //REVISIT: probably need to send info to logger.
            }
        }
        private void processClientRingLogin(BinaryReader clientReader, BinaryWriter clientWriter)
        {
            //deserialize the message
            BinaryFormatter deserializer = new BinaryFormatter();
            uint ringID = (uint)deserializer.Deserialize(clientReader.BaseStream);
            string userName = (string)deserializer.Deserialize(clientReader.BaseStream);
            byte[] password = (byte[])deserializer.Deserialize(clientReader.BaseStream);
            IPEndPoint commPoint = (IPEndPoint)deserializer.Deserialize(clientReader.BaseStream);
            InformationEntropy[] IE = (InformationEntropy[])deserializer.Deserialize(clientReader.BaseStream);

            ServerRingInfo serverRingInfo = ServerRingInfo.findServerRingInfoByID(this.serverRingsInfo, ringID);
            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream = new MemoryStream(message);
            BinaryFormatter serializer = deserializer; //reuse the object
            Member member = null;

            NetLib.insertEntropyHeader(serializer, stream);

            //not a member need to signup first, goodbye =)
            if((member = accountsManager.findMemberByUserName(userName)) == null)
            {
                deserializer.Serialize(stream, Constants.MessageTypes.MSG_NOTAMEMBER);
                clientWriter.Write(message);
                clientWriter.Flush();
                return;
            }

            ClientSession session;
            ulong sessionID;
            Peer memberAsPeer = new Peer(member.node, member.publicUserInfo, IE);

            //get users current node settings
            member.node.syncCommunicationPoint = commPoint;

            //Already on the network from the requesting device (are you a hacker?)
            if((session = serverRingInfo.ringClientManager.findClientSession(member)) == null)
            {
                //get a session ID add the user to the client manager database
                sessionID = serverRingInfo.getNextSessionID();

                serverRingInfo.ringClientManager.addClient(member, sessionID);
            }
            else
                sessionID = session.sessionID;

            memberAsPeer.token = sessionID;
            //give the session id and adjacent peers
            serializer.Serialize(stream, Constants.MessageTypes.MSG_RINGNEIGHBORS);
            serializer.Serialize(stream, sessionID);
            serializer.Serialize(stream, serverRingInfo.serverPolicyManager.getSearchQueryPolicy());
            serializer.Serialize(stream, serverRingInfo.serverPolicyManager.queryServer);
            serializer.Serialize(stream, serverRingInfo.ringPeerManager.getAdjacentPeers(memberAsPeer,
                Constants.IE_MAX_KEYWORDS_TO_CONSIDER, Constants.MAX_PEERS_TO_CONSIDER_FOR_KEYWORD,
                Constants.MAX_PEERS));

            clientWriter.Write(message);
            clientWriter.Flush();

            //Now add the new peer to the database
            serverRingInfo.ringPeerManager.addPeer(memberAsPeer);

            //invoke the user interface call back to update everything that depends on a new user
            //joining the network
            Member[] methodInvokeArgs = new Member[1];
            methodInvokeArgs[0] = member;
            //Asynchronous call to the UI thread
            ServerUserInterface.serverUserInterfaceInstance.BeginInvoke(
                serverUserInterfaceCallbackTable.addNewClient, methodInvokeArgs);
        }
 public WeightedPeer(float __weight, Peer __peer)
 {
     weight = __weight;
     peer = __peer;
 }
 public Neighbor(Peer __peer, NeighborProxy __neighborProxy)
 {
     peer = __peer;
     neighborProxy = __neighborProxy;
 }
        public void showQueryHit(RingInfo ringInfo, Peer hitPeer, ResourceHeader resourceHeader)
        {
            DataRow dr = queryResultsTable.NewRow();

            dr[0] = hitPeer.userInfo.nickname;
            dr[1] = resourceHeader.resourceID;
            dr[2] = resourceHeader.name;
            dr[3] = resourceHeader.size;
            dr[4] = "";
            dr[5] = hitPeer;
            dr[6] = ringInfo;
            dr[7] = resourceHeader;

            this.queryResultsTable.Rows.Add(dr);
        }
 public void RetreiveResource(Peer peer, RingInfo ringInfo, ResourceHeader resourceHeader, 
     UICallBack UIHndlr)
 {
     downloadManager.Download(peer, ringInfo, resourceHeader, UIHndlr);
 }