示例#1
0
        public void GenericExceptionWithSingleParameterTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("File", "c:/home.txt");

            Assert.IsTrue(e.Message == "It went wrong");
            Assert.IsTrue(e.ToString() == "It went wrong... File: c:/home.txt");
        }
示例#2
0
        public void GenericExceptionPresentDataAccessTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("File", "c:/home.txt").With("Next", "Fred");

            Assert.IsTrue(e.Data.Count == 2);
            Assert.IsTrue((string)e.Data["File"] == "c:/home.txt");
        }
示例#3
0
        public void GenericExceptionWithNumberParameterTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Count", 5);

            Assert.IsTrue(e.Message == "It went wrong");
            Assert.IsTrue(e.ToString() == "It went wrong... Count: 5");
        }
示例#4
0
        public void GenericExceptionWithTwoParametersTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("File", "c:/home.txt").With("Next", "Fred");

            Assert.IsTrue(e.Message == "It went wrong");
            Assert.IsTrue(e.ToString() == "It went wrong... File: c:/home.txt; Next: Fred" || e.ToString() == "It went wrong.. Next: Fred; File: c:/home.txt");
        }
示例#5
0
        public void GenericExceptionBasicExceptionTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong");

            Assert.IsTrue(e.Id == GenericException.NullError);
            Assert.IsTrue(e.Message == "It went wrong");
            Assert.IsTrue(e.ToString() == "It went wrong");
        }
示例#6
0
 public static void Main()
 {
     Mechanics.SomeMethod();
     GenericException.Go();
     OneStatementDemo.Go();
     CodeContracts.Go();
     //UnhandledException.Go();
     ConstrainedExecutionRegion.Go();
 }
        public override Exception HandlerException(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Exception exception)
        {
            //if (exception is GenericException)
            //    exception = exception;

            if (exception is WebFaultException<ExceptionDetail>)
                throw exception;

            if (!(exception is GenericException))
                exception = new GenericException(exception);

            ExceptionDetail detail = new ExceptionDetail(exception);

            var result = new WebFaultException<ExceptionDetail>(detail, HttpStatusCode.BadRequest);
            throw result;
        }
        public override Exception HandlerException(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Exception exception)
        {
            if (exception is WebFaultException <ExceptionDetail> )
            {
                string note = FormmatException(exception.StackTrace, exception.Message);
                ExceptionLog.Write(note);
                throw exception;
            }
            if (!(exception is GenericException))
            {
                exception = new GenericException(exception);
                string notepad = FormmatException(exception.StackTrace, exception.Message);
                ExceptionLog.Write(notepad);
            }
            ExceptionDetail detail = new ExceptionDetail(exception);

            var result = new WebFaultException <ExceptionDetail>(detail, HttpStatusCode.BadRequest);

            throw result;
        }
示例#9
0
        //
        //====================================================================================================
        /// <summary>
        /// Execute a command or sql statemwent and return a dataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="dataSourceName"></param>
        /// <param name="startRecord"></param>
        /// <param name="maxRecords"></param>
        /// <returns></returns>
        private DataTable executeQuery(string sql)
        {
            DataTable returnData = new DataTable();

            try {
                using (SqlConnection connSQL = new SqlConnection(getConnectionStringADONET())) {
                    connSQL.Open();
                    using (SqlCommand cmdSQL = new SqlCommand()) {
                        cmdSQL.CommandType = CommandType.Text;
                        cmdSQL.CommandText = sql;
                        cmdSQL.Connection  = connSQL;
                        using (dynamic adptSQL = new System.Data.SqlClient.SqlDataAdapter(cmdSQL)) {
                            adptSQL.Fill(returnData);
                        }
                    }
                }
            } catch (Exception ex) {
                ApplicationException newEx = new GenericException("Exception [" + ex.Message + "] executing master sql [" + sql + "]", ex);
                LogController.logError(core, newEx);
            }
            return(returnData);
        }
示例#10
0
        public override Exception HandlerException(Microsoft.Practices.Unity.InterceptionExtension.IMethodInvocation input, Exception exception)
        {
            //if (exception is GenericException)
            //    exception = exception;

            if (exception is WebFaultException <ExceptionDetail> )
            {
                throw exception;
            }

            if (!(exception is GenericException))
            {
                exception = new GenericException(exception);
            }

            ExceptionDetail detail = new ExceptionDetail(exception);


            var result = new WebFaultException <ExceptionDetail>(detail, HttpStatusCode.BadRequest);

            throw result;
        }
        public ActionResult Index(string methodName, string rawInput)
        {
            if (string.IsNullOrEmpty(methodName))
            {
                return(new EmptyResult());
            }

            if (Request.Browser.Crawler)
            {
                KernelContext.Log.Info("crawler:" + Request.UserAgent);

                return(Content(GenericException.Stringify(I18n.Exceptions["code_web_api_ban_search_engine_spider"],
                                                          I18n.Exceptions["text_web_api_ban_search_engine_spider"])));
            }

            // 限制 IP 访问频次 两个小时 500 次
            if (HttpRequestLimit.LimitIP())
            {
                return(Content(GenericException.Stringify(I18n.Exceptions["code_web_api_request_exceed_limit"],
                                                          I18n.Exceptions["text_web_api_request_exceed_limit"])));
            }

            DateTime timestamp = DateTime.Now;

            HttpContextBase context = this.HttpContext;

            IDictionary <string, APIMethod> dictionary = APIsConfigurationView.Instance.Configuration.APIMethods;

            string responseText = string.Empty;

            // 支持两种格式 connect/auth/authorize 和 connect.auth.authorize, 内部统一使用 connect.auth.authorize 格式
            if (methodName.IndexOf("/") > -1)
            {
                methodName = methodName.Replace("/", ".");
            }

            // 调试情况下记录输入参数
            if (context.Request.QueryString["xhr-debug"] == "1")
            {
                logger.Info("api:" + methodName + " start.");

                logger.Info(RequestHelper.Dump(context.Request, rawInput));
            }

            if (dictionary.ContainsKey(methodName))
            {
                // 优先执行 WebAPI 配置文件中设置的方法.
                responseText = APIHub.ProcessRequest(context, methodName, rawInput, logger, APIMethodInvoke);
            }
            else
            {
                // 匿名方法允许用户跳过验证直接访问
                // 应用方法信息
                ApplicationMethodInfo method = AppsContext.Instance.ApplicationMethodService.FindOneByName(methodName);

                if (method == null)
                {
                    logger.Warn(string.Format(I18n.Exceptions["text_web_api_method_not_exists"], methodName));

                    responseText = GenericException.Stringify(I18n.Exceptions["code_web_api_method_not_exists"],
                                                              string.Format(I18n.Exceptions["text_web_api_method_not_exists"], methodName));
                }
                else if (method.EffectScope == 1 || Authenticate(context, methodName))
                {
                    // 直接执行匿名方法 或者 验证需要身份验证方法

                    // 尝试执行 Application Method 中设置的方法.
                    responseText = APIHub.ProcessRequest(context, methodName, rawInput, logger, MethodInvoker.Invoke);
                }
                else
                {
                    responseText = "401";
                }
            }

            // 调试情况下记录输出参数
            if (context.Request.QueryString["xhr-debug"] == "1")
            {
                KernelContext.Log.Info("api " + methodName + " finished, timespan:" + DateHelper.GetTimeSpan(timestamp).TotalSeconds + "s.");

                KernelContext.Log.Info(responseText);
            }

            return(Content(responseText));
        }
示例#12
0
 public static string BriefErrorDescription(GenericException genericException) => genericException.Description;
示例#13
0
        public void GenericExceptionIsNamespaceTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Next", "Fred");

            Assert.IsTrue(e.IsNamespace(GenericException.ExceptionNamespace));
        }
示例#14
0
        public void GenericExceptionIndexParameterWithUnspecifiedValueTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Next", "Fred");

            Assert.IsTrue(e["Other"] == "<not-set>");
        }
示例#15
0
        public void GenericExceptionIndexParameterWithNumberTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Count", 5);

            Assert.IsTrue(e["Count"] == "5");
        }
示例#16
0
        public void GenericExceptionIndexParameterWithStringTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Next", "Fred");

            Assert.IsTrue(e["Next"] == "Fred");
        }
        /// <summary>处理请求</summary>
        public static string ProcessRequest(HttpContextBase context, string methodName, string rawInput, ILog logger, APIInvokeDelegate methodInvoke)
        {
            // 请求响应的内容
            string responseText = string.Empty;
            // clientId
            string clientId = RequestHelper.Fetch("clientId", new string[] { "client_id", "app_key", "appKey" });
            // accessToken
            string accessToken = RequestHelper.Fetch("accessToken", "access_token");
            // 默认支持 form-data 方式
            string xml = (context.Request.Form["xhr-xml"] == null) ? string.Empty : context.Request.Form["xhr-xml"];

            // 支持 application/xml 请求方式
            if (context.Request.ContentType.IndexOf("application/xml") > -1 && string.IsNullOrEmpty(xml) && !string.IsNullOrEmpty(rawInput))
            {
                xml = rawInput;
            }

            // 支持 application/json 请求方式
            if (context.Request.ContentType.IndexOf("application/json") > -1 && string.IsNullOrEmpty(xml) && !string.IsNullOrEmpty(rawInput))
            {
                XmlDocument xmlDoc = JsonHelper.ToXmlDocument(rawInput);

                xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<request>" + xmlDoc.DocumentElement.InnerXml + "</request>";
            }

            if (!string.IsNullOrEmpty(xml) || context.Request.QueryString.Count > 0 || (context.Request.HttpMethod == "POST" && context.Request.Form.Count > 0))
            {
                XmlDocument doc = new XmlDocument();

                if (string.IsNullOrEmpty(xml))
                {
                    doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<request></request>");
                }
                else
                {
                    doc.LoadXml(xml);
                }

                // 将 QueryString 中,除 xhr-name 外的所有参数转为统一的Xml文档的数据
                if (context.Request.QueryString.Count > 0)
                {
                    for (int i = 0; i < context.Request.QueryString.Count; i++)
                    {
                        if (string.IsNullOrEmpty(context.Request.QueryString.Keys[i]))
                        {
                            continue;
                        }

                        if (context.Request.QueryString.Keys[i] != "xhr-name" && context.Request.QueryString.Keys[i].IndexOf("[") == -1)
                        {
                            XmlElement element = doc.CreateElement(context.Request.QueryString.Keys[i]);

                            element.InnerText = context.Request.QueryString[i];

                            doc.DocumentElement.AppendChild(element);
                        }
                    }

                    doc = AnalyzePagingXml(doc, context.Request.QueryString);

                    doc = AnalyzeQueryXml(doc, context.Request.QueryString);
                }

                // 将表单中,除 xhr-name 和 xhr-xml 外的所有参数转为统一的Xml文档的数据
                if (context.Request.HttpMethod == "POST" && context.Request.Form.Count > 0)
                {
                    for (int i = 0; i < context.Request.Form.Count; i++)
                    {
                        if (string.IsNullOrEmpty(context.Request.Form.Keys[i]))
                        {
                            continue;
                        }

                        if (context.Request.Form.Keys[i] != "xhr-name" && context.Request.Form.Keys[i] != "xhr-xml" && context.Request.Form.Keys[i].IndexOf("[") == -1)
                        {
                            XmlElement element = doc.CreateElement(context.Request.Form.Keys[i]);

                            element.InnerText = context.Request.Form[i];

                            doc.DocumentElement.AppendChild(element);
                        }
                    }

                    doc = AnalyzeQueryXml(doc, context.Request.QueryString);
                }

                string clientTargetObject = XmlHelper.Fetch("clientTargetObject", doc);

                try
                {
                    // 记录
                    if (ConnectConfigurationView.Instance.EnableCallLog == "ON")
                    {
                        ConnectCallInfo call = new ConnectCallInfo(clientId, context.Request.RawUrl, string.IsNullOrEmpty(rawInput) ? doc.InnerXml : rawInput);

                        call.AccessToken = accessToken;

                        try
                        {
                            call.Start();

                            var responseObject = methodInvoke(methodName, doc, logger);

                            responseText = call.ResponseData = (responseObject == null) ? string.Empty : responseObject.ToString();

                            if (call.RequestData.Length > 2048)
                            {
                                call.RequestData = "[Long String] " + call.RequestData.Length;
                            }

                            if (call.ResponseData.Length > 2048)
                            {
                                call.ResponseData = "[Long String] " + call.ResponseData.Length;
                            }

                            call.ReturnCode = 0;
                        }
                        catch
                        {
                            call.ReturnCode = 1;

                            throw;
                        }
                        finally
                        {
                            call.Finish();

                            call.IP = IPQueryContext.GetClientIP();

                            ConnectContext.Instance.ConnectCallService.Save(call);
                        }
                    }
                    else
                    {
                        var responseObject = methodInvoke(methodName, doc, logger);

                        responseText = (responseObject == null) ? string.Empty : responseObject.ToString();
                    }

                    if (responseText.IndexOf("\"message\":") > -1 &&
                        !string.IsNullOrEmpty(clientTargetObject))
                    {
                        responseText = responseText.Insert(responseText.IndexOf("\"message\":"), "\"clientTargetObject\":\"" + clientTargetObject + "\",");
                    }
                }
                catch (GenericException genericException)
                {
                    responseText = genericException.ToString();
                }
                catch (ThreadAbortException threadAbortException)
                {
                    GenericException exception = new GenericException("9999", threadAbortException);

                    responseText = exception.ToString();
                }
                catch (Exception ex)
                {
                    GenericException exception = null;

                    if (ex.InnerException is GenericException)
                    {
                        exception = (GenericException)ex.InnerException;
                    }
                    else
                    {
                        exception = new GenericException("-1", ex);
                    }

                    responseText = exception.ToString();
                }
            }

            // JSONP
            string callback = context.Request["callback"];

            return(string.IsNullOrEmpty(callback)
                ? responseText
                : callback + "(" + responseText + ")");
        }
示例#18
0
        public void GenericExceptionIsClassTest()
        {
            var e = new GenericException(GenericException.NullError, "It went wrong").With("Next", "Fred");

            Assert.IsTrue(e.IsClass(GenericException.ExceptionClass));
        }