/// <summary>
        /// Returns a list of All friends who have added the facebook app
        /// regardless of whether they are online
        /// </summary>
        /// <param name="fbAccountId"></param>
        /// <param name="fbSessionKey"></param>
        /// <returns></returns>
        public SimpleResponse GetAllFriendsWhoAreAppUsers(long fbAccountId, string fbSessionKey, string getMockData)
        {
            mServiceLog.Log.InfoFormat("GetAllFriendsWhoAreAppUsers: fbAccountId={0}, fbSessionKey={1}, getMockData={2}", fbAccountId, fbSessionKey, getMockData);
            bool isMockRequest = false;

            if (getMockData == "1" || getMockData == "true")
            {
                isMockRequest = true;
            }
            StringBuilder xmlBuilder = new StringBuilder();

            //instantiate connection to facebookApi
            FacebookSession facebookSession = new HangoutFacebookSession();

            facebookSession.ApplicationKey    = WebConfig.FacebookAPIKey;
            facebookSession.ApplicationSecret = WebConfig.FacebookSecret;
            facebookSession.SessionKey        = fbSessionKey;
            Api facebookApi = new Api(facebookSession);


            Dictionary <long, string> accountMapping = new Dictionary <long, string>();
            List <long> fbAppUserFriendIds;

            try
            {
                fbAppUserFriendIds = (List <long>)facebookApi.Friends.GetAppUsers();
            }
            catch (FacebookException fbEx)
            {
                mServiceLog.Log.Error("Facebook Exception: errorcode=" + fbEx.ErrorCode + ", errorType=" + fbEx.ErrorType + ", message=" + fbEx.Message);
                HangoutException hangoutException = new HangoutException("FACEBOOK EXCEPTION: " + fbEx.Message + ", Facebook ErrorCode: " + fbEx.ErrorCode + ", FbErrorType: " + fbEx.ErrorType);


                hangoutException.Source = fbEx.Source;
                throw hangoutException;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Facebook did not return any useful information or invalid xml " + ex.Message, ex.InnerException);
            }

            accountMapping = ListHangoutAccountsForFbAccounts(fbAppUserFriendIds);

            //For each friend who is an app user,
            XmlDocument friendsXml = GetAllFriendsWhoAreAppUsersXml(fbAccountId, facebookApi);

            string friendString = "";

            if (getMockData != null && isMockRequest)
            {
                friendString = GetMockFriendDataForFacebook();
            }
            else
            {
                friendString = ConstructFriendData(friendsXml, accountMapping);
            }


            return(new SimpleResponse("Friends", friendString));
        }
Exemple #2
0
        public SimpleResponse LoginFacebook(long fbAccountId, string fbSessionKey)
        {
            mServiceLog.Log.InfoFormat("LoginFacebook: fbAccountId={0}, fbSessionKey={1}", fbAccountId, fbSessionKey);

            FacebookSession facebookSession = new HangoutFacebookSession();

            facebookSession.ApplicationKey    = WebConfig.FacebookAPIKey;
            facebookSession.ApplicationSecret = WebConfig.FacebookSecret;
            facebookSession.SessionKey        = fbSessionKey;

            Api facebookApi = new Api(facebookSession);

            long currentFbUserId;

            Facebook.Schema.user fbUser;

            try
            {
                currentFbUserId = facebookApi.Users.GetLoggedInUser();
                fbUser          = facebookApi.Users.GetInfo(currentFbUserId);
            }
            catch (FacebookException fbEx)
            {
                mServiceLog.Log.Error("Facebook Exception: errorcode=" + fbEx.ErrorCode + ", errorType=" + fbEx.ErrorType + ", message=" + fbEx.Message);
                HangoutException hangoutException = new HangoutException("FACEBOOK EXCEPTION: " + fbEx.Message + ", Facebook ErrorCode: " + fbEx.ErrorCode + ", FbErrorType: " + fbEx.ErrorType);


                hangoutException.Source = fbEx.Source;
                throw hangoutException;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Facebook did not return any useful information or invalid xml " + ex.Message, ex.InnerException);
            }

            if (!fbUser.is_app_user.GetValueOrDefault())
            {
                throw new Exception("is_app_user returned false");
            }

            if (fbAccountId != fbUser.uid)
            {
                throw new Exception("logged in facebook UID does not match fbAccountId parameter");
            }
            SetUserMetricsData(fbAccountId.ToString());
            return(GetAccounts(fbAccountId.ToString(), null, null, null, null, null));
        }
        public SimpleResponse GetAllFacebookFriends(long fbAccountId, string fbSessionKey)
        {
            mServiceLog.Log.InfoFormat("GetAllFacebookFriends: fbAccountId={0}, fbSessionKey={1}", fbAccountId, fbSessionKey);
            StringBuilder xmlBuilder = new StringBuilder();

            FacebookSession facebookSession = new HangoutFacebookSession();

            facebookSession.ApplicationKey    = WebConfig.FacebookAPIKey;
            facebookSession.ApplicationSecret = WebConfig.FacebookSecret;
            facebookSession.SessionKey        = fbSessionKey;

            Api facebookApi = new Api(facebookSession);

            //IList<facebook.Schema.user> fbFriends = facebookApi.friends.getUserObjects(fbAccountId);//get(Convert.ToInt64(fbAccountId));
            mServiceLog.Log.InfoFormat("GetAllFacebookFriends: got fb response");

            Dictionary <long, string> accountMapping = new Dictionary <long, string>();

            List <long> fbAppUserFriendIds;

            try
            {
                fbAppUserFriendIds = (List <long>)facebookApi.Friends.GetAppUsers();
            }
            catch (FacebookException fbEx)
            {
                mServiceLog.Log.Error("Facebook Exception: errorcode=" + fbEx.ErrorCode + ", errorType=" + fbEx.ErrorType + ", message=" + fbEx.Message);
                HangoutException hangoutException = new HangoutException("FACEBOOK EXCEPTION: " + fbEx.Message + ", Facebook ErrorCode: " + fbEx.ErrorCode + ", FbErrorType: " + fbEx.ErrorType);


                hangoutException.Source = fbEx.Source;
                throw hangoutException;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Facebook did not return any useful information or invalid xml " + ex.Message, ex.InnerException);
            }
            accountMapping = ListHangoutAccountsForFbAccounts(fbAppUserFriendIds);

            XmlDocument friendsXml = GetAllFriendsXml(fbAccountId, facebookApi);

            xmlBuilder.Append(ConstructFriendData(friendsXml, accountMapping));

            return(new SimpleResponse("Friends", xmlBuilder.ToString()));
        }
        /// <summary>
        /// Get all friend data for users who ARE app users regardless of presence
        /// </summary>
        /// <param name="fbAccountId"></param>
        /// <param name="facebookApi"></param>
        /// <returns></returns>
        private XmlDocument GetAllFriendsWhoAreAppUsersXml(long fbAccountId, Api facebookApi)
        {
            string response = "";

            try
            {
                response = facebookApi.Fql.Query(
                    "SELECT " +
                    "birthday, birthday_date, email_hashes, first_name, has_added_app," +
                    "is_app_user, last_name, name, pic, pic_big," +
                    "pic_small, pic_square, sex, status, timezone, uid, online_presence " +
                    "FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='" + fbAccountId.ToString() + "') AND is_app_user='******';");
            }
            catch (FacebookException fbEx)
            {
                mServiceLog.Log.Error("Facebook Exception: errorcode=" + fbEx.ErrorCode + ", errorType=" + fbEx.ErrorType + ", message=" + fbEx.Message);
                HangoutException hangoutException = new HangoutException("FACEBOOK EXCEPTION: " + fbEx.Message + ", Facebook ErrorCode: " + fbEx.ErrorCode + ", FbErrorType: " + fbEx.ErrorType);


                hangoutException.Source = fbEx.Source;
                throw hangoutException;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Facebook did not return any useful information or invalid xml " + ex.Message, ex.InnerException);
            }

            XmlDocument friendsXml = new XmlDocument();

            try
            {
                friendsXml.LoadXml(response);
            }
            catch (XmlException xmlEx)
            {
                throw xmlEx;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return(friendsXml);
        }
Exemple #5
0
        /// <summary>
        /// CreateAccountFromFacebook checks first to see if there is an existing account for this fbUser.
        /// If a user exists it simply returns that user, otherwise it inserts a new user into the db
        /// and returns their information
        /// </summary>
        /// <param name="fbAccountId"></param>
        /// <param name="fbSessionKey"></param>
        /// <param name="nickName"></param>
        /// <param name="campaign"></param>
        /// ONLY ONE of the following should be sent.
        /// <param name="referringAccountId"></param>
        /// <param name="referringFbAccountId"></param>
        /// <param name="campaign"></param>
        /// <returns></returns>
        public SimpleResponse CreateAccountFromFacebook(long fbAccountId, string fbSessionKey, string nickName, string referringAccountId, string referringFbAccountId, string campaign)
        {
            mServiceLog.Log.InfoFormat("CreateAccountFromFacebook: fbAccountId={0}, fbSessionKey={1}, nickName={2}, referringAccountId={3}, referringFbAccountId={4}, campaign={5}", fbAccountId, fbSessionKey, nickName, referringAccountId, referringFbAccountId, campaign);

            FacebookSession facebookSession = new HangoutFacebookSession();

            facebookSession.ApplicationKey    = WebConfig.FacebookAPIKey;
            facebookSession.ApplicationSecret = WebConfig.FacebookSecret;
            facebookSession.SessionKey        = fbSessionKey;

            Api facebookApi = new Api(facebookSession);

            long currentFbUserId;

            Facebook.Schema.user fbUser;

            try
            {
                currentFbUserId = facebookApi.Users.GetLoggedInUser();
                fbUser          = facebookApi.Users.GetInfo(currentFbUserId);
            }
            catch (FacebookException fbEx)
            {
                mServiceLog.Log.Error("Facebook Exception: errorcode=" + fbEx.ErrorCode + ", errorType=" + fbEx.ErrorType + ", message=" + fbEx.Message);
                HangoutException hangoutException = new HangoutException("FACEBOOK EXCEPTION: " + fbEx.Message + ", Facebook ErrorCode: " + fbEx.ErrorCode + ", FbErrorType: " + fbEx.ErrorType);

                hangoutException.Source = fbEx.Source;
                throw hangoutException;
            }
            catch (System.Exception ex)
            {
                throw new Exception("Facebook did not return any useful information or invalid xml " + ex.Message, ex.InnerException);
            }



            if (!fbUser.is_app_user.GetValueOrDefault())
            {
                throw new Exception("is_app_user returned false");
            }

            if (fbAccountId != fbUser.uid)
            {
                throw new Exception("logged in facebook UID does not match fbAccountId parameter");
            }

            SimpleResponse selectResponse = GetAccounts(fbAccountId.ToString(), null, null, null, null, null);

            XmlNode accountNode = selectResponse.SelectSingleNode("//Account");

            if (accountNode != null)
            {
                XmlAttribute accountIdAttr = accountNode.Attributes["AccountId"];
                if (accountIdAttr != null && !String.IsNullOrEmpty(accountIdAttr.Value))
                {
                    return(selectResponse);
                }
            }
            //pass through and insert a new user... because the old user don't EXIST!!

            uint accountId = 0;

            using (MySqlConnection mysqlConnection = new MySqlConnection(WebConfig.AccountsDBConnectionString))
            {
                mysqlConnection.Open();

                string createNewHangoutUserQuery = "INSERT INTO LocalAccountInfo " +
                                                   " (FacebookAccountId, HangoutNickName, FirstName, LastName, Birthdate, Gender, CreatedDate, LastLoggedIn) " +
                                                   " VALUES (@FBAccountId, @HangoutNickName, @FirstName, @LastName, @Birthdate, @Gender, UTC_TIMESTAMP(), UTC_TIMESTAMP()); SELECT LAST_INSERT_ID();";

                using (MySqlCommand createAccountCommand = mysqlConnection.CreateCommand())
                {
                    createAccountCommand.CommandText = createNewHangoutUserQuery;
                    createAccountCommand.Parameters.AddWithValue("@FBAccountId", fbAccountId);
                    createAccountCommand.Parameters.AddWithValue("@HangoutNickName", fbUser.first_name);
                    createAccountCommand.Parameters.AddWithValue("@FirstName", fbUser.first_name);
                    createAccountCommand.Parameters.AddWithValue("@LastName", fbUser.last_name);
                    createAccountCommand.Parameters.AddWithValue("@Birthdate", fbUser.birthday_date.ToShortDateString());
                    createAccountCommand.Parameters.AddWithValue("@Gender", fbUser.sex);


                    accountId = Convert.ToUInt32(createAccountCommand.ExecuteScalar());
                    if (accountId == 0)
                    {
                        throw new Exception("AccountId returned 0");
                    }
                }

                InsertReferralData(accountId.ToString(), referringAccountId, referringFbAccountId, campaign);
            }

            return(GetAccounts(null, accountId.ToString(), null, null, null, null));
        }
Exemple #6
0
        private void ExecuteInAppDomain(Type T, int roomCatalogId, HttpContext context, string verb, MemoryStream GetValueCollectionStream, HttpCookieCollection cookieCollection)
        {
            try
            {
                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "INFO", String.Format("ExecuteInAppDomain roomCatalogId: {0} Verb: {1}", roomCatalogId, verb));

                AppDomain appDomain = appRoomCatalog.GetCatalogAppDomain(roomCatalogId.ToString());
                if (appDomain == null)
                {
                    appDomain = CreateAppDomain(roomCatalogId);
                }

                if (appDomain == null)
                {
                    throw new SystemException(String.Format("CreateAppDomain roomCatalogId: {0} Error: appDomain is null", roomCatalogId));
                }

                //hangoutCookies
                HangoutCookiesCollection oCookies = new HangoutCookiesCollection();
                oCookies.InitCookies(context.Request.Cookies);
                appDomain.SetData("AppCookies", oCookies);

                HangoutPostedFile oFile = new HangoutPostedFile();
                if (context.Request.Files.Count > 0)
                {
                    oFile.InitPostedFile(context.Request.Files[0]);
                }
                appDomain.SetData("PostedFile", oFile);

                AppErrorInformation oErrorInfo = new AppErrorInformation();
                oErrorInfo.RequestType     = context.Request.RequestType;
                oErrorInfo.URL             = context.Request.Url.ToString();
                oErrorInfo.UserHostAddress = context.Request.UserHostAddress;
                oErrorInfo.Timestamp       = context.Timestamp;
                oErrorInfo.MachineName     = Dns.GetHostName().ToString();
                appDomain.SetData("AppErrorInfo", oErrorInfo);

                mServiceLog.Log.Debug("ExecuteInAppDomain (create instance of ) (" + verb + ")");
                AppRestHandler mbrt = (AppRestHandler)appDomain.CreateInstanceAndUnwrap("AppService", "Hangout.Server.WebServices.AppService.AppRestHandler");

                mServiceLog.Log.Debug("ExecuteInAppDomain (process request through specific dll) (" + verb + ")");
                //Specified room catalog of 1 for the data  if we branch db this needs to change to be the roomCatalogId.
                MemoryStream outputStream = mbrt.ProcessRequest(T, verb, 1, GetValueCollectionStream);

                Session.Refresh();
                mServiceLog.Log.Debug("ExecuteInAppDomain (sending response) (" + verb + ")");
                // serialize the response based on the methods return type
                context.Response.OutputStream.Write(outputStream.GetBuffer(), 0, (int)outputStream.Length);

                // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                // string sTemp = enc.GetString(outputStream.GetBuffer());
            }

            catch (System.Exception ex)
            {
                if (ex.GetType() == typeof(TargetInvocationException))
                {
                    ex = ex.InnerException;
                }

                bool debugMode = (ConfigurationManager.AppSettings["DebugMode"] == "true") ? true : false;

                HangoutException hangoutException = ex as HangoutException;
                if (hangoutException == null)
                {
                    hangoutException = new HangoutException(ex);
                }

                RESTerror e = hangoutException.GetRestError(debugMode);

                // Add additional debug information
                hangoutException.RequestType = context.Request.RequestType;
                hangoutException.RequestUrl  = context.Request.Url.ToString();
                hangoutException.ClientIp    = context.Request.UserHostAddress;
                hangoutException.TimeStamp   = context.Timestamp;
                hangoutException.MachineName = Dns.GetHostName().ToString();
                if (Session.GetCurrentUserId() != null)
                {
                    hangoutException.CurrentUserId = Session.GetCurrentUserId().Id;
                }

                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "ERROR", String.Format("RequestUrl: {0} User: {1}", context.Request.Url.ToString(), hangoutException.CurrentUserId), ex);

                // Handle exception through exception handling application block.
                //ExceptionPolicy.HandleException(hangoutException, "Global Policy");

                //context.Response.StatusCode = 404;
                new XmlSerializer(typeof(RESTerror)).Serialize(context.Response.OutputStream, e);
                return;
            }

            //   finally
            //  {
            //    AppDomain.Unload(appDomain);
            // }
        }
Exemple #7
0
        public void DoProcessRequest(HttpContext context, string verb)
        {
            try
            {
                // find the method using the verb name
                // TODO: add argIndex test to make sure it is argIndex static method
                MethodInfo methodInfo = typeof(T).GetMethod(verb);
                if (methodInfo == null)
                {
                    throw new ArgumentException("Service verb could not be found: " + verb);
                }
                // loop though each parameter in the method and look for argIndex corresponding
                // query parameter in the REST request URL.
                string   argString = "";
                string   delimiter = "";
                int      numArgs   = methodInfo.GetParameters().Length;
                object[] args      = new object[numArgs];
                for (int argIndex = 0; argIndex < numArgs; argIndex++)
                {
                    ParameterInfo parameterInfo = methodInfo.GetParameters()[argIndex];

                    if (parameterInfo.ParameterType == typeof(int))
                    {
                        string arg = Util.GetHttpValue(parameterInfo.Name);
                        int    p   = Int32.Parse(arg);
                        args[argIndex] = p;
                        argString     += delimiter + parameterInfo.Name + "=" + Util.GetHttpValue(parameterInfo.Name);
                        delimiter      = "; ";
                    }
                    else if (parameterInfo.ParameterType == typeof(long))
                    {
                        string arg = Util.GetHttpValue(parameterInfo.Name);
                        long   p   = Int64.Parse(arg);
                        args[argIndex] = p;
                        argString     += delimiter + parameterInfo.Name + "=" + Util.GetHttpValue(parameterInfo.Name);
                        delimiter      = "; ";
                    }
                    else if (parameterInfo.ParameterType == typeof(uint))
                    {
                        string arg = Util.GetHttpValue(parameterInfo.Name);
                        uint   p   = UInt32.Parse(arg);
                        args[argIndex] = p;
                        argString     += delimiter + parameterInfo.Name + "=" + Util.GetHttpValue(parameterInfo.Name);
                        delimiter      = "; ";
                    }
                    else if (parameterInfo.ParameterType == typeof(string))
                    {
                        args[argIndex] = Util.GetHttpValue(parameterInfo.Name);
                        argString     += delimiter + parameterInfo.Name + "=" + Util.GetHttpValue(parameterInfo.Name);
                        delimiter      = "; ";
                    }
                    else if (parameterInfo.ParameterType == typeof(HangoutPostedFile))
                    {
                        HangoutPostedFile oFile = new HangoutPostedFile();
                        oFile.InitPostedFile(context.Request.Files[parameterInfo.Name]);
                        args[argIndex] = oFile;
                    }
                    else if (parameterInfo.ParameterType == typeof(Session.UserId))
                    {
                        Session.UserId userId;
                        string         stringUserId = Util.GetHttpValue("userId");
                        if (stringUserId == null)
                        {
                            userId = Session.GetCurrentUserId();
                            if (userId == null)
                            {
                                throw new UserNotLoggedin("No user session active and userId not provided.");
                            }
                        }
                        else
                        {
                            int intUserId = System.Convert.ToInt32(stringUserId);
                            userId = new Session.UserId(intUserId);
                        }
                        args[argIndex] = userId;
                    }
                    //else if (parameterInfo.ParameterType == typeof(RoomCatalog)) {
                    //    args[argIndex] = RestUrl.version;

                    //}
                    else if (parameterInfo.ParameterType == typeof(HangoutCookiesCollection))
                    {
                        HangoutCookiesCollection oCookies = new HangoutCookiesCollection();
                        oCookies.InitCookies(context.Request.Cookies);
                        args[argIndex] = oCookies;
                    }
                    else
                    {
                        throw new ArgumentException("unsupported argument type");
                    }
                }
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("DoProcessRequest (Invoke Method) (" + methodInfo.ReflectedType.Name + ")(" + verb + ") args: " + argString);
                }
                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "INFO", String.Format("Noun: {0} Verb: {1}", methodInfo.ReflectedType.Name, verb));
                T      instance         = Activator.CreateInstance <T>();
                object reflectionObject = methodInfo.Invoke(instance, args);

                // refresh the session if it has one
                Session.Refresh();

                // serialize the response based on the methods return type
                new XmlSerializer(methodInfo.ReturnType).Serialize(context.Response.OutputStream, reflectionObject);
                Globals.RemoveCurrentRestRequest();
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("---- Current RestService Requests: " + Globals.GetCurrentRestRequests);
                }
                return;
            }
            catch (System.Exception ex)
            {
                if (ex.GetType() == typeof(TargetInvocationException))
                {
                    ex = ex.InnerException;
                }

                bool debugMode = (ConfigurationManager.AppSettings["DebugMode"] == "true") ? true : false;

                HangoutException hangoutException = ex as HangoutException;
                if (hangoutException == null)
                {
                    hangoutException = new HangoutException(ex);
                }

                RESTerror e = hangoutException.GetRestError(debugMode);

                // Add additional debug information
                hangoutException.RequestType = context.Request.RequestType;
                hangoutException.RequestUrl  = context.Request.Url.ToString();
                hangoutException.ClientIp    = context.Request.UserHostAddress;
                hangoutException.TimeStamp   = context.Timestamp;
                hangoutException.MachineName = Dns.GetHostName().ToString();
                if (Session.GetCurrentUserId() != null)
                {
                    hangoutException.CurrentUserId = Session.GetCurrentUserId().Id;
                }
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("DoProcessRequest (HangoutException) (" + verb + "): " +
                                          "RequestType: " + hangoutException.RequestType +
                                          "RequestUrl: " + hangoutException.RequestUrl +
                                          "ClientIp: " + hangoutException.ClientIp +
                                          "TimeStamp: " + hangoutException.TimeStamp +
                                          "MachineName: " + hangoutException.MachineName
                                          );
                }
                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "ERROR", String.Format("RequestUrl: {0} User: {1}", context.Request.Url.ToString(), hangoutException.CurrentUserId), ex);

                // Handle exception through exception handling application block.
                // TODO: lucas commented this out... eventually we'll figure out if this needs to be in here
                //ExceptionPolicy.HandleException( hangoutException, "Global Policy" );

                context.Response.StatusCode = 500;
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("DoProcessRequest (ErrorMessage) (" + verb + "): " + e.ErrorMessage);
                }
                new XmlSerializer(typeof(RESTerror)).Serialize(context.Response.OutputStream, e);
                Globals.RemoveCurrentRestRequest();
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("---- Current RestService Requests: " + Globals.GetCurrentRestRequests);
                }
                return;
            }
        }
Exemple #8
0
        /*  Specifing the lease time is not used for now.
         *  If needed then remove the comments from the below code.
         *  and set the lease times.
         * /*  public override object  InitializeLifetimeService()
         * {
         *    ILease lease = (ILease)base.InitializeLifetimeService();
         *    if (lease.CurrentState == LeaseState.Initial)
         *    {
         *        lease.InitialLeaseTime = TimeSpan.FromMinutes(5);
         *        lease.SponsorshipTimeout = TimeSpan.FromSeconds(10);
         *        lease.RenewOnCallTime = TimeSpan.FromMinutes(2);
         *    }
         *    return lease;
         * } */

        public MemoryStream ProcessRequest(Type T, string verb, int roomCatalogId, MemoryStream GetValueCollectionStream)
        {
            MemoryStream returnStream = new MemoryStream();

            try
            {
                Dictionary <string, HangoutCookie> cookieCollection = _cookieCollection.CookieCollection;

                BinaryFormatter     formatter = new BinaryFormatter();
                NameValueCollection vars      = formatter.Deserialize(GetValueCollectionStream) as NameValueCollection;

                // find the method using the verb name
                // TODO: add argIndex test to make sure it is argIndex static method
                MethodInfo methodInfo = T.GetMethod(verb);
                if (methodInfo == null)
                {
                    throw new ArgumentException("Service verb could not be found: " + verb);
                }
                // loop though each parameter in the method and look for argIndex corresponding
                // query parameter in the REST request URL.
                int      numArgs = methodInfo.GetParameters().Length;
                object[] args    = new object[numArgs];
                for (int argIndex = 0; argIndex < numArgs; argIndex++)
                {
                    ParameterInfo parameterInfo = methodInfo.GetParameters()[argIndex];
                    if (parameterInfo.ParameterType == typeof(int))
                    {
                        string arg = GetHttpValue(vars, parameterInfo.Name);
                        int    p   = Int32.Parse(arg);
                        args[argIndex] = p;
                    }
                    else if (parameterInfo.ParameterType == typeof(string))
                    {
                        args[argIndex] = GetHttpValue(vars, parameterInfo.Name);
                    }
                    else if (parameterInfo.ParameterType == typeof(HangoutPostedFile))
                    {
                        args[argIndex] = _oFile;
                    }
                    else if (parameterInfo.ParameterType == typeof(Session.UserId))
                    {
                        Session.UserId userId;
                        string         stringUserId = GetHttpValue(vars, "userId");
                        if (stringUserId == null)
                        {
                            userId = Session.GetCurrentUserId(cookieCollection);
                            if (userId == null)
                            {
                                throw new UserNotLoggedin("No user session active and userId not provided.");
                            }
                        }
                        else
                        {
                            int intUserId = System.Convert.ToInt32(stringUserId);
                            userId = new Session.UserId(intUserId);
                        }
                        args[argIndex] = userId;
                    }
                    //else if (parameterInfo.ParameterType == typeof(RoomCatalog)) {
                    //    args[argIndex] = new RoomCatalog(roomCatalogId);
                    //}
                    else if (parameterInfo.ParameterType == typeof(HangoutCookiesCollection))
                    {
                        args[argIndex] = _cookieCollection;
                    }
                    else
                    {
                        throw new ArgumentException("unsupported argument type");
                    }
                }

                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "INFO", String.Format("Noun: {0} Verb: {1}", methodInfo.ReflectedType.Name, verb));

                object reflectionObject = methodInfo.Invoke(null, args);

                new XmlSerializer(methodInfo.ReturnType).Serialize(returnStream, reflectionObject);

                // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                // string sTemp = enc.GetString(returnStream.GetBuffer());

                return(returnStream);
            }

            catch (System.Exception ex)
            {
                if (ex.GetType() == typeof(TargetInvocationException))
                {
                    ex = ex.InnerException;
                }

                bool debugMode = (ConfigurationManager.AppSettings["DebugMode"] == "true") ? true : false;

                HangoutException hangoutException = ex as HangoutException;
                if (hangoutException == null)
                {
                    hangoutException = new HangoutException(ex);
                }

                RESTerror e = hangoutException.GetRestError(debugMode);

                hangoutException.RequestType = _ErrorInfo.RequestType;
                hangoutException.RequestUrl  = _ErrorInfo.URL;
                hangoutException.ClientIp    = _ErrorInfo.UserHostAddress;
                hangoutException.TimeStamp   = _ErrorInfo.Timestamp;
                hangoutException.MachineName = _ErrorInfo.MachineName;

                Dictionary <string, HangoutCookie> cookieCollection = _cookieCollection.CookieCollection;
                Session.UserId userId = Session.GetCurrentUserId(cookieCollection);
                if (userId != null)
                {
                    hangoutException.CurrentUserId = userId.Id;
                }

                //Log4NetHandler logger = new Log4NetHandler();
                //logger.SendToLogger("RESTService", "ERROR", String.Format("RequestUrl: {0} User: {1}", _ErrorInfo.URL, hangoutException.CurrentUserId), ex);

                // Handle exception through exception handling application block.
                ExceptionPolicy.HandleException(hangoutException, "Global Policy");

                //context.Response.StatusCode = 404;
                new XmlSerializer(typeof(RESTerror)).Serialize(returnStream, e);

                return(returnStream);
            }
        }