public override string Format(ResultBase result)
        {
            var r = result as ComparisonResult;

            var f = "{2:" + NumFormat + "}";
            var o1 = "{3:" + NumFormat + "}";
            var o2 = "{4:" + NumFormat + "}";
            var fmt = _hypothesisLabels[r.Hypothesis] + f + "ms. (Observed: " + o1 + " vs " + o2 + ")";
            string rv;

            if (!r.Significant)
            {
                if (r.HypothesizedDifference == 0)
                {
                    fmt = "Difference between {0} and {1} is not significant.";
                }
                else
                {
                    fmt = "Difference between {0} and {1} is not significant or is less than " + f + "ms. (Observed: " +
                          o1 + " vs " + o2 + ")";
                }
            }
            rv = String.Format(fmt, r.FirstSample.Name, r.SecondSample.Name, Math.Abs(r.HypothesizedDifference),
                r.FirstSample.Mean, r.SecondSample.Mean);
            return rv;
        }
        public override string Format(ResultBase result)
        {
            var r = result as DescriptiveResult;

            var sb = new StringBuilder();

            var formats = new string[3];

            for (int i = 0; i < 3; i++) formats[i] = "{" + String.Format("{0}", i) + ":" + NumFormat + "}";

            sb.AppendLine(String.Format("Summary,Samples,{0}", r.Count));
            sb.AppendLine(String.Format("Summary,Minimum," + formats[0], r.Min));
            sb.AppendLine(String.Format("Summary,Maximum," + formats[0], r.Max));
            sb.AppendLine(String.Format("Summary,Mean," + formats[0], r.Mean));
            sb.AppendLine(String.Format("Summary,Median," + formats[0], r.Median));
            sb.AppendLine(String.Format("Summary,StdDev," + formats[0], r.StdDev));

            sb.AppendLine(String.Format("Quartiles,First," + formats[0], r.FirstQuartile));
            sb.AppendLine(String.Format("Quartiles,Second," + formats[0], r.Median));
            sb.AppendLine(String.Format("Quartiles,Third," + formats[0], r.ThirdQuartile));

            for (int p = 0; p < 100; p++)
            {
                sb.AppendLine(String.Format("Percentiles,{0}," + formats[1], p, r.Percentile(p)));
            }

            if (r.Histogram != null)
            {
                foreach (var t in r.Histogram)
                {
                    sb.AppendLine(t.ToString(ResultFormat.cCsvFormat, NumFormat));
                }
            }
            return sb.ToString();
        }
        public override string Format(ResultBase result)
        {
            var r = result as ReliabilityResult;
            var numFormat = "{0:" + String.Format("N{0}", Precision) + "}%";
            var sb = new StringBuilder();

            sb.AppendLine(String.Format("Valid,{0}", r.IsValid));
            sb.AppendLine(String.Format("Count,{0}", (r.Passed + r.Failed)));
            sb.AppendLine(String.Format("Passed," + numFormat + ",{1}", r.PercentPassed, r.Passed));
            sb.AppendLine(String.Format("Failed," + numFormat + ",{1}", r.PercentFailed, r.Failed));

            return sb.ToString();
        }
        public override string Format(ResultBase result)
        {
            var sb = new StringBuilder();
            var r = result as ReliabilityResult;
            var numFormat = "{0:" + NumFormat + "}%";

            sb.AppendLine(String.Format("Valid: {0}", r.IsValid));
            sb.AppendLine(String.Format("Total Iterations: {0}", (r.Passed + r.Failed)));
            sb.AppendLine(String.Format("Passed: " + numFormat + " ({1})", r.PercentPassed, r.Passed));
            sb.AppendLine(String.Format("Failed: " + numFormat + " ({1})", r.PercentFailed, r.Failed));

            return sb.ToString();
        }
Exemplo n.º 5
0
        public JsonResult DeleteFile(string PrefixInfo)
        {
            ResultBase result = new ResultBase();

            //check is there are uploaded file.
            if (sessionData.trading.UploadFiles.Any(x => x.Key == PrefixInfo && x.Value != "DELETE"))
            {
                string filename = sessionData.trading.UploadFiles[PrefixInfo];
                if (System.IO.File.Exists(GetTempPathFileName(filename)))
                {
                    System.IO.File.Delete(GetTempPathFileName(filename));
                }
            }
            sessionData.trading.UploadFiles[PrefixInfo] = "DELETE";
            result.setMessage("檔案已刪除。");
            return(Json(result, JsonRequestBehavior.DenyGet));
        }
        public override string Format(ResultBase result)
        {
            var f = "{0:" + NumFormat + "}";
            var r = result as DescriptiveResult;
            var root = new XElement("PerformanceDetails");
            var summary = new XElement("Summary",
                new XElement("Samples", r.Count),
                new XElement("Minimum", String.Format(f, r.Min)),
                new XElement("Maximum", String.Format(f, r.Max)),
                new XElement("Mean", String.Format(f, r.Mean)),
                new XElement("Median", String.Format(f, r.Median)),
                new XElement("StdDev", String.Format(f, r.StdDev))
                );

            var quartiles = new XElement("Quartiles",
                new XElement("First", String.Format(f, r.FirstQuartile)),
                new XElement("Second", String.Format(f, r.Median)),
                new XElement("Third", String.Format(f, r.ThirdQuartile))
                );

            var pctiles = new XElement("Percentiles");

            for (int p = 0; p < 99; p++)
            {
                var pct = new XElement("Percentile",
                    new XAttribute("pct", p), String.Format(f, r.Percentile(p))
                    );
                pctiles.Add(pct);
            }

            root.Add(summary);
            root.Add(quartiles);
            root.Add(pctiles);

            if (r.Histogram != null)
            {
                var histogram = new XElement("Histogram",
                    from h in r.Histogram
                    select XElement.Parse(h.ToString(ResultFormat.cXmlFormat, f))
                    );

                root.Add(histogram);
            }

            return root.ToString();
        }
        public JsonResult Set(CourseSystem model)
        {
            if (model == null)
            {
                return(Error("参数错误。"));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Error("课程名称不能为空。"));
            }
            var fileAvatar = Request.Files["fileAvatar"];

            if (fileAvatar != null)
            {
                string uploadResult = UploadHelper.Process(fileAvatar.FileName, fileAvatar.InputStream);
                if (!string.IsNullOrEmpty(uploadResult))
                {
                    model.Picture = uploadResult;
                }
            }

            var fileBanner = Request.Files["fileBanner"];

            if (fileBanner != null)
            {
                string uploadResult = UploadHelper.Process(fileBanner.FileName, fileBanner.InputStream);
                if (!string.IsNullOrEmpty(uploadResult))
                {
                    model.BannerImg = uploadResult;
                }
            }
            var result = new ResultBase();

            if (model.Id > 0)
            {
                result.success = _courseSystemService.UpdateAsync(model);
            }
            else
            {
                result.success = _courseSystemService.InsertAsync(model);
            }

            return(Json(result));
        }
Exemplo n.º 8
0
        protected IHttpActionResult ProcessResult(ResultBase result)
        {
            if (!result.IsSuccess)
            {
                if (result.StatusCode != HttpStatusCode.BadRequest)
                {
                    var response = new HttpResponseMessage(result.StatusCode)
                    {
                        ReasonPhrase = result.Message
                    };
                    return(this.ResponseMessage(response));
                }

                return(this.BadRequest(result.Message));
            }

            return(this.Ok(result.Message));
        }
        public override string Format(ResultBase result)
        {
            var r = result as ReliabilityResult;
            var numFormat = "{0:" + String.Format("N{0}", Precision) + "}%";

            var root = new XElement("ReliabilityResult",
                new XElement("Valid", r.IsValid),
                new XElement("Count", (r.Passed + r.Failed)),
                new XElement("Passed",
                    new XElement("Count", r.Passed),
                    new XElement("Percent", String.Format(numFormat, r.PercentPassed))),
                new XElement("Failed",
                    new XElement("Count", r.Failed),
                    new XElement("Percent", String.Format(numFormat, r.PercentFailed)))
                );

            return root.ToString();
        }
Exemplo n.º 10
0
        public ActionResult VinRemove(string id)
        {
            id = HttpUtility.UrlDecode(id);
            var r = new ResultBase();

            if (string.IsNullOrEmpty(id))
            {
                r.Error("标识不正确,无法操作");
            }
            else
            {
                if (VinManager.DeleteVin_recordById(id) < 1)
                {
                    r.Error("删除失败");
                }
            }
            return(Content(r.ToJson()));
        }
Exemplo n.º 11
0
        public static void ParseResultBase(XDocument resultDocument, ResultBase resultBase)
        {
            if (resultDocument != null) {
                if (resultDocument.Descendants("error").Count() > 0) {
                    string errMsg = resultDocument.Descendants("error").ElementAt(0).Attribute("code").Value;
                    throw new ApplicationException(errMsg);
                }

                resultBase.ResultCode = resultDocument.Descendants("success").ElementAt(0).Attribute("code").Value;

                int remaingCount= -1;
                int.TryParse(resultDocument.Descendants("success").ElementAt(0).Attribute("remaining").Value,
                             out remaingCount);
                resultBase.RemainingMessageCount = remaingCount;

                resultBase.TimeStamp = resultDocument.Descendants("success").ElementAt(0).Attribute("resetdate").Value;
            }
        }
Exemplo n.º 12
0
        private ResultBase Invoke(Action action)
        {
            var result = new ResultBase();

            try
            {
                this.cremaHost.Dispatcher.Invoke(action);
                result.SignatureDate = this.authentication.SignatureDate;
            }
            catch (Exception e)
            {
                result.Fault = new CremaFault()
                {
                    ExceptionType = e.GetType().Name, Message = e.Message
                };
            }
            return(result);
        }
        public IActionResult GetByFilter([FromBody] TouristSpot filter)
        {
            try
            {
                var result = new ResultBase <IEnumerable <TouristSpot> >();

                result.Success = true;
                result.Data    = _service.GetByName(filter);

                return(new ObjectResult(result));
            }
            catch (Exception erro)
            {
                var result = new ResultBase <IEnumerable <TouristSpot> >();
                result.Success = false;
                throw new Exception(erro.Message);
            }
        }
Exemplo n.º 14
0
        private ResultBase SyncLookExecuteCommand(CommandBase command)
        {
            ResultBase toReturn         = null;
            var        manualResetEvent = new ManualResetEvent(false);

            serviceControl.AddCommand(
                command,
                result =>
            {
                toReturn = result;
                LogFailedMessage(toReturn);
                manualResetEvent.Set();
            },
                LookSendCommandWithin,
                LookExpectResultWithin);
            manualResetEvent.WaitOne();
            return(toReturn);
        }
Exemplo n.º 15
0
        private async Task <T> RunOperationAndConvertExceptionToErrorAsync <T>(Func <Task <T> > operation)
            where T : ResultBase
        {
            try
            {
                return(await operation());
            }
            catch (Exception ex)
            {
                var result = new ErrorResult(ex).AsResult <T>();
                if (Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex))
                {
                    result.IsCancelled = true;
                }

                return(result);
            }
        }
        protected T RunOperationAndConvertExceptionToError <T>(Func <T> operation)
            where T : ResultBase
        {
            try
            {
                return(operation());
            }
            catch (Exception ex)
            {
                var result = new ErrorResult(ex).AsResult <T>();
                if (_context.Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex))
                {
                    result.IsCancelled = true;
                }

                return(result);
            }
        }
Exemplo n.º 17
0
        protected async Task <T> RunOperationAndConvertExceptionToErrorAsync <T>(Func <Task <T> > operation)
            where T : ResultBase
        {
            try
            {
                return(await WithOptionalTimeoutAsync(operation(), _timeout));
            }
            catch (Exception ex)
            {
                var result = new ErrorResult(ex).AsResult <T>();
                if (_context.Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex))
                {
                    result.IsCancelled = true;
                }

                return(result);
            }
        }
Exemplo n.º 18
0
        public ResultBase CancelShutdown()
        {
            var result = new ResultBase();

            try
            {
                this.cremaHost.CancelShutdown(this.authentication);
                result.SignatureDate = this.authentication.SignatureDate;
            }
            catch (Exception e)
            {
                result.Fault = new CremaFault()
                {
                    ExceptionType = e.GetType().Name, Message = e.Message
                };
            }
            return(result);
        }
Exemplo n.º 19
0
        public override string Format(ResultBase result)
        {
            var r         = result as ReliabilityResult;
            var numFormat = "{0:" + String.Format("N{0}", Precision) + "}%";

            var root = new XElement("ReliabilityResult",
                                    new XElement("Valid", r.IsValid),
                                    new XElement("Count", (r.Passed + r.Failed)),
                                    new XElement("Passed",
                                                 new XElement("Count", r.Passed),
                                                 new XElement("Percent", String.Format(numFormat, r.PercentPassed))),
                                    new XElement("Failed",
                                                 new XElement("Count", r.Failed),
                                                 new XElement("Percent", String.Format(numFormat, r.PercentFailed)))
                                    );

            return(root.ToString());
        }
Exemplo n.º 20
0
            public override int CompareTo(ResultBase other)
            {
                Result res = other as Result;

                if (res == null)
                {
                    return(0);
                }

                int patternDiff = (int)pattern - (int)res.pattern;

                if (patternDiff != 0)
                {
                    return(patternDiff);
                }

                return(strengthValue - res.strengthValue);
            }
Exemplo n.º 21
0
        public ResultBase Shutdown(int milliseconds, ShutdownType shutdownType, string message)
        {
            var result = new ResultBase();

            try
            {
                this.cremaHost.Shutdown(this.authentication, milliseconds, shutdownType, message);
                result.SignatureDate = this.authentication.SignatureDate;
            }
            catch (Exception e)
            {
                result.Fault = new CremaFault()
                {
                    ExceptionType = e.GetType().Name, Message = e.Message
                };
            }
            return(result);
        }
        public JsonResult DelMeeting(string meetingId)
        {
            ResultBase result = new ResultBase();

            if (imeeting.UpdateMeeting(meetingId) > 0)
            {
                result.Result = ResultCode.Ok;
                result.Msg    = "删除会议成功";
                Helper.DeleteFolder(Consts.SaveUrlPath + meetingId);
            }
            else
            {
                result.Result = ResultCode.ServerError;
                result.Msg    = "删除会议失败";
            }

            return(Json(result));
        }
Exemplo n.º 23
0
        private ResultBase <T> InvokeImmediately <T>(Func <T> func)
        {
            var result = new ResultBase <T>();

            try
            {
                result.Value         = func();
                result.SignatureDate = this.authentication.SignatureDate;
            }
            catch (Exception e)
            {
                result.Fault = new CremaFault()
                {
                    ExceptionType = e.GetType().Name, Message = e.Message
                };
            }
            return(result);
        }
        public IActionResult GetByUser(int id)
        {
            try
            {
                var result = new ResultBase <IEnumerable <FavoriteTouristSpot> >();

                result.Success = true;
                result.Data    = _service.getByUser(id);

                return(new ObjectResult(result));
            }
            catch (Exception erro)
            {
                var result = new ResultBase <IEnumerable <FavoriteTouristSpot> >();
                result.Success = false;
                throw new Exception(erro.Message);
            }
        }
Exemplo n.º 25
0
        public JsonResult Set(AboutInstart model)
        {
            if (model == null)
            {
                return(Error("参数错误。"));
            }

            var fileImg = Request.Files["fileImg"];

            if (fileImg != null)
            {
                string uploadResult = UploadHelper.Process(fileImg.FileName, fileImg.InputStream);
                if (!string.IsNullOrEmpty(uploadResult))
                {
                    model.ImgUrl = uploadResult;
                }
            }

            var fileVideo = Request.Files["fileVideo"];

            if (fileVideo != null)
            {
                string uploadResult = UploadHelper.Process(fileVideo.FileName, fileVideo.InputStream);
                if (!string.IsNullOrEmpty(uploadResult))
                {
                    model.VideoUrl = uploadResult;
                }
            }
            var result = new ResultBase();

            int count = _aboutInstartService.GetCountAsync();

            if (count > 0)
            {
                result.success = _aboutInstartService.UpdateAsync(model);
            }
            else
            {
                result.success = _aboutInstartService.InsertAsync(model);
            }

            return(Json(result));
        }
Exemplo n.º 26
0
        public ResultBase <Activity> Get(int id)
        {
            ResultBase <Activity> res = new ResultBase <Activity>();

            try
            {
                res.Item = _activityService.GetById(id);
            }
            catch (Exception ex)
            {
                res.IsSuccess = false;
                res.Error     = new Error()
                {
                    Message = Resources.ServerError + " : " + ex.InnerException, Stack = ex.StackTrace
                };
            }

            return(res);
        }
Exemplo n.º 27
0
        public virtual IActionResult Delete(int id)
        {
            var result = new ResultBase <TEntity>();

            try
            {
                var item = new ObjectResult(_business.GetById(id));
                result.Success = true;
                _business.Remove((TEntity)item.Value);

                return(new ObjectResult(result));
            }
            catch (Exception erro)
            {
                result.Success   = false;
                result.Exception = new Exception(erro.InnerException.Message);
                return(new ObjectResult(result));
            }
        }
Exemplo n.º 28
0
        public ResultBase <ManagePostModel> AddUpdatePublicPost(ManagePostModel managePostModel)
        {
            var result = new ResultBase <ManagePostModel> {
                IsSuccess = false
            };
            var Session = _sessionHelper.GetDecodedSession();

            try
            {
                using (SqlConnection sqlConnection = Utils.Utils.GetConnection(_configuration))
                {
                    using (SqlCommand cmd = new SqlCommand("PR_POST_PublicPost_Insert", sqlConnection))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ImageName", managePostModel.ImageName);
                        cmd.Parameters.AddWithValue("@CategoryID", managePostModel.PostCategory);
                        cmd.Parameters.AddWithValue("@PostedDateTime", DateTime.Now);
                        cmd.Parameters.AddWithValue("@QuoteText", managePostModel.QuoteText);
                        cmd.Parameters.AddWithValue("@IsActive", true);
                        cmd.Parameters.AddWithValue("@UserName", Session.UserName);
                        cmd.Parameters.AddWithValue("@UserID", Session.UserID);
                        int PostID = cmd.ExecuteNonQuery();
                        if (PostID > 0)
                        {
                            _tagsBll.AddEditTags(managePostModel.Tags, PostID);
                            result.Result    = managePostModel;
                            result.IsSuccess = true;
                            result.Message   = "Your Record has been Saved";
                        }

                        else
                        {
                            result.Message = "Something went wrong please try again letter";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "Something Went Wring while Saving record. Please try again letter." + ex.Message;
            }
            return(result);
        }
Exemplo n.º 29
0
        public ResultBase <long> GetRevision(string dataBaseName)
        {
            var result = new ResultBase <long>();

            try
            {
                using (var dataBaseItem = UsingDataBase.Set(this.cremaHost, dataBaseName, this.authentication, true))
                {
                    var dataBase = dataBaseItem.DataBase;
                    result.Value = dataBase.Dispatcher.Invoke(() => dataBase.DataBaseInfo.Revision);
                }
            }
            catch (Exception e)
            {
                result.Fault = new CremaFault(e);
            }

            return(result);
        }
Exemplo n.º 30
0
        public IActionResult UpdateMultiLang([FromBody] string lang)
        {
            ResultBase result = new ResultBase {
                Success = false
            };

            try
            {
                _multiLang.SetLang(lang);
                _httpContext.HttpContext.Session.SetString("MultiLang_CurrentLang", lang);
                result.Success = true;
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Message = e.Message;
            }
            return(Json(result));
        }
Exemplo n.º 31
0
 static OperationStatus statusFromResult(ResultBase resultBase)
 {
     if (resultBase.IsCriticalFailure)
     {
         return(OperationStatus.CriticalFailure);
     }
     else if (resultBase.IsCancelled)
     {
         return(OperationStatus.Cancelled);
     }
     else if (!resultBase.Succeeded)
     {
         return(OperationStatus.Failure);
     }
     else
     {
         return(OperationStatus.Success);
     }
 }
        public override string Format(ResultBase result)
        {
            var r = result as PerformanceResult;
            var f = "{0:" + NumFormat + "}";

            var root = new XElement("PerformanceResult",
                new XElement("Header",
                    new XElement("Iterations", r.Iterations),
                    new XElement("DegreeOfParallelism", r.DegreeOfParallelism),
                    new XElement("TotalSeconds", String.Format(f, r.TotalSeconds)),
                    new XElement("TotalMilliseconds", String.Format(f, r.TotalMilliseconds)),
                    new XElement("TotalTicks", String.Format(f, r.TotalTicks))
                    ));

            var details = XElement.Parse(_descriptiveFormatter.Format(r.DescriptiveResult));
            root.Add(details);

            return root.ToString();
        }
Exemplo n.º 33
0
        public ActionResult UserLogin(UserViewModel model)
        {
            mUser      umodel = new mUser();
            ResultBase result = new ResultBase();

            try
            {
                model.UserName = HttpUtility.UrlDecode(model.UserName);
                model.UserPass = Tool.MD5(HttpUtility.UrlDecode(model.UserPass));
                int roleId = 2;
                umodel = ilogin.LoginUserInfo(model.UserName, model.UserPass, roleId);



                if (umodel.PassWord == model.UserPass && umodel.UserName == model.UserName)
                {
                    if (umodel.UserRoleId == 2)
                    {
                        HttpContext.Session["LoginUser"] = umodel;
                        result.Msg    = "登陆成功";
                        result.Result = ResultCode.Ok;
                    }
                    else
                    {
                        result.Msg    = "此账号没有权限登录议员版本";
                        result.Result = ResultCode.ClientError;
                    }
                }
                else
                {
                    result.Msg    = "用户名和密码错误";
                    result.Result = ResultCode.ClientError;
                }
            }
            catch (Exception ex)
            {
                result.Msg    = "服务器错误";
                result.Result = ResultCode.ServerError;
                LogHelper.Error("UserLogin-" + DateTime.Now.ToString(), ex);
            }

            return(Json(result));
        }
Exemplo n.º 34
0
        public ResultBase <Category> Get()
        {
            ResultBase <Category> res = new ResultBase <Category>();

            try
            {
                res.Data = _categoryService.Get();
            }
            catch (Exception ex)
            {
                res.IsSuccess = false;
                res.Error     = new Error()
                {
                    Message = Resources.ServerError + " : " + ex.InnerException, Stack = ex.StackTrace
                };
            }

            return(res);
        }
        public ResultBase UploadReadtimeDatas([FromBody] RealtimeDatas UploadDatas)
        {
            ResultBase res = new ResultBase();



            long currentTicks = DateTime.Now.Ticks;

            if (UploadDatas == null)
            {
                LoggerManager.Log.Error("Upload realtime datas error: <UploadDatas  == NULL>!\n");
                res.IsSuccess = false;
                return(res);
            }



            if (CompanyManagerHelper.CheckDeviceCode(UploadDatas.DeviceInfo) == false)
            {
                LoggerManager.Log.Error("Upload realtime datas error: <check DeviceInfo is false>!\n");
                res.IsSuccess = false;
                return(res);
            }

            try
            {
                var    client        = RedisManager.GetClient();
                string RedisHashName = $"[{UploadDatas.DeviceInfo.CompanyCode}]-[{UploadDatas.DeviceInfo.DeviceCode}]";;
                Dictionary <string, string> TagDictionary = UploadDatas.Datas.ToDictionary(x => x.TagName, y => y.TagValue);
                client.HMSet(RedisHashName, TagDictionary);
            }
            catch (Exception ex)
            {
                LoggerManager.Log.Info("更新Resis数据库出错!\n");
                res.IsSuccess = false;
                return(res);
            }


            LoggerManager.Log.Info($"Upload realtime datas !{(DateTime.Now.Ticks-currentTicks)/10000}\n");

            return(res);
        }
Exemplo n.º 36
0
        /// <summary>
        /// 处理要访问方法
        /// </summary>
        /// <param name="aSocketMessage">信息实体对象</param>
        /// <param name="aUserSession">用户 websocket session 可以为空</param>
        private void handlerControllerAction(SocketEntity aobjSocketEnriry, WebSocketSession aobjSocketSession)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();


            //得到要执行的方法名称和类名
            string message = aobjSocketEnriry.ActionMethod;

            System.Diagnostics.Debug.WriteLine("方法名称与类名:" + message);

            string[] am = message.Split('.');
            //得到需要传入的参数
            Dictionary <string, object> param = js.Deserialize <Dictionary <string, object> >(aobjSocketEnriry.Message);



            object backObj = null;
            //得到要执行的方法对象和类实例对象

            ResultBase responseVo = new ResultBase();

            MethodInfo method = GetActionMethod(out backObj, className: am[0], method: am[1]);

            System.Diagnostics.Debug.WriteLine(method + "" + param);
            //得到方法执行数据
            object result = takeData(method, param, backObj);

            System.Diagnostics.Debug.WriteLine("通过方法" + result);
            responseVo.Result = result;


            //处理ResponseVo对象并发送数据
            aobjSocketEnriry.Message = JsonHelper.ReplaceDateTime(js.Serialize(responseVo));
            if (aobjSocketEnriry.FromUser != "")
            {
                List <string> vs = new List <string>();
                vs.Add(aobjSocketEnriry.FromUser);
                aobjSocketEnriry.ToUser = vs;
                aobjSocketSession       = null;
            }

            handlerSendMessage(aobjSocketEnriry, aobjSocketSession);
        }
Exemplo n.º 37
0
        /// <summary>
        /// 处理要访问方法
        /// </summary>
        /// <param name="aSocketMessage">信息实体对象</param>
        /// <param name="aUserSession">用户 websocket session 可以为空</param>
        private void handlerControllerAction(SocketEntity aobjSocketEnriry, WebSocketSession aobjSocketSession)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            //得到要执行的方法名称和类名
            string message = aobjSocketEnriry.ActionMethod;

            string[] am = message.Split('.');
            //得到需要传入的参数
            Dictionary <string, object> param = js.Deserialize <Dictionary <string, object> >(aobjSocketEnriry.Message);

            object backObj = null;
            //得到要执行的方法对象和类实例对象

            ResultBase responseVo = new ResultBase();
            //    try
            //  {
            MethodInfo method = GetActionMethod(out backObj, className: am[0], method: am[1]);
            //得到方法执行数据
            object result = takeData(method, param, backObj);

            responseVo.Result = result;

            // }
            //catch (Exception ex)
            // {

            //     responseVo.ErrorCode = "500";
            //     responseVo.ErrorMsg = ex.Message;
            //}


            //处理ResponseVo对象并发送数据
            aobjSocketEnriry.Message = JsonHelper.ReplaceDateTime(js.Serialize(responseVo));
            if (aobjSocketEnriry.FromUser != "")
            {
                List <string> vs = new List <string>();
                vs.Add(aobjSocketEnriry.FromUser);
                aobjSocketEnriry.ToUser = vs;
                aobjSocketSession       = null;
            }

            handlerSendMessage(aobjSocketEnriry, aobjSocketSession);
        }
        protected async Task <T> RunOperationAndConvertExceptionToErrorAsync <T>(Func <Task <T> > operation)
            where T : ResultBase
        {
            try
            {
                using var timer = CreatePeriodicTimerIfNeeded();
                return(await operation());
            }
            catch (Exception ex)
            {
                var result = new ErrorResult(ex).AsResult <T>();
                if (_context.Token.IsCancellationRequested && ResultBase.NonCriticalForCancellation(ex))
                {
                    result.IsCancelled = true;
                }

                return(result);
            }
        }
        public override string Format(ResultBase result)
        {
            var sb = new StringBuilder();
            var r = result as PerformanceResult;
            sb.AppendLine("Iterations,DegreeOfParallelism");
            sb.AppendLine(String.Format("{0},{1}", r.Iterations, r.DegreeOfParallelism));

            var f = "{0:" + NumFormat + "}";

            var t = String.Format(f, r.TotalTicks);
            var s = String.Format(f, r.TotalSeconds);
            var m = String.Format(f, r.TotalMilliseconds);

            sb.AppendLine("TotalSeconds,TotalMilliseconds,TotalTicks");
            sb.AppendLine(String.Format("{0},{1},{2}", s, m, t));
            sb.AppendLine();

            sb.Append(_descriptiveFormatter.Format(r.DescriptiveResult));

            return sb.ToString();
        }
Exemplo n.º 40
0
        /// <summary>
        /// Lê um arquivo do tipo .err, preenche os dados do NFeResult e retorna
        /// </summary>
        /// <param name="result">Variável do tipo NFeResult para receber os erros</param>
        /// <param name="fullPathErrFile">Caminho completo do arquivo .err</param>
        /// <exception cref="FileNotFoundException">Se o arquivo não existir.</exception>
        /// <returns></returns>
        public static ResultBase SetErrorResult(ResultBase result, string fullPathErrFile)
        {
            FileInfo fi = new FileInfo(fullPathErrFile);

            if(!fi.Exists)
                throw new FileNotFoundException();

            if(result == null) result = new NFeResult();

            if(WaitFile(new[] { fullPathErrFile }))
            {
                using (StreamReader stream = new StreamReader(fi.FullName, System.Text.Encoding.GetEncoding(1252)))
                {
                    string line = stream.ReadToEnd();

                    result.Message = line;
                    result.Exception = new Exception(line);
                }
            }

            return result;
        }
        public override string Format(ResultBase result)
        {
            var sb = new StringBuilder();
            var r = result as PerformanceResult;

            sb.AppendLine(String.Format("Total Iterations: {0}", r.Iterations));
            sb.AppendLine(String.Format("Degree Of Parallelism: {0}", r.DegreeOfParallelism));

            var f = "{0:" + NumFormat + "}";

            var t = String.Format(f, r.TotalTicks);
            var s = String.Format(f, r.TotalSeconds);
            var m = String.Format(f, r.TotalMilliseconds);

            sb.AppendLine(String.Format("Total Time: {0} seconds, {1} milliseconds, {2} ticks", s, m, t));
            sb.AppendLine();
            sb.AppendLine("Statistics (ms)");
            sb.AppendLine("---------------");

            sb.Append(descriptiveFormatter.Format(r.DescriptiveResult));

            return sb.ToString();
        }
Exemplo n.º 42
0
        private XDocument GetResultDocument(Dictionary<string, string> parameters, string method, ResultBase resultBase)
        {
            HttpWebRequest httpWebRequest = BuildRequest(BASE_URL, method, parameters);

            WebResponse response = default(WebResponse);

            try {
                response = httpWebRequest.GetResponse();
            }
            catch (TimeoutException e) {
                throw new TimeoutException("Timeout delivery uncertain");
            }
            XDocument resultDocument = XDocument.Load(response.GetResponseStream());
            ResultParser.ParseResultBase(resultDocument, resultBase);

            return resultDocument;
        }
Exemplo n.º 43
0
 /// <summary>
 /// Helper method to create a ResultBase containing one message.
 /// </summary>
 /// <param name="resultCode">The result code.  Negative for errors.  Positive for warnings.  Value -1 is reserved for internal use.</param>
 /// <param name="messageText"></param>
 /// <returns></returns>
 public static ResultBase WithMessage(int resultCode, string messageText)
 {
     var resultBase = new ResultBase();
     resultBase.AddMessage(new ResultItem(resultCode, messageText));
     return resultBase;
 }
 public override string Format(ResultBase result)
 {
     throw new NotImplementedException();
 }
 public abstract string Format(ResultBase result);