示例#1
0
        /// <summary>
        /// the delegate returns null if there was no default room found
        /// will also throw an error if the default room is not enabled in the xml or if the xml is not formatted correctly
        /// this does NOT add the room to the RoomManager cache
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="getDefaultRoomFinishedCallback"></param>
        private void GetDefaultRoom(ServerAccount userAccount, System.Action <IServerDistributedRoom> getDefaultRoomFinishedCallback)
        {
            Action <XmlDocument> getDefaultRoomServiceCallback = delegate(XmlDocument xmlResponse)
            {
                IServerDistributedRoom returnedDefaultRoom = null;
                XmlNode defaultRoomXmlNode = xmlResponse.SelectSingleNode("Rooms/Room");
                //if the default Room is null, we want to create a new room and set that as the default room
                if (defaultRoomXmlNode != null)
                {
                    RoomProperties         roomProperties = RoomXmlUtil.GetRoomPropertiesFromXml(defaultRoomXmlNode, mServerStateMachine.ServerAssetRepository);
                    IServerDistributedRoom defaultRoom    = CreateServerDistributedRoom(roomProperties);
                    if (defaultRoom == null)
                    {
                        StateServerAssert.Assert(new System.Exception("Error: the default room is either not enabled or does not contain proper data: " + defaultRoomXmlNode.OuterXml));
                    }
                    else
                    {
                        //if the user's default room is already cached, we just return the room object we have stored
                        // otherwise we add the newly created defaultRoom to the roomManager cache
                        if (!mRoomIdToRoomDistributedObject.TryGetValue(defaultRoom.RoomId, out returnedDefaultRoom))
                        {
                            returnedDefaultRoom = defaultRoom;
                        }
                    }
                }
                getDefaultRoomFinishedCallback(returnedDefaultRoom);
            };

            RoomManagerServiceAPI.GetDefaultRoomService(userAccount.AccountId, getDefaultRoomServiceCallback);
        }
示例#2
0
        public void DoWork()
        {
            try
            {
                List <ConnectionEventArgs> receivedMessages = null;
                // ReadFromAllConnections is where all the magic happens.
                // It runs Select on all sockets and reads data from any socket that won't block.
                // If there are completed packets, they are placed in receivedMessages.
                // Sleeping happens via Select's timeout.  We no longer sleep blindly.
                // Timeout argument is in MICROseconds, 1000000 microseconds = 1 second
                if (ReadFromAllConnections(out receivedMessages, 100000))
                {
                    foreach (ConnectionEventArgs connectionEventArgsMessage in receivedMessages)
                    {
                        mProcessIncomingMessage(connectionEventArgsMessage);
                    }
                }

                // Attempt to process outbound message queues
                SendToAllConnections();

                // Accept one new connection, if available
                // TODO: Move this into the select inside ReadFromAllConnections.
                TryAcceptSingleConnection();
            }
            catch (System.Exception ex)
            {
                StateServerAssert.Assert(ex);
            }
        }
        /// <summary>
        /// the expected node for the item xml is the following:
        /// <item id="1061" name="106" appName="HANGOUT_FAMILY_Application_1" itemTypeName="Room Backdrop" buttonName="Two Fast Two Furious" description="Live life a quarter mile at a time" smallImageUrl="http://s3.amazonaws.com/HangoutDevFileBucket/48141004.jpg" mediumImageUrl="" largeImageUrl="http://s3.amazonaws.com/HangoutDevFileBucket/48141004.jpg" available="-1">
        ///     <Assets />
        /// </item>
        /// </summary>
        /// <param name="receivedMessage"></param>
        private void ChangeBackground(Message receivedMessage)
        {
            mRoomBackgroundItemId = CheckType.TryAssignType <ItemId>(receivedMessage.Data[0]);

            List <ItemId> roomItems = UpdateRoomItems();

            XmlDocument updatedRoomDna = RoomXmlUtil.CreateRoomDnaXml(this.RoomName, this.RoomType, roomItems);

            //update the database with the new items
            RoomManagerServiceAPI.UpdateRoomDnaService(this.RoomId, updatedRoomDna, delegate(XmlDocument xmlResponse)
            {
                XmlNode successNode = xmlResponse.SelectSingleNode("Success");
                if (successNode != null && successNode.InnerText == "true")
                {
                    XmlNode backgroundItemXml = mServerAssetRepository.GetXmlDna(new ItemId[] { mRoomBackgroundItemId });
                    List <object> backgroundChangeMessageData = new List <object>();
                    backgroundChangeMessageData.Add(backgroundItemXml.OuterXml);

                    Message broadcastBackgroundChangeMessage = new Message();
                    broadcastBackgroundChangeMessage.UpdateObjectMessage(true, false, this.DistributedObjectId, (int)MessageSubType.ChangeBackground, backgroundChangeMessageData);

                    BroadcastMessage(broadcastBackgroundChangeMessage);
                }
                else
                {
                    StateServerAssert.Assert(new System.Exception("Error setting background in room on database."));
                }
            }
                                                       );
        }
示例#4
0
 public void StartLoop()
 {
     while (true)
     {
         try
         {
             foreach (IServerLoopWorker serverLoopWorker in mServerLoopWorkers)
             {
                 //we need to make sure that objects running in this loop dont
                 // starve the other objects that need to run
                 serverLoopWorker.DoWork();
             }
         }
         catch (System.InvalidOperationException)
         {
             //this is to handle the event where someone adds a serverLoopWorker after the start loop has already spun up (from another thread for example)
             // we don't have to do anything here, we just need to not stop running this loop
             // this condition shouldn't happen very often anyway.. and if it does.. we have other things to worry about
         }
         catch (System.Exception e)
         {
             StateServerAssert.Assert(e);
         }
     }
 }
示例#5
0
 public static void VerifySuccess(XmlDocument responseXml)
 {
     if (responseXml.SelectSingleNode("Success") == null)
     {
         StateServerAssert.Assert(new Exception("Fashion Minigame Server Error:\n" + responseXml.OuterXml));
     }
 }
示例#6
0
        /// <summary>
        // Activate the remote interface IServiceInterface
        /// </summary>
        /// <returns>true if activated else false</returns>
        public virtual bool ActivateTheInterface()
        {
            bool activated = false;

            try
            {
                WellKnownServiceTypeEntry WKSTE = new WellKnownServiceTypeEntry(typeof(IServiceInterface), StateServerConfig.RestServicesUrl, WellKnownObjectMode.SingleCall);

                if (RemotingConfiguration.ApplicationName == null)
                {
                    RemotingConfiguration.ApplicationName = "RestService";
                    RemotingConfiguration.RegisterWellKnownServiceType(WKSTE);
                }

                callToService = (IServiceInterface)Activator.GetObject(typeof(IServiceInterface), WKSTE.ObjectUri);

                if (callToService != null)
                {
                    activated = true;
                }
            }

            catch (System.Exception ex)
            {
                StateServerAssert.Assert(ex);
            }

            return(activated);
        }
示例#7
0
        public void CreateAccountForUser(string fbAccountId, string fbSessionKey, string nickName, string firstName, string lastName, string userIpAddress, string campaignId, string referrerId, Action <ServerAccount> createAccountForUserCallback)
        {
            mLogger.Debug(String.Format("CreateAccountForUser {0} {1} {2} {3} {4} {5} {6} {7}", fbAccountId, fbSessionKey, nickName, firstName, lastName, userIpAddress, campaignId, referrerId));
            Action <XmlDocument> createServerAccountServiceCallback = delegate(XmlDocument receivedXmlCreateNewAccount)
            {
                XmlNode newAccountXmlNode = receivedXmlCreateNewAccount.SelectSingleNode("Accounts/Account");
                //if we get a null xml node when trying to create an account, we need to throw an error
                if (newAccountXmlNode == null)
                {
                    StateServerAssert.Assert(new System.Exception("Error: unable to create a new account.. do you have a valid facebook Account Id, Session key, nickname, firstname, lastname, campaignId, and referredId?  Check your client data file! Returned Xml: " + receivedXmlCreateNewAccount.OuterXml));
                    createAccountForUserCallback(null);
                }
                else
                {
                    ServerAccount serverAccount = AccountsXmlUtil.GetAccountFromXml(newAccountXmlNode);
                    serverAccount.IpAddress = userIpAddress;
                    SaveCurrentAccountData(serverAccount);
                    CreatePaymentItemAccountForUser(serverAccount, userIpAddress, createAccountForUserCallback);

                    Metrics.Log(LogGlobals.CATEGORY_ACCOUNT, LogGlobals.EVENT_ACCOUNT_CREATED, LogGlobals.ACCOUNT_ID_LABEL, serverAccount.AccountId.ToString(), serverAccount.AccountId.ToString());
                }
            };

            CallCreateServerAccountService(fbAccountId, fbSessionKey, nickName, firstName, lastName, userIpAddress, campaignId, referrerId, createServerAccountServiceCallback);
        }
示例#8
0
        /// <summary>
        /// Connect to the Remote server via tcp
        /// </summary>
        /// <returns>true if successfull else false</returns>
        public bool RemoteConnect()
        {
            try
            {
                if ((channel != null) && ChannelServices.GetChannel(channel.ChannelName) != null)
                {
                    BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
                    BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
                    serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

                    IDictionary props = new Hashtable();
                    props["port"] = 0;
                    string s = System.Guid.NewGuid().ToString();
                    props["name"]            = s;
                    props["typeFilterLevel"] = TypeFilterLevel.Full;
                    channel = new TcpChannel(props, clientProvider, serverProvider);
                    ChannelServices.RegisterChannel(channel, false);

                    isConnected = true;
                }
            }
            catch (Exception ex)
            {
                isConnected = false;
                StateServerAssert.Assert(ex);
            }

            return(isConnected);
        }
示例#9
0
        /// <summary>
        /// it is expected the Account Xml node be formated as such:
        ///  <Account accountId="" fbAccountid="" piAccountId="" nickname="">
        ///		<AccountData>
        ///			<UserProperties>
        ///				<UserProperty Name="" Value=""/>
        ///				<UserProperty Name="" Value=""/>
        ///				<UserProperty Name="" Value=""/>
        ///				...
        ///			</UserProperties>
        ///		</AccountData>
        ///  </Account>
        /// </summary>
        /// <param name="xmlNode"></param>
        public static ServerAccount GetAccountFromXml(XmlNode xmlNode)
        {
            string accountIdString   = string.Empty;
            string fbAccountIdString = string.Empty;
            string piAccountIdString = string.Empty;
            string piSecureKeyString = string.Empty;
            string nickNameString    = string.Empty;
            string firstNameString   = string.Empty;
            string lastNameString    = string.Empty;

            if (!(XmlUtil.TryGetAttributeFromXml(ConstStrings.kAccountId, xmlNode, out accountIdString) &&              //uint
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kFbAccountId, xmlNode, out fbAccountIdString) &&          //long
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kPiAccountId, xmlNode, out piAccountIdString) &&          //
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kPiSecureKey, xmlNode, out piSecureKeyString) &&          //
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kNickName, xmlNode, out nickNameString) &&
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kFirstName, xmlNode, out firstNameString) &&
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kLastName, xmlNode, out lastNameString)))                //
            {
                StateServerAssert.Assert(new Exception("An account parameter is missing when creating a new account."));
                return(null);
            }

            AccountId accountId   = null;
            long      fbAccountId = 0;

            try
            {
                uint accountIdUInt = Convert.ToUInt32(accountIdString);
                accountId   = new AccountId(accountIdUInt);
                fbAccountId = Convert.ToInt64(fbAccountIdString);
            }
            catch (System.Exception ex)
            {
                StateServerAssert.Assert(new Exception("Error converting string to accountId type: " + ex.Data, ex));
                return(null);
            }

            XmlNode        accountDataNode = xmlNode.SelectSingleNode(ConstStrings.kAccountData);
            UserProperties userProperties  = new UserProperties();

            if (accountDataNode != null)
            {
                XmlNode userPropertiesXmlNode = accountDataNode.SelectSingleNode(ConstStrings.kUserProperties);
                //if we can't find a UserProperties node, we can just set some default values
                if (userPropertiesXmlNode != null)
                {
                    if (!UserProperties.UserPropertiesFromXml(userPropertiesXmlNode, out userProperties))
                    {
                        StateServerAssert.Assert(new Exception("Error parsing user properties from xml: " + xmlNode.OuterXml));
                        return(null);
                    }
                }
            }

            SetDefaultUserProperties(ref userProperties);

            return(new ServerAccount(accountId, fbAccountId, piAccountIdString, piSecureKeyString, nickNameString, firstNameString, lastNameString, userProperties));
        }
示例#10
0
        private static void VerifyGiveCoinSuccess(XmlDocument responseXml)
        {
            XmlNode successNode = responseXml.SelectSingleNode("success");

            if ((successNode == null) || (successNode.InnerXml != "true"))
            {
                StateServerAssert.Assert(new Exception("Create Coin Error:\n" + responseXml.OuterXml));
            }
        }
示例#11
0
        public void GetAccountForUser(string fbAccountId, string fbSessionKey, string nickName, string firstName, string lastName, string userIpAddress, string campaignId, string referrerId, Action <ServerAccount> getAccountForUserCallback)
        {
            Action <XmlDocument> getAccountForFacebookIdCallback = delegate(XmlDocument receivedXmlGetAccount)
            {
                //<Accounts>
                //  <Account accountId="" fbaccountid="" tfaccountId="" nickname="" firstname="" lastname=""/>
                //</Accounts>
                XmlNode accountXmlNode = receivedXmlGetAccount.SelectSingleNode("Accounts/Account");
                if (accountXmlNode != null)
                {
                    ServerAccount serverAccount = AccountsXmlUtil.GetAccountFromXml(accountXmlNode);

                    if (serverAccount != null)
                    {
                        serverAccount.IpAddress = userIpAddress;
                        mLogger.Info("GetAccountForUser, ServerAccount: " + serverAccount.ToString());
                        serverAccount.SaveCurrentAccountData(delegate(XmlDocument returnedXmlDocument)
                        {
                        });
                        if (serverAccount.PaymentItemUserId.Trim().Length == 0)
                        {
                            mLogger.Debug("GetAccountForUser.CreatePaymentItemsAccount");
                            CreatePaymentItemAccountForUser(serverAccount, userIpAddress, getAccountForUserCallback);
                        }
                        else
                        {
                            mLogger.Debug("GetAccountForUser, calling callback");
                            getAccountForUserCallback(serverAccount);
                        }
                    }
                    else
                    {
                        StateServerAssert.Assert(new Exception("Could not extract the account from the Xml"));
                    }
                }
                else
                {
                    CreateAccountForUser(fbAccountId, fbSessionKey, nickName, firstName, lastName, userIpAddress, campaignId, referrerId, delegate(ServerAccount newServerAccount)
                    {
                        getAccountForUserCallback(newServerAccount);
                    }
                                         );
                }
            };

            try
            {
                CallGetServerAccountForFacebookIdService(fbAccountId, getAccountForFacebookIdCallback);
            }
            catch (System.Exception)
            {
                mLogger.Warn("Could not get an account for facebook id: " + fbAccountId);
                getAccountForUserCallback(null);
            }
        }
示例#12
0
        /// <summary>
        /// return true in the event of an enabled room with valid data
        /// return false in the event of a non-enabled room or a room with missing / invalid data
        /// roomNodeXml is expected to be in the following format:
        /// <Room RoomId="1" AccountId="696969" IsEnabled="1" PrivacyLevel="0">
        ///     <RoomDna RoomName="" RoomType=""><Items> </Items> </RoomDna>
        /// </Room>
        /// </summary>
        public static bool GetRoomInfoFromRoomXmlNode(XmlNode roomNodeXml, out AccountId accountId, out PrivacyLevel privacyLevel, out string roomName, out RoomId roomId, out RoomType roomType, out List <ItemId> itemIds)
        {
            accountId    = null;
            roomName     = string.Empty;
            roomId       = null;
            roomType     = RoomType.Default;
            itemIds      = new List <ItemId>();
            privacyLevel = PrivacyLevel.Default;

            XmlAttributeCollection attributes         = roomNodeXml.Attributes;
            XmlAttribute           isEnabledAttribute = attributes["IsEnabled"];

            if (isEnabledAttribute == null)
            {
                StateServerAssert.Assert(new System.Exception("Error: Could not find the IsEnabled xml attribute."));
                return(false);
            }

            if (isEnabledAttribute.Value == "1")
            {
                GetRoomInfoFromRoomXmlNode(roomNodeXml, out accountId, out privacyLevel, out roomName, out roomId, out roomType);

                //find the room items in the DNA
                XmlNode roomItemsXmlNode = roomNodeXml.SelectSingleNode("RoomDna/Items");
                if (roomItemsXmlNode != null)
                {
                    //parse out the item ids separated by comma's in the xml node and convert them to ItemId objects
                    string   roomItems       = roomItemsXmlNode.InnerText;
                    string[] roomItemStrings = roomItems.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string roomItemString in roomItemStrings)
                    {
                        uint rawUIntValue = 0;
                        try
                        {
                            rawUIntValue = Convert.ToUInt32(roomItemString);
                            itemIds.Add(new ItemId(rawUIntValue));
                        }
                        catch (System.Exception ex)
                        {
                            StateServerAssert.Assert(ex);
                            return(false);
                        }
                    }
                }
                else
                {
                    StateServerAssert.Assert(new System.Exception("Error: Could not find RoomDna/Items in the xml document."));
                    return(false);
                }
                return(true);
            }
            return(false);
        }
示例#13
0
        /// <summary>
        /// this expects a document with a top level <Room> </Room> xml node
        /// </summary>
        /// <param name="roomXmlDocument"></param>
        /// <returns></returns>
        public static RoomProperties GetRoomPropertiesFromXml(XmlDocument roomXmlDocument, IServerAssetRepository serverAssetRepository)
        {
            XmlNode roomXmlNode = roomXmlDocument.SelectSingleNode("Rooms/Room");

            if (roomXmlNode != null)
            {
                //the room node is parsed out of the xml doc and passed to the GetRoomFromXml(XmlNode) function
                return(GetRoomPropertiesFromXml(roomXmlNode, serverAssetRepository));
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("Error: could not find top level Room node"));
            }
            return(null);
        }
示例#14
0
        /// <summary>
        /// the expected output of this xml document looks like this:
        /// <Items>
        ///     <Item>
        ///         <Id>1</Id>
        ///         <Assets>
        ///             <Asset ItemId="" AssetId="">
        ///                 <!-- asset xml data from web service -->
        ///             </Asset>
        ///             <Asset ItemId="" AssetId="">
        ///                 <!-- asset xml data from web service -->
        ///             </Asset>
        ///         </Assets>
        ///     </Item>
        ///     <Item>
        ///         <Id></Id>
        ///         <Assets><Asset ItemId="" AssetId=""></Asset></Assets>
        ///     </Item>
        /// </Items>
        /// </summary>
        /// <param name="itemIdsForObject"></param>
        /// <returns></returns>
        public XmlDocument GetXmlDna(IEnumerable <ItemId> itemIdsForObject)
        {
            Dictionary <ItemId, List <XmlNode> > itemIdsToAssetXmls = GetAssetXmlFromItemList(itemIdsForObject);
            //build an xml structure out of the Dictionary<ItemId, List<XmlNode>>
            StringBuilder xmlBuilder = new StringBuilder();

            xmlBuilder.Append("<Items>");
            foreach (KeyValuePair <ItemId, List <XmlNode> > itemIdToAssetXmls in itemIdsToAssetXmls)
            {
                ItemInfo itemInfo;
                if (mItems.TryGetValue(itemIdToAssetXmls.Key, out itemInfo))
                {
                    xmlBuilder.AppendFormat
                    (
                        "<Item type=\"{0}\" thumbnailUrl=\"{1}\" >",
                        itemInfo.ItemTypeString,
                        itemInfo.ThumbnailUrl
                    );
                    xmlBuilder.AppendFormat("<Id>{0}</Id>", itemIdToAssetXmls.Key.ToString());
                    xmlBuilder.Append("<Assets>");
                    foreach (XmlNode assetXml in itemIdToAssetXmls.Value)
                    {
                        string assetXmlString = assetXml.OuterXml;

                        int indexOfAssetIdAttribute = assetXmlString.IndexOf(" AssetId");
                        if (indexOfAssetIdAttribute > 0 && indexOfAssetIdAttribute < assetXmlString.Length)
                        {
                            //add the ItemId attribute
                            assetXmlString = assetXmlString.Insert(indexOfAssetIdAttribute, " ItemId=\"" + itemIdToAssetXmls.Key.ToString() + "\"");
                        }
                        else
                        {
                            StateServerAssert.Assert(new System.Exception("indexOfAssetIdAttribute out of bounds.  will be unable to instert ItemId into xml node"));
                        }

                        xmlBuilder.Append(assetXmlString);
                    }
                    xmlBuilder.Append("</Assets>");
                    xmlBuilder.Append("</Item>");
                }
            }
            xmlBuilder.Append("</Items>");

            XmlDocument newdoc = new XmlDocument();

            newdoc.LoadXml(xmlBuilder.ToString());
            return(newdoc);
        }
        /// <summary>
        /// Creates and error XML document response document from a message.
        /// </summary>
        /// <param name="message">The error message</param>
        /// <returns>Error XML document</returns>
        protected static XmlDocument CreateErrorDoc(string message)
        {
            XmlDocument response = new XmlDocument();

            try
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("<response><Error><Message>" + message + "</Message></Error></response>");
                response.LoadXml(sb.ToString());
            }
            catch
            {
                response.LoadXml("<response><Error>unknown</Error></response>");
            }

            StateServerAssert.Assert(new Exception(response.OuterXml));
            return(response);
        }
示例#16
0
        private void GetAvatarServiceResponse(XmlNode avatarXmlNode, string nickname, Guid sessionId, ZoneId zoneId, Action <bool> gotAvatarServiceResponse)
        {
            List <ItemId> itemIds = null;
            AvatarId      avatarId;

            try
            {
                if (AvatarXmlUtil.GetAvatarInfoFromAvatarXmlNode(avatarXmlNode, out avatarId, out itemIds))
                {
                    Dna savedDna = mServerAssetRepository.GetDna(itemIds);

                    // Create an updated dna by starting with the reference dna and updating it with the savedDna
                    GetReferenceAvatar(delegate(Dna referenceAvatarDna)
                    {
                        Dna avatarDna = new Dna(mReferenceAvatarDna);
                        avatarDna.UpdateDna(savedDna);
                        // TODO?  If UpdateDna overwrites something or fills in missing data we should save the dna back to the db

                        // Get xml from updated avatar dna
                        XmlDocument dnaXml = mServerAssetRepository.GetXmlDna(avatarDna.GetItemIdList());

                        DistributedObjectId distributedObjectId = mDistributedObjectIdManager.GetNewId();

                        ServerAccount serverAccount = mServerStateMachine.SessionManager.GetServerAccountFromSessionId(sessionId);
                        ServerDistributedAvatar serverDistributedAvatar = new ServerDistributedAvatar(distributedObjectId, avatarId, sessionId, nickname, dnaXml, serverAccount, mServerObjectRepository, mServerAssetRepository);
                        //register object with object repository
                        mServerObjectRepository.AddObjectToSessionId(sessionId, serverDistributedAvatar);
                        //register object with session manager
                        mServerEngine.ProcessZoneChange(serverDistributedAvatar, zoneId);
                        gotAvatarServiceResponse(true);
                    });
                }
                else
                {
                    gotAvatarServiceResponse(false);
                }
            }
            catch (System.Exception ex)
            {
                StateServerAssert.Assert(ex);
                gotAvatarServiceResponse(false);
            }
        }
示例#17
0
        /// <summary>
        /// This function creates in ram the room distributed object for the RoomManager
        /// roomDnaXmlNode is expected to be in the format of:
        /// <RoomDna RoomName="" RoomType="">
        ///     <Items>1, 2, 3, 4 </Items>
        /// </RoomData>
        /// </summary>
        private void AddRoomToRoomManager(IServerDistributedRoom newServerDistributedRoom)
        {
            //create a new zone Id for the room
            ZoneId zoneId = mServerStateMachine.ZoneManager.GetNewZoneId();

            //register the new room with the server object repository
            mServerStateMachine.ServerObjectRepository.AddObject(newServerDistributedRoom);
            //register the new room with the zone
            mServerStateMachine.ServerEngine.ProcessZoneChange(newServerDistributedRoom, zoneId);
            //add the new room to our dictionary listing indexed by room Id
            if (!mRoomIdToRoomDistributedObject.ContainsKey(newServerDistributedRoom.RoomId))
            {
                mRoomIdToRoomDistributedObject.Add(newServerDistributedRoom.RoomId, newServerDistributedRoom);
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("Trying to create a room that has a non-unique RoomId."));
            }
        }
示例#18
0
        public void CreateNewAvatarForAccount(Guid sessionId, ZoneId zoneId, ServerAccount serverAccount, AvatarId defaultAvatarId, System.Action <bool> createAvatarFinishedCallback)
        {
            Action <XmlDocument> createAvatarServiceCallback = delegate(XmlDocument xmlResponse)
            {
                XmlNode avatarXmlNode = xmlResponse.SelectSingleNode("Avatars/Avatar");

                if (avatarXmlNode != null)
                {
                    Metrics.Log(LogGlobals.CATEGORY_ACCOUNT, LogGlobals.EVENT_AVATAR_CREATED, LogGlobals.AVATAR_ID_LABEL, defaultAvatarId.ToString(), serverAccount.AccountId.ToString());
                    GetAvatarServiceResponse(avatarXmlNode, serverAccount.Nickname, sessionId, zoneId, createAvatarFinishedCallback);
                }
                else
                {
                    StateServerAssert.Assert(new System.Exception("Error: Could not create avatar: " + xmlResponse.InnerText));
                    createAvatarFinishedCallback(false);
                }
            };

            AvatarManagerServiceAPI.CreateAvatarForUser(serverAccount, defaultAvatarId, createAvatarServiceCallback);
        }
示例#19
0
        public static bool GetFriendsInfoFromXml(XmlDocument xml, out List <FacebookFriendInfo> friendInfos)
        {
            friendInfos = new List <FacebookFriendInfo>();

            XmlNode friendsXmlNode = xml.SelectSingleNode("Friends");

            if (friendsXmlNode != null)
            {
                XmlNodeList friendXmlNodes = friendsXmlNode.SelectNodes("Friend");
                foreach (XmlNode friendNode in friendXmlNodes)
                {
                    XmlAttribute hangoutAccountIdAttribute = friendNode.Attributes["AccountId"];
                    AccountId    accountId = null;
                    if (hangoutAccountIdAttribute != null && hangoutAccountIdAttribute.Value != string.Empty)
                    {
                        try
                        {
                            uint accountIdUint = Convert.ToUInt32(hangoutAccountIdAttribute.Value);
                            accountId = new AccountId(accountIdUint);
                        }
                        catch (System.Exception ex)
                        {
                            //log here.. someone put a non-uint in for the accountId
                            StateServerAssert.Assert(ex);
                        }
                    }
                    string firstName   = (friendNode.Attributes["FirstName"].Value);
                    string lastName    = (friendNode.Attributes["LastName"].Value);
                    long   fbAccountId = long.Parse(friendNode.Attributes["FBAccountId"].Value);
                    string imageUrl    = (friendNode.Attributes["PicSquare"].Value);

                    friendInfos.Add(new FacebookFriendInfo(accountId, fbAccountId, firstName, lastName, imageUrl));
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
示例#20
0
        /// <summary>
        /// Get a reference system avatar.  This avatar is used to fill in missing required info when pulling an avatar from the db
        /// </summary>
        private void GetReferenceAvatar(Action <Dna> gotReferenceAvatarFinished)
        {
            Action <XmlDocument> systemAvatarCallback = delegate(XmlDocument xmlResponse)
            {
                // Get the avatars for the friends without Hangout Avatars
                XmlNode       avatarXmlNode = xmlResponse.SelectSingleNode("/Avatars/Avatar[@AvatarId='1']");
                AvatarId      avatarId;
                List <ItemId> itemIds = null;
                if (AvatarXmlUtil.GetAvatarInfoFromAvatarXmlNode(avatarXmlNode, out avatarId, out itemIds))
                {
                    //use the ServerAssetRepo to composite the List<ItemId> into an XmlNode
                    XmlDocument itemsXml = mServerAssetRepository.GetXmlDna(itemIds);

                    // Get a list of AssetInfos from this xml
                    IEnumerable <AssetInfo> assetInfoList = ServerAssetInfo.Parse(itemsXml);

                    // Make dna
                    mReferenceAvatarDna = new Dna();
                    mReferenceAvatarDna.UpdateDna(assetInfoList);
                    gotReferenceAvatarFinished(mReferenceAvatarDna);
                    mLogger.Debug("System avatar xml = " + xmlResponse.OuterXml);
                }
                else
                {
                    StateServerAssert.Assert(new Exception("Didn't get a valid system avatar for reference avatar, using an empty DNA"));
                    mReferenceAvatarDna = new Dna();
                    gotReferenceAvatarFinished(mReferenceAvatarDna);
                }
            };

            if (mReferenceAvatarDna == null)
            {
                AvatarManagerServiceAPI.GetSystemAvatars(systemAvatarCallback);
            }
            else
            {
                gotReferenceAvatarFinished(mReferenceAvatarDna);
            }
        }
示例#21
0
        public void FacebookFriendsReady(ServerAccount serverAccount, Guid sessionId)
        {
            try
            {
                if (serverAccount.FacebookFriendsRequested)
                {
                    mLogger.Debug("FacebookFriendsReady: " + serverAccount.AccountId.ToString());
                    serverAccount.FacebookFriendsRequested = false;
                    IDictionary <long, FacebookFriendInfo> possibleHires = new Dictionary <long, FacebookFriendInfo>(serverAccount.FacebookFriendsLookupTable);

                    FashionMinigameServiceAPI.GetAllHiredFriends(serverAccount, delegate(ICollection <long> hiredFriendIds)
                    {
                        // Filter out any users that have already been hired
                        foreach (long facebookId in hiredFriendIds)
                        {
                            possibleHires.Remove(facebookId);
                        }

                        Message responseMessage    = new Message();
                        List <object> responseData = new List <object>();
                        responseData.Add(serverAccount.FacebookFriendsReadyCallbackId);                         // callback Id
                        if (possibleHires.Count == 0)
                        {
                            responseData.Add(false);
                        }
                        else
                        {
                            responseData.Add(possibleHires);
                        }
                        responseMessage.FashionGameFriendsToHire(responseData);
                        SendMessageToClient(responseMessage, sessionId);
                    });
                }
            }
            catch (System.Exception ex)
            {
                StateServerAssert.Assert(new Exception("Something went wrong with sending the facebook friends to the client.", ex));
            }
        }
示例#22
0
        protected void GetAssetXml(XmlDocument responseXmlDoc)
        {
            XmlNodeList assets = responseXmlDoc.GetElementsByTagName("Asset");

            foreach (XmlNode asset in assets)
            {
                uint assetIdUnsignedInt = 0;
                if (uint.TryParse(asset.Attributes["AssetId"].Value, out assetIdUnsignedInt))
                {
                    AssetId assetId = new AssetId(assetIdUnsignedInt);
                    try
                    {
                        mAssetIdsToAssetXml.Add(assetId, asset);
                    }
                    catch (System.Exception ex)
                    {
                        StateServerAssert.Assert(ex);
                        continue;
                    }
                }
            }
        }
示例#23
0
        public void GetAllFacebookFriendsForUser(Guid senderId, long facebookAccountId, string facebookSessionKey, Action <List <FacebookFriendInfo> > facebookFriendsCallback)
        {
            System.Action <XmlDocument> getFacebookFriendsServiceFinished = delegate(XmlDocument xmlResponse)
            {
                List <FacebookFriendInfo> friendInfos = null;
                if (FriendsXmlUtil.GetFriendsInfoFromXml(xmlResponse, out friendInfos))
                {
                    facebookFriendsCallback(friendInfos);

                    ServerAccount serverAccount = mServerStateMachine.SessionManager.GetServerAccountFromSessionId(senderId);
                    //if the serverAccount is null, we don't do anything.. this can happen for example if the user logs out before the service call has time to return
                    if (serverAccount != null)
                    {
                        mFacebookFriendsReceivedEvent(serverAccount, senderId);
                    }
                }
                else
                {
                    StateServerAssert.Assert(new Exception("There was a problem parsing the friends info out of the service returned xml: " + xmlResponse.OuterXml));
                }
            };

            FriendsManagerServiceAPI.GetAllFacebookFriends(facebookAccountId, facebookSessionKey, getFacebookFriendsServiceFinished);
        }
示例#24
0
 public void ReceiveRequest(Message receivedMessage, Guid senderId)
 {
     switch (receivedMessage.MessageType)
     {
     case MessageType.Update:
         if (receivedMessage.DistributedObjectId == null)
         {
             StateServerAssert.Assert(new System.Exception("receivedMessage.DistributedObjectId is null"));
         }
         else
         {
             IServerDistributedObject serverDistributedObject = (IServerDistributedObject)this.GetObject(receivedMessage.DistributedObjectId);
             if (serverDistributedObject == null)
             {
                 Console.WriteLine("WARNING: ReceiveMessage for object not on server: %i", receivedMessage.DistributedObjectId);
             }
             else
             {
                 serverDistributedObject.ProcessMessage(receivedMessage);
             }
         }
         break;
     }
 }
示例#25
0
        private void ProcessHiredFriends(ServerAccount serverAccount,
                                         Action <List <object> > returnFunc,
                                         List <object> responseData,
                                         ICollection <long> hiredFriendIds)
        {
            if (hiredFriendIds.Count > 0)
            {
                Dictionary <AccountId, FacebookFriendInfo> friendAccounts = new Dictionary <AccountId, FacebookFriendInfo>();
                List <FacebookFriendInfo> friendsWithoutAccounts          = new List <FacebookFriendInfo>();

                foreach (long facebookId in hiredFriendIds)
                {
                    if (facebookId == serverAccount.FacebookAccountId)
                    {
                        friendAccounts.Add(serverAccount.AccountId, null);
                        continue;
                    }

                    HandleFriendCase
                    (
                        serverAccount,
                        facebookId,
                        delegate(FacebookFriendInfo ffi) { friendAccounts.Add(ffi.AccountId, ffi); },
                        delegate(FacebookFriendInfo ffi) { friendsWithoutAccounts.Add(ffi); },
                        delegate() { friendsWithoutAccounts.Add(new FacebookFriendInfo(new AccountId(0u), facebookId, "Unfriended", "", "")); }
                    );
                }

                AvatarManagerServiceAPI.GetAvatarForUsers(friendAccounts.Keys, delegate(XmlDocument friendAccountsAvatars)
                {
                    AvatarManagerServiceAPI.GetSystemAvatars(delegate(XmlDocument npcAvatarsXml)
                    {
                        // Get the Avatars for the friends with Hangout Avatars
                        foreach (XmlNode friendAvatarNode in friendAccountsAvatars.SelectNodes("Avatars/Avatar"))
                        {
                            // This is a little weird... the dictionary doesn't actually contain the new object, but that object
                            // will index properly into the dictionary for what we want. If we didn't do this weirdness we'd have
                            // to make a new data structure or search linearly
                            AccountId accountId = new AccountId(uint.Parse(friendAvatarNode.SelectSingleNode("@AccountId").InnerText));

                            FacebookFriendInfo facebookFriend;
                            if (!friendAccounts.TryGetValue(accountId, out facebookFriend))
                            {
                                StateServerAssert.Assert
                                (
                                    new Exception
                                    (
                                        "Facebook friend ID provided by the client (" +
                                        accountId +
                                        ") was not found in Account ID (" +
                                        serverAccount.AccountId +
                                        ")'s friend list while trying to process hired friends"
                                    )
                                );
                                return;
                            }

                            XmlElement friendAvatarElement = (XmlElement)friendAvatarNode;
                            ReplaceItemIdsWithDna(friendAvatarElement);
                            AddFacebookData(friendAvatarNode, facebookFriend);
                            responseData.Add(friendAvatarNode.OuterXml);
                        }

                        // Get the avatars for the friends without Hangout Avatars
                        XmlNodeList npcAvatarNodes = npcAvatarsXml.SelectNodes("/Avatars/Avatar");
                        foreach (FacebookFriendInfo facebookFriend in friendsWithoutAccounts)
                        {
                            XmlNode npcAvatarNode = npcAvatarNodes[mRand.Next(0, npcAvatarNodes.Count)];

                            // Local avatar is already expanded to assets
                            XmlElement npcElement = (XmlElement)npcAvatarNode;
                            ReplaceItemIdsWithDna(npcElement);
                            AddFacebookData(npcAvatarNode, facebookFriend);
                            responseData.Add(npcAvatarNode.OuterXml);
                        }

                        returnFunc(responseData);
                    });
                });
            }
            else
            {
                returnFunc(responseData);
            }
        }
示例#26
0
        /// <summary>
        /// Parse the client PaymentItems Command
        /// Converts the client PaymentItems command to a PaymentItems command
        /// </summary>
        /// <param name="clientCommand">Client PaymentItems command</param>
        /// <returns>PaymentItems command</returns>
        private PaymentCommand ParseClientPaymentCommand(PaymentCommand clientCommand)
        {
            MoneyTransactionLogging moneyLog       = new MoneyTransactionLogging();
            PaymentCommand          paymentCommand = null;

            switch (clientCommand.Verb)
            {
            case "GetUserBalance":
                paymentCommand = CreateSimpleCommand("HangoutUsers", "GetUserBalance", clientCommand.Parameters);
                break;

            case "AddVirtualCoinForUser":
                paymentCommand = AddVirtualCoinForUser(clientCommand.Parameters);
                break;

            case "GetUserInventory":
                paymentCommand = GetUserInventory(clientCommand.Parameters);
                break;

            case "GetStoreInventory":
                paymentCommand = GetStoreInventory(clientCommand.Parameters);
                break;

            case "PurchaseOffers":
                paymentCommand = CreateSimpleCommand("HangoutPurchase", "PurchaseCashOffers", clientCommand.Parameters);
                break;

            case "PurchaseCoinOffers":
                paymentCommand = CreateSimpleCommand("HangoutPurchase", "PurchaseCoinOffers", clientCommand.Parameters);
                break;

            case "PurchaseItems":
                paymentCommand = PurchaseItems(clientCommand.Parameters, false);
                break;

            case "PurchaseItemsGift":
                paymentCommand = PurchaseItems(clientCommand.Parameters, true);
                break;

            case "PurchaseGameCurrencyPayPal":
                paymentCommand = PurchaseGameCurrencyPayPal(clientCommand.Parameters);
                moneyLog.LogMoneyPaymentCommand("", "", paymentCommand.Parameters, "", "Paypal");
                break;

            case "PurchaseGameCurrencyCreditCard":
                paymentCommand = PurchaseGameCurrencyCreditCard(clientCommand.Parameters);
                moneyLog.LogMoneyPaymentCommand("", "", paymentCommand.Parameters, "", "CreditCard");
                break;

            case "HealthCheck":
                paymentCommand      = new PaymentCommand();
                paymentCommand.Noun = "HangoutInfo";
                paymentCommand.Verb = "HealthCheck";
                break;

            case "SecurePaymentInfo":
                paymentCommand      = new PaymentCommand();
                paymentCommand.Noun = "HangoutUsers";
                paymentCommand.Verb = "SecurePaymentInfo";
                break;

            default:
                StateServerAssert.Assert(new System.Exception("Invalid Payment Items Command"));
                break;
            }

            return(paymentCommand);
        }
示例#27
0
        public static bool GetRoomInfoFromRoomXmlNode(XmlNode roomNode, out AccountId accountId, out PrivacyLevel privacyLevel, out string roomName, out RoomId roomId, out RoomType roomType)
        {
            roomId       = null;
            roomName     = String.Empty;
            roomType     = RoomType.Default;
            accountId    = null;
            privacyLevel = PrivacyLevel.Default;

            XmlAttributeCollection attributes      = roomNode.Attributes;
            XmlAttribute           roomIdAttribute = attributes["RoomId"];

            if (roomIdAttribute != null)
            {
                try
                {
                    roomId = new RoomId(Convert.ToUInt32(roomIdAttribute.Value));
                }
                catch (System.Exception ex)
                {
                    StateServerAssert.Assert(ex);
                    return(false);
                }
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("RoomId xml attribute found in the Room xml node"));
                return(false);
            }

            XmlAttribute accountIdAttribute = attributes["AccountId"];

            if (accountIdAttribute != null)
            {
                try
                {
                    uint accountIdUInt = Convert.ToUInt32(accountIdAttribute.Value);
                    accountId = new AccountId(accountIdUInt);
                }
                catch (System.Exception ex)
                {
                    StateServerAssert.Assert(ex);
                    return(false);
                }
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("AccountId xml attribute not found in the Room xml node"));
                return(false);
            }

            XmlAttribute privacyLevelAttribute = attributes["PrivacyLevel"];

            if (privacyLevelAttribute != null)
            {
                try
                {
                    privacyLevel = (PrivacyLevel)(Convert.ToInt32(privacyLevelAttribute.Value));
                }
                catch (System.Exception ex)
                {
                    StateServerAssert.Assert(ex);
                    return(false);
                }
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("PrivacyLevel xml attribute not found in the Room xml node"));
                return(false);
            }

            XmlNode roomDnaXmlNode = roomNode.SelectSingleNode("RoomDna");

            if (roomDnaXmlNode != null)
            {
                XmlAttribute roomTypeAttribute = roomDnaXmlNode.Attributes["RoomType"];
                try
                {
                    roomType = (RoomType)Enum.Parse(typeof(RoomType), roomTypeAttribute.Value);
                }
                catch (System.Exception ex)
                {
                    StateServerAssert.Assert(ex);
                    return(false);
                }
                roomName = roomDnaXmlNode.Attributes["RoomName"].Value;
            }
            else
            {
                StateServerAssert.Assert(new System.Exception("RoomDna xml node not found in the Room xml node"));
                return(false);
            }
            return(true);
        }