Пример #1
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;
            }
        }
Пример #2
0
        /// <summary>
        /// Process a REST Service call
        /// </summary>
        /// <param name="restCommand">RESTCommand</param>
        /// <returns>xml string containing the response</returns>
        public string ProcessRestService(RESTCommand restCommand)
        {
            Globals.AddCurrentRemotingRequest();
            if (mDebugMode)
            {
                mServiceLog.Log.Debug("Total Remoting Service Requests: " + Globals.GetTotalRemotingRequests);
            }
            mServiceLog.Log.Debug("++++ Current Remoting Service Requests: " + Globals.GetCurrentRemotingRequests);
            string response = "";

            try
            {
                Type commandClassType = GetCommandClassType(restCommand.Noun);

                if (commandClassType == null)
                {
                    throw new ArgumentException("Service noun could not be found: " + restCommand.Noun);
                }

                MethodInfo methodInfo = commandClassType.GetMethod(restCommand.Verb);

                if (methodInfo == null)
                {
                    throw new ArgumentException("Service verb could not be found: " + restCommand.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];
                    argString += delimiter + parameterInfo.Name + "=" + Util.GetHttpValue(parameterInfo.Name);
                    delimiter  = "; ";
                    if (parameterInfo.ParameterType == typeof(int))
                    {
                        string arg = GetParameterValue(restCommand.Parameters, parameterInfo.Name);
                        int    p   = Int32.Parse(arg);
                        args[argIndex] = p;
                    }
                    else if (parameterInfo.ParameterType == typeof(string))
                    {
                        args[argIndex] = GetParameterValue(restCommand.Parameters, parameterInfo.Name);
                    }
                    else if (parameterInfo.ParameterType == typeof(PostFile))
                    {
                        PostFile postFile = new PostFile();
                        postFile       = restCommand.PostFile;
                        args[argIndex] = postFile;
                    }
                    else if (parameterInfo.ParameterType == typeof(Session.UserId))
                    {
                        string         stringUserId = GetParameterValue(restCommand.Parameters, "userId");
                        int            intUserId    = System.Convert.ToInt32(stringUserId);
                        Session.UserId userId       = new Session.UserId(intUserId);
                        args[argIndex] = userId;
                    }
                    else if (parameterInfo.ParameterType == typeof(RESTCommand))
                    {
                        args[argIndex] = restCommand;
                    }
                    else
                    {
                        throw new ArgumentException("unsupported argument type");
                    }
                }
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("ProcessRestService (remoting)(Invoke Method) (" + restCommand.Noun + ")(" + restCommand.Verb + ") args: " + argString);
                }
                Object invokeParam1 = Activator.CreateInstance(commandClassType);

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

                StringWriterWithEncoding            stringWriter  = new StringWriterWithEncoding(Encoding.UTF8);
                XmlTextWriterFormattedNoDeclaration xmlTextWriter = new XmlTextWriterFormattedNoDeclaration(stringWriter);

                new XmlSerializer(methodInfo.ReturnType).Serialize(xmlTextWriter, reflectionObject);
                Globals.RemoveCurrentRemotingRequest();
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("---- Current Remoting Service Requests: " + Globals.GetCurrentRemotingRequests);
                }
                response = stringWriter.ToString();
            }

            catch (Exception ex)
            {
                Globals.RemoveCurrentRemotingRequest();
                if (mDebugMode)
                {
                    mServiceLog.Log.Debug("---- Current Remoting Service Requests: " + Globals.GetCurrentRemotingRequests);
                }
                mServiceLog.Log.Error("ProcessRequest (remoting) ERROR:" + ex.Message);
                //logError("ProcessRequest", ex);
                //response = CreateErrorDoc(ex.Message);
            }

            return(response);
        }
Пример #3
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);
            }
        }