コード例 #1
0
ファイル: BoxServer.cs プロジェクト: BryanApellanes/Naizari
 private static void SendBoxedError(HttpContext context, Exception ex)
 {
     JsonResult result = new JsonResult();
     if (ex.InnerException != null)
         ex = ex.InnerException;
     result.ErrorMessage = ex.Message;
     result.StackTrace = ex.StackTrace;
     result.Status = JsonResultStatus.Error;
     SendBoxedError(context.Response, result);
 }
コード例 #2
0
ファイル: BoxServer.cs プロジェクト: BryanApellanes/Naizari
 /// <summary>
 /// Sets the status of the specified JsonResult to JsonResultStatus.Error and
 /// sends the error message to the client in a div.  This is used to 
 /// respond to "DataBox" requests that fail due to an exception.
 /// </summary>
 /// <param name="response">The HttpResponse object to be used to send the error.</param>
 /// <param name="jsonResult">The JsonResult to box the error for.</param>
 public static void SendBoxedError(HttpResponse response, JsonResult jsonResult)
 {
     LogManager.CurrentLog.AddEntry("An error occurred fulfilling a box request: {0}\r\n{1}", LogEventType.Error, jsonResult.ErrorMessage, jsonResult.StackTrace);
     jsonResult.Status = JsonResultStatus.Error;
     string html = "<div class='error'>An error occurred fulfilling the request, we apologize for the inconvenience please try again shortly (";
     html += jsonResult.ErrorMessage + ").</br>";
     #if DEBUG
     html += jsonResult.StackTrace + "</br>";
     #endif
     html += "</div>";
     response.Clear();
     response.Write(html);
     response.Flush();
     response.SuppressContent = true;
     HttpContext.Current.ApplicationInstance.CompleteRequest();
     //response.End();
 }
コード例 #3
0
ファイル: BoxServer.cs プロジェクト: BryanApellanes/Naizari
        /// <summary>
        /// This method will send the "ConglomerateScript" for the specified templateName.
        /// </summary>
        /// <remarks>A ConglomerateScript represents all the scripts required by the JsonControls
        /// in an ascx file.   The BoxUserControl class prepares the resulting ascx control for 
        /// Json/Box rendering.</remarks>
        /// <param name="context">The HttpContext significant to the current request.</param>
        /// <param name="templateName">The name of an ascx file contained in the 
        /// BoxServer.BoxTemplateDirectory or the virutal path to an ascx file.</param>
        /// <returns></returns>
        //public static void SendBoxScriptResponse(HttpContext context, string templateName)
        //{
        //    string virtualBoxPath = GetVirtualBoxPath(context, templateName);
        //    try
        //    {
        //        if (string.IsNullOrEmpty(virtualBoxPath))
        //            throw new InvalidOperationException("The box template could not be found: [" + templateName + "]");
        //        string requesterId = context.Request.QueryString["domid"];
        //        HttpResponse response = context.Response;
        //        //string responseString = BoxServer.GetScriptString(virtualBoxPath, requesterId);
        //        //GetDataBoxResponse(context, virtualBoxPath, null);
        //        response.Clear();
        //        response.Write(responseString);
        //        response.Flush();
        //        response.SuppressContent = true;
        //        context.ApplicationInstance.CompleteRequest();
        //    }
        //    catch (Exception ex)
        //    {
        //        SendBoxedError(context, ex);
        //    }
        //}
        /// <summary>
        /// Applies a template to the Data property of the specified JsonResult object 
        /// and sends the result to the client as an html section or "Box".
        /// </summary>
        /// <param name="context">The HttpContext</param>
        /// <param name="jsonResult">The result to be Boxed</param>
        public static void SendDataBoxResponse(HttpContext context, JsonResult jsonResult)
        {
            #region check JsonResult
            HttpResponse response = context.Response;

            // Check the status of the jsonResult
            // if status is error send default error box
            if (jsonResult.Status == JsonResultStatus.Error)
            {
                SendBoxedError(response, jsonResult);
                return;
            }

            if (jsonResult.Data == null)
            {
                SendBoxedError(response, jsonResult);
                return;
            }
            #endregion

            HttpRequest request = context.Request;

            string boxTemplateName = request.QueryString["dbx"];// TODO: create enums to represent all the magic strings used by the different script components
            string clientKey = request.QueryString["ck"];
            if (string.IsNullOrEmpty(boxTemplateName))
            {
                SendBoxedError(response, jsonResult);
                return;
            }

            object[] objectsToTemplate = new object[] { jsonResult.Data };
            if (jsonResult.Data is Array)
                objectsToTemplate = (object[])jsonResult.Data;

            BoxResponses responses = SingletonHelper.GetApplicationProvider<BoxResponses>();
            string allHtml = string.Empty;
            string allScript = string.Empty;
            try
            {
                foreach (object objectToTemplate in objectsToTemplate)
                {
                    // getting the property variables for each object will allow objects of different types to
                    // be templated in one pass.  This incurs some processing overhead but the flexibility is
                    // worth it.
                    string[] propertyVariables = GetPropertyVariables(objectToTemplate.GetType());
                    string virtualBoxPath = GetVirtualDataBoxPath(context, objectToTemplate.GetType(), boxTemplateName);
                    if (string.IsNullOrEmpty(virtualBoxPath))
                        SendBoxedError(context, ExceptionHelper.CreateException<JsonInvalidOperationException>("Unable to find specified data box template ['{0}.{1}']", objectToTemplate.GetType().Name, boxTemplateName));

                    BoxResponse dataBoxResponse = GetBoxResponse(context, virtualBoxPath, objectToTemplate, true);
                    string html = dataBoxResponse.Html;
                    string script = dataBoxResponse.Script;

                    allHtml += GetVariableReplaceText(html, propertyVariables, objectToTemplate);
                    allScript += GetVariableReplaceText(script, propertyVariables, objectToTemplate);
                }
            }
            catch (Exception ex)
            {
                SendBoxedError(context, ex);
            }

            responses.Add(clientKey, new BoxResponse(allHtml, allScript));

            response.Clear();
            response.Write(allHtml);
            response.Flush();
            response.SuppressContent = true;

            HttpContext.Current.ApplicationInstance.CompleteRequest();
            //response.End();
        }
コード例 #4
0
        private static JsonResult GetJsonResultFromInvoke(string typeName, string methodName, string[] parameters)
        {
            Expect.IsNotNullOrEmpty(typeName, "typeName not specified");
            Expect.IsNotNullOrEmpty(methodName, "methodName not specified");
            JsonResult ret = new JsonResult();

            ret.Status = JsonResultStatus.Unknown;
            ret.Input  = parameters;
            if (HttpContext.Current == null)
            {
                ret.Status = JsonResultStatus.Error;
                ret.Data   = NewInvalidOperationException();
            }
            else
            {
                object handler = GetInstance(typeName);//HttpContext.Current.Session[typeName.ToLowerInvariant()];
                if (handler == null)
                {
                    ret.Status = JsonResultStatus.Error;
                    ret.Data   = new Exception("The specified type was not registered to handle json requests");
                }
                else
                {
                    MethodInfo[] methods = handler.GetType().GetMethods();
                    foreach (MethodInfo method in methods)
                    {
                        JsonMethod jsonMethodAttribute = null;
                        if (!CustomAttributeExtension.HasCustomAttributeOfType <JsonMethod>(method, out jsonMethodAttribute))
                        {
                            continue;
                        }

                        if (method.Name.ToLowerInvariant().Equals(methodName.ToLowerInvariant()))
                        {
                            try
                            {
                                switch (jsonMethodAttribute.Verb)
                                {
                                case Verbs.GET:
                                    ret.Data   = method.Invoke(handler, (object[])parameters);
                                    ret.Status = JsonResultStatus.Success;
                                    break;

                                case Verbs.POST:
                                    ParameterInfo[] parameterInfos = method.GetParameters();
                                    string[]        jsonParameters = null;
                                    using (StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream))
                                    {
                                        string inputString = sr.ReadToEnd();
                                        jsonParameters = StringExtensions.DelimitSplit(inputString, ParameterDelimiter);
                                    }

                                    if (jsonParameters.Length != parameterInfos.Length)
                                    {
                                        ExceptionHelper.Throw <JsonInvalidOperationException>("Parameter count mismatch in call to method {0}, required {1} parameters received {2}", method.Name, parameterInfos.Length, jsonParameters.Length);
                                    }


                                    List <object> parameterList = new List <object>();
                                    for (int i = 0; i < parameterInfos.Length; i++)
                                    {
                                        ParameterInfo parameterInfo = parameterInfos[i];
                                        Serializer    serializer    = new Serializer(parameterInfo.ParameterType);
                                        parameterList.Add(serializer.Deserialize(jsonParameters[i]));
                                    }

                                    ret.Data   = method.Invoke(handler, parameterList.ToArray());
                                    ret.Status = JsonResultStatus.Success;
                                    ret.Input  = jsonParameters;
                                    break;
                                }

                                break;
                            }
                            catch (Exception ex)
                            {
                                string parms = parameters != null?StringExtensions.ToDelimited(parameters, ",") : "";

                                LogManager.CurrentLog.AddEntry("An error occurred during Javascript Method Invokation: typeName={0};methodName={1};parameters={2}", ex, typeName, methodName, parms);
                                if (ex.InnerException != null)
                                {
                                    ex = ex.InnerException;
                                }
                                ret.Status       = JsonResultStatus.Error;
                                ret.Data         = ex.Message;
                                ret.ErrorMessage = ex.Message;
#if DEBUG
                                ret.StackTrace = ex.StackTrace;
#endif
                                break;
                            }
                        }
                    }
                }
            }

            return(ret);
        }