protected void HandleUnauthorizedRequest(ref AuthorizationContext filterContext)
        {
            UrlHelper urlHelper = null;
            if (filterContext.Controller is Controller)
            {
                urlHelper = ((Controller)filterContext.Controller).Url;
            }
            else
            {
                urlHelper = new UrlHelper(filterContext.RequestContext);
            }

            bool isAjaxRequest = filterContext.RequestContext.HttpContext.Request.IsAjaxRequest();

            Func<string, JsonResult> setResult = delegate(string msg)
            {
                DataResultBoolean response = new DataResultBoolean()
                {
                    IsValid = false,
                    Message = msg,
                    MessageType = DataResultMessageType.Error,
                    Data = false
                };
                JsonResult result = new JsonResult();
                result.Data = response;
                return result;
            };

            if (!this.CheckSessionExpired(filterContext.HttpContext))
            {
                if (isAjaxRequest)
                {
                    filterContext.Result = setResult($customNamespace$.Resources.General.GeneralTexts.SessionExpired);
                }
                else
                {
                    filterContext.Result = new RedirectResult(ErrorUrlHelper.SessionExpired(urlHelper));
                }
            }

            // break execution in case a result has been already set
            if (filterContext.Result != null)
                return;

            if (!this.CheckIsAutohrized(filterContext.HttpContext))
            {
                if (isAjaxRequest)
                {
                    filterContext.Result = setResult($customNamespace$.Resources.General.GeneralTexts.PermissionDenied);
                }
                else
                {
                    filterContext.Result = new RedirectResult(ErrorUrlHelper.UnAuthorized(urlHelper));
                }
            }
        }
예제 #2
0
        public void AllPropertiesDefaultToNull() {
            // Act
            JsonResult result = new JsonResult();

            // Assert
            Assert.IsNull(result.Data);
            Assert.IsNull(result.ContentEncoding);
            Assert.IsNull(result.ContentType);
        }
예제 #3
0
        public void PropertyDefaults() {
            // Act
            JsonResult result = new JsonResult();

            // Assert
            Assert.IsNull(result.Data);
            Assert.IsNull(result.ContentEncoding);
            Assert.IsNull(result.ContentType);
            Assert.AreEqual(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);
        }
예제 #4
0
        public void ProcessResult_WhenCreatedWithCustomObject_ReturnsCorrectJsonRepresentation()
        {
            var response = new FakeResponseContext();
            var result = new JsonResult(new CustomType { Data = "data", Number = 50 });

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("application/json"));
            Assert.That(response.Response, Is.EqualTo("{\"Data\":\"data\",\"Number\":50}"));
        }
예제 #5
0
        public void ProcessResult_WhenCreatedWithCollection_ReturnsCorrectJsonRepresentation()
        {
            var response = new FakeResponseContext();
            var result = new JsonResult(new List<CustomType> { new CustomType { Data = "data1", Number = 1 }, new CustomType { Data = "data2", Number = 2 } });

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("application/json"));
            Assert.That(response.Response, Is.EqualTo("[{\"Data\":\"data1\",\"Number\":1},{\"Data\":\"data2\",\"Number\":2}]"));
        }
예제 #6
0
        public void ProcessResult_WhenCreatedWithAnonymousObject_ReturnsCorrectJsonRepresentation()
        {
            var response = new FakeResponseContext();
            var result = new JsonResult(new { message = "hello world", number = 42 });

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("application/json"));
            Assert.That(response.Response, Is.EqualTo("{\"message\":\"hello world\",\"number\":42}"));
        }
예제 #7
0
        public static string GetJsonResult(JsonStatus status, string reason = "")
        {
            var result = new JsonResult()
            {
                status = status,
                reason = reason
            };

            return JsonConvert.SerializeObject(result);
        }
예제 #8
0
        public override JsonResult ToJsonResult()
        {
            JsonResult jr = new JsonResult();

            jr.Error = (int)MvcErrorType;
            jr.DataSource = ReasonCode;
            jr.ErrorMessage = this.Message;

            return jr;
        }
예제 #9
0
 public JsonResult<OperationResult<ConceptViewModel>> Get(long id)
 {
     var viewModel = this.conceptLogic.ConceptOnly(id);
     var result = new JsonResult<OperationResult<ConceptViewModel>>(
         viewModel,
         new JsonSerializerSettings(),
         Encoding.Default,
         this);
     return result;
 }
예제 #10
0
        public JsonResult<OperationResult<bool>> Delete(long id)
        {
            var operationResult = this.conceptLogic.Delete(id);
            var result = new JsonResult<OperationResult<bool>>(
                operationResult,
                new JsonSerializerSettings(),
                Encoding.Default,
                this);

            return result;
        }
예제 #11
0
        public JsonResult<OperationResult<RegisterUserViewModel>> Get()
        {
            var operationResult = this.registerLogic.GetRegisterViewModel();
            var js = new JsonSerializerSettings();
            var result = new JsonResult<OperationResult<RegisterUserViewModel>>(
                operationResult,
                js,
                Encoding.Default,
                this);

            return result;
        }
예제 #12
0
        public JsonResult<OperationResult<ListConceptViewModel>> Get(string include = "")
        {
            var viewModel = this.conceptLogic.ConceptsWith(include);

            var result = new JsonResult<OperationResult<ListConceptViewModel>>(
                viewModel,
                new JsonSerializerSettings(),
                Encoding.Default,
                this);

            return result;
        }
예제 #13
0
 public Negotiation Negotiate(IRequest request, object model)
 {
     var opt = request.Headers.MatchAccept(reIsJson);
     if (opt == null) return Negotiation.None(this);
     var match = opt.Value == "*/*" ? Match.Inexact : Match.Exact;
     return new Negotiation(
         match, opt.Q, this, () => {
             var result = new JsonResult(model);
             if (opt.Value != "*/*") result.MimeType = opt.Value;
             return result;
         }
     );
 }
예제 #14
0
        public void PropertyDefaults()
        {
            // Act
            JsonResult result = new JsonResult();

            // Assert
            Assert.Null(result.Data);
            Assert.Null(result.ContentEncoding);
            Assert.Null(result.ContentType);
            Assert.Null(result.MaxJsonLength);
            Assert.Null(result.RecursionLimit);
            Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);
        }
예제 #15
0
 public JsonResult<OperationResult<long>> Post(RegisterUserViewModel model)
 {
     JsonResult<OperationResult<long>> result;
     var js = new JsonSerializerSettings();
     if (ModelState.IsValid)
     {
         var registerResult = this.registerLogic.RegisterUser(model);
         result = new JsonResult<OperationResult<long>>(registerResult, js, Encoding.Default, this);
     }
     else
     {
         var errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
         var faultyResult = new OperationResult<long>(-1, false, errors.ToList());
         result = new JsonResult<OperationResult<long>>(faultyResult, js, Encoding.Default, this);
     }
     return result;
 }
예제 #16
0
        /// <summary>
        /// Executes the <see cref="JsonResult"/> and writes the response.
        /// </summary>
        /// <param name="context">The <see cref="ActionContext"/>.</param>
        /// <param name="result">The <see cref="JsonResult"/>.</param>
        /// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns>
        public Task ExecuteAsync(ActionContext context, JsonResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            string resolvedContentType = null;
            Encoding resolvedContentTypeEncoding = null;
            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            var serializerSettings = result.SerializerSettings ?? Options.SerializerSettings;

            Logger.JsonResultExecuting(result.Value);
            using (var writer = WriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
            {
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.CloseOutput = false;

                    var jsonSerializer = JsonSerializer.Create(serializerSettings);
                    jsonSerializer.Serialize(jsonWriter, result.Value);
                }
            }

            return TaskCache.CompletedTask;
        }
예제 #17
0
        public async Task ExecuteAsync_UsesDefaultContentType_IfNoContentTypeSpecified()
        {
            // Arrange
            var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { foo = "abcd" }));

            var context = GetActionContext();

            var result = new JsonResult(new { foo = "abcd" });
            var executor = CreateExcutor();

            // Act
            await executor.ExecuteAsync(context, result);

            // Assert
            var written = GetWrittenBytes(context.HttpContext);
            Assert.Equal(expected, written);
            Assert.Equal("application/json; charset=utf-8", context.HttpContext.Response.ContentType);
        }
예제 #18
0
        public async Task ExecuteAsync_NullEncoding_DoesNotSetCharsetOnContentType()
        {
            // Arrange
            var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { foo = "abcd" }));

            var context = GetActionContext();

            var result = new JsonResult(new { foo = "abcd" });
            result.ContentType = new MediaTypeHeaderValue("text/json");
            var executor = CreateExcutor();

            // Act
            await executor.ExecuteAsync(context, result);

            // Assert
            var written = GetWrittenBytes(context.HttpContext);
            Assert.Equal(expected, written);
            Assert.Equal("text/json", context.HttpContext.Response.ContentType);
        }
예제 #19
0
		public JsonResult getCodeOne(int tree_code)
		{
			CCode code = new CCode();
			JsonResult json = new JsonResult();

			HttpContext.GetGlobalResourceObject("c", "s");

			try
			{
				DaoCode daoTree = new DaoCode();

				code = daoTree.getCodeOne(tree_code);
				json.Data = code;
			}
			catch (Exception e)
			{
				throw new Exception(e.Message);
			}

			return json;
		}
예제 #20
0
        public void EmptyContentTypeRendersDefault() {
            // Arrange
            object data = _jsonData;
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);
            mockControllerContext.ExpectSet(c => c.HttpContext.Response.ContentType, "application/json").Verifiable();
            mockControllerContext.ExpectSet(c => c.HttpContext.Response.ContentEncoding, contentEncoding).Verifiable();
            mockControllerContext.Expect(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();

            JsonResult result = new JsonResult {
                Data = data,
                ContentType = String.Empty,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
예제 #21
0
        public JsonResult GetSharedInfo(string type, string URL)
        {
            /// type值为空
            if (string.IsNullOrEmpty(type))
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_TypeIsNull
                }, JsonRequestBehavior.AllowGet));
            }

            /// URL为空
            if (string.IsNullOrEmpty(URL))
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_UrlIsNull
                }, JsonRequestBehavior.AllowGet));
            }
            LogHelper.Info("------------PinLifeDetail---刚进入方法--URL:" + URL);
            JsonResult json = null;

            /// 团详情页分享
            if (type.Equals(ShareUtils.TeamSharedFlag))
            {
                // 获得团详情页分享Json
                json = TeamJoinDetail(URL);
            }
            // 拼生活详情页分享Json
            else if (type.Equals(ShareUtils.PinLifeDetailSharedFlag))
            {
                // 拼生活详情页分享Json
                json = PinLifeProductDetail(URL);
            }
            // 专题页
            else
            {
                // 根据专题活动标志Key获取专题对象
                var model = activityBll.GetActivityByKey(type);

                if (model == null)
                {
                    json = Json(new
                    {
                        type    = (int)ShareUtils.JsonType.typeFailed,
                        content = ShareUtils.JsonContent_JsonIsNull
                    }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string imgPath = model.ImgPath + "shareImg.jpg?v=" + ConfigurationManager.AppSettings["ImgVersion"].ToString();
                    // 专题页Json
                    json = SpecialPage(type, URL
                                       , model.Title, model.Discription, imgPath);
                }
            }

            return(json);
        }
예제 #22
0
        /// <summary>
        /// 获取车场操作权限
        /// </summary>
        /// <returns></returns>
        public JsonResult GetParkingOperatePurview()
        {
            JsonResult result = new JsonResult();
            List <SystemOperatePurview> options        = new List <SystemOperatePurview>();
            List <SysRoleAuthorize>     roleAuthorizes = GetLoginUserRoleAuthorize.Where(p => p.ParentID == "PK010103").ToList();

            foreach (var item in roleAuthorizes)
            {
                switch (item.ModuleID)
                {
                case "PK01010301":
                {
                    SystemOperatePurview option = new SystemOperatePurview();
                    option.text    = "添加";
                    option.handler = "Add";
                    option.sort    = 1;
                    options.Add(option);
                    break;
                }

                case "PK01010302":
                {
                    SystemOperatePurview option = new SystemOperatePurview();
                    option.text    = "修改";
                    option.handler = "Update";
                    option.sort    = 2;
                    options.Add(option);
                    break;
                }

                case "PK01010303":
                {
                    SystemOperatePurview option = new SystemOperatePurview();
                    option.text    = "删除";
                    option.handler = "Delete";
                    option.sort    = 3;
                    options.Add(option);
                    break;
                }

                case "PK01010304":
                {
                    SystemOperatePurview option = new SystemOperatePurview();
                    option.text    = "放行备注";
                    option.id      = "btnremark";
                    option.handler = "PassRmark";
                    option.iconCls = "icon-add";
                    option.sort    = 4;
                    options.Add(option);
                    break;
                }

                case "PK01010306":
                {
                    SystemOperatePurview option = new SystemOperatePurview();
                    option.text    = "消费减免";
                    option.id      = "btnderate";
                    option.handler = "ParkDerate";
                    option.iconCls = "icon-add";
                    option.sort    = 5;
                    options.Add(option);
                    break;
                }

                case "PK01010305":
                {
                    SystemOperatePurview option8 = new SystemOperatePurview();
                    option8.text    = "下载二维码";
                    option8.id      = "btndownloadqrcode";
                    option8.handler = "DownloadQRCode";
                    option8.iconCls = "icon-import";
                    option8.sort    = 6;
                    options.Add(option8);
                    break;
                }
                }
            }


            SystemOperatePurview roption = new SystemOperatePurview();

            roption.text    = "刷新";
            roption.handler = "Refresh";
            roption.sort    = 7;
            options.Add(roption);

            result.Data = options.OrderBy(p => p.sort);
            return(result);
        }
        public async Task <JsonResult> CreateNewPorject([FromBody] ProjectInput input)
        {
            string     sErr     = "";
            JsonResult response = null;
            string     userID   = "";

            try
            {
                Project existProject = null;
                if (String.IsNullOrEmpty(input.Name))
                {
                    sErr = "Project name cannot be empty!";
                    goto Get_Out;
                }
                if (String.IsNullOrEmpty(input.Username))
                {
                    sErr = "User name cannot be empty!";
                    goto Get_Out;
                }
                await Task.Run(() =>
                {
                    userID = _userRepository.GetUserID(input.Username);
                });

                if (String.IsNullOrEmpty(userID))
                {
                    sErr = "Cannot find user!";
                    goto Get_Out;
                }
                await Task.Run(() =>
                {
                    existProject = this._projectRepository.Get(input.Name, userID);
                });

                if (existProject != null)
                {
                    sErr += "Project name cannot be duplicated!";
                    goto Get_Out;
                }
                Project project = new Project()
                {
                    UserID      = userID,
                    Name        = input.Name,
                    ProjectType = input.ProjectType,
                    Description = input.Description,
                };
                await Task.Run(() =>
                {
                    sErr = _projectRepository.Add(project);
                });

                if (sErr != "")
                {
                    goto Get_Out;
                }
                //using (ConfigContext db = new ConfigContext(new DbContextOptions<ConfigContext>()))
                //{
                //    db.Porjects.Add(project);
                //    db.SaveChanges();
                //}
            }
            catch (Exception ex)
            {
                sErr += "\r\n" + ex.Message + "\r\n" + ex.StackTrace;
                goto Get_Out;
            }
Get_Out:
            if (!String.IsNullOrEmpty(sErr))
            {
                sErr += "\r\nRoutine=" + MethodInfo.GetCurrentMethod().ReflectedType.Name + "." + MethodInfo.GetCurrentMethod().ToString();
                //_logger.LogError(sErr);
                response = Json(new AjaxResponse
                {
                    Succeed = false,
                    Status  = "failed",
                    Message = "Create project failed:" + sErr
                });

                return(response);
            }

            else
            {
                sErr = "Create Model Success!";
                //_logger.LogInformation(sErr);
                response = Json(new AjaxResponse
                {
                    Succeed = true,
                    Status  = "success",
                    Message = "Create project success!"
                });

                return(response);
            }
        }
        public ActionResult EditingSaveChanges()
        {
            ViewData["GenerateCompactJSONResponse"] = false;
            GridModel m = new GridModel();
            List <Transaction <Category> > categoryTransactions = m.LoadTransactions <Category>(HttpContext.Request.Form["ig_transactions"]);

            foreach (Transaction <Category> t in categoryTransactions)
            {
                DataRow dr = this.CategoriesProducts.Tables["Categories"].Rows.Find(Int32.Parse(t.rowId));
                if ((t.layoutKey == null) && (dr != null))
                {
                    if (t.type == "row")
                    {
                        Category categoryRow = (Category)t.row;
                        if (categoryRow.CategoryName != null)
                        {
                            dr["CategoryName"] = categoryRow.CategoryName;
                        }
                        if (categoryRow.Description != null)
                        {
                            dr["Description"] = categoryRow.Description;
                        }
                    }
                    else if (t.type == "deleterow")
                    {
                        this.CategoriesProducts.Tables["Categories"].Rows.Remove(dr);
                    }
                }
            }
            List <Transaction <Product> > productTransactions = m.LoadTransactions <Product>(HttpContext.Request.Form["ig_transactions"]);

            foreach (Transaction <Product> t in productTransactions)
            {
                DataRow dr = this.CategoriesProducts.Tables["Products"].Rows.Find(Int32.Parse(t.rowId));
                if ((t.layoutKey == "Products") && (dr != null))
                {
                    if (t.type == "deleterow")
                    {
                        this.CategoriesProducts.Tables["Products"].Rows.Remove(dr);
                    }
                    else if (t.type == "row")
                    {
                        Product productRow = (Product)t.row;
                        if (productRow.ProductName != null)
                        {
                            dr["ProductName"] = productRow.ProductName;
                        }
                        if (productRow.CategoryID != null)
                        {
                            dr["CategoryID"] = productRow.CategoryID;
                        }
                        if (productRow.UnitPrice != null)
                        {
                            dr["UnitPrice"] = productRow.UnitPrice;
                        }
                        if (productRow.UnitsInStock != null)
                        {
                            dr["UnitsInStock"] = productRow.UnitsInStock;
                        }
                        dr["Discontinued"] = productRow.Discontinued;
                    }
                }
            }
            JsonResult result = new JsonResult();
            Dictionary <string, bool> response = new Dictionary <string, bool>();

            response.Add("Success", true);
            result.Data = response;
            return(result);
        }
예제 #25
0
 public static JsonResult WithWarning(this JsonResult result, string message)
 {
     return(new AlertJsonDecoratorResult(result, "alert-warning", message));
 }
예제 #26
0
 public static JsonResult WithSuccess(this JsonResult result, string message)
 {
     return(new AlertJsonDecoratorResult(result, "alert-success", message));
 }
예제 #27
0
        //保存基本信息
        public JsonResult setCmMstUser(string UserId, string UserName, string Password, string EndDate, string PhoneNo, string userClassCode, int NewFlag)
        {
            var user = Session["CurrentUser"] as UserAndRole;

            EndDate = EndDate.Replace(" ", "");
            EndDate = EndDate.Replace("-", "");
            int    intEndDate = Convert.ToInt32(EndDate);
            var    res        = new JsonResult();
            string Class      = ""; //该字段已作废
            bool   IsSaved    = false;
            int    flag       = 0;

            IsSaved = _ServicesSoapClient.SetMstUserUM(UserId, UserName, Password, Class, intEndDate, user.UserId, user.TerminalName, user.TerminalIP, user.DeviceType);
            if (userClassCode == "Patient")
            {
                if (NewFlag == 0)
                {
                    IsSaved = _ServicesSoapClient.SetPatName(UserId, UserName);
                }
                else
                {
                    //此界面不涉及病人新建
                }
            }
            else
            {
                string Code = "";
                IsSaved = _ServicesSoapClient.SetDocName(UserId, UserName);
                if (NewFlag != 0)
                {
                    if (userClassCode == "Administrator")
                    {
                        flag = _ServicesSoapClient.SetPsRoleMatch(UserId, "Administrator", "", "0", "");
                    }
                    else if (userClassCode == "Doctor")
                    {
                        Code = _ServicesSoapClient.GetNoByNumberingType(13);
                        flag = _ServicesSoapClient.SetPsRoleMatch(UserId, "Doctor", Code, "1", "");
                    }
                    else if (userClassCode == "HealthCoach")
                    {
                        Code = _ServicesSoapClient.GetNoByNumberingType(12);
                        flag = _ServicesSoapClient.SetPsRoleMatch(UserId, "HealthCoach", Code, "1", "");
                    }
                }
            }
            if (IsSaved == true)
            {
                flag = _ServicesSoapClient.SetPhoneNo(UserId, "PhoneNo", PhoneNo, user.UserId, user.TerminalName, user.TerminalIP, user.DeviceType);
            }
            if ((flag == 1) && (userClassCode != "Patient"))
            {
                IsSaved = _ServicesSoapClient.SetDoctorInfoDetail(UserId, "Contact", "Contact002_1", 1, PhoneNo, "", 1, user.UserId, user.TerminalName, user.TerminalIP, user.DeviceType);
                if (IsSaved)
                {
                    flag = 1;
                }
                else
                {
                    flag = 0;
                }
            }
            res.Data = flag;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return(res);
        }
예제 #28
0
        public async Task Test_TicketsController_AddInternalReplyToTicket()
        {
            // Setup.
            SeedDatabase();
            TicketsController controllerUnderTest = new TicketsController(Database);

            // Check that the controller handles incorrect paramters.
            if (await controllerUnderTest.AddExternalReplyToTicket(null, null, null, null))
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }
            if (await controllerUnderTest.AddExternalReplyToTicket("", "", "", ""))
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }
            if (await controllerUnderTest.AddExternalReplyToTicket("not_a_number", "could_be_valid", "could_be_valid", "could_be_valid"))
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }

            // Setup (Get a valid User to test with).
            User user = Database.Users.First();

            if (user == null)
            {
                Assert.Fail("Seeded database not as expected for this test.");
            }
            string     userId        = user.Id;                                                           // Used as a cache to get the same User later on.
            JsonResult userTokenJson = await new UserController(Database).GetNewUserToken(user.UserName); // This Controller has been tested independently.

            if (userTokenJson == null)                                                                    // Check that we didn't get an error from the controller and that we can continue.
            {
                Assert.Fail("Problem getting User Token for testing.");
            }
            user = Database.Users.FirstOrDefault(u => u.Id == userId); // Re-get the User from the database, as UserController should have changed it.
            if (user == null)
            {
                Assert.Fail("Logic problem with test, cannot continue.");
            }

            int ticketLogCount = await Database.TicketLogs.CountAsync(tl => tl.TicketId == 1);

            if (ticketLogCount != 3)
            {
                Assert.Fail("Seeded database not as expected for this test, incorrect amount of ticket logs.");
            }

            if (!await controllerUnderTest.AddInternalReplyToTicket("1", user.UserName, user.UserToken, "Message to add to Ticket."))
            {
                Assert.Fail("Received unexpected result from controller.");
            }

            ticketLogCount = await Database.TicketLogs.CountAsync(tl => tl.TicketId == 1);

            if (ticketLogCount != 4)
            {
                Assert.Fail("Seeded database not as expected for this test, incorrect amount of ticket logs.");
            }

            if (!await controllerUnderTest.AddInternalReplyToTicket("1", user.UserName, user.UserToken, "Another message to add to Ticket."))
            {
                Assert.Fail("Received unexpected result from controller.");
            }

            ticketLogCount = await Database.TicketLogs.CountAsync(tl => tl.TicketId == 1);

            if (ticketLogCount != 5)
            {
                Assert.Fail("Seeded database not as expected for this test, incorrect amount of ticket logs.");
            }

            // TODO: Check for the handling of the User being internal/not internal.
        }
예제 #29
0
        public JsonResult<OperationResult<long>> Post(AddConceptViewModel model)
        {
            OperationResult<long> operationResult;
            if (ModelState.IsValid)
            {
                operationResult = this.conceptLogic.Add(model);
            }
            else
            {
                var errors =
                    this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x).Select(x => x.ErrorMessage).ToList();
                operationResult = new OperationResult<long>(0, false, errors);

            }

            var result = new JsonResult<OperationResult<long>>(
                 operationResult,
                 new JsonSerializerSettings(),
                 Encoding.Default,
                 this);

            return result;
        }
예제 #30
0
        public ActionResult GetView()
        {
            JsonResult resultnew = GetVmSizes();

            return(PartialView("_LabsPartial"));
        }
예제 #31
0
        public ActionResult <GroupModel> Get(int id)
        {
            JsonResult json = new JsonResult(_groups.FinGroupById(id));

            return(json);
        }
예제 #32
0
        public ActionResult <IEnumerable <GroupModel> > Get()
        {
            JsonResult json = new JsonResult(_groups.FindAllGroups());

            return(json);
        }
예제 #33
0
        public void InsBookAppFinal(string LibroPDF, string ImagenLibro, string FileNamePic, string NombreLibro, string NombreUsuario, string sinopsis, string Categoria, int EstatusLibro)
        {
            LibrosBO  Olibros           = new LibrosBO();
            LibrosDAO DaoLibros         = new LibrosDAO();
            var       originalDirectory = new DirectoryInfo(Server.MapPath("~/LibrosPortadas/" + NombreUsuario + "/"));

            //Verificamos si existe el directorio
            if (!Directory.Exists(originalDirectory.ToString()))
            {
                Directory.CreateDirectory(originalDirectory.ToString());
            }
            var fileName1 = NombreLibro.Replace(" ", "");    //Cambié esta instrucción para obtener solo el nombre del archivo, sin la extensión.
            //Solo el pdf necesitamos encriptar
            string encryptedName = fileName1 + "_encrypted"; //Se asigna el nombre que tendrá el archivo ya encriptado

            //Convertimos a Byte el base 64
            byte[] bytesPDF    = Convert.FromBase64String(LibroPDF);
            string pathDestino = originalDirectory.ToString() + encryptedName; //Se combinan las rutas para indicar en dónde se guardará el archivo encriptado

            EncryptFile(bytesPDF, pathDestino);                                //Llamada al método para encriptar archivo

            //Hasta aqui ya se guardo el archivo

            Olibros.Titulo        = NombreLibro;
            Olibros.Sinpsis       = sinopsis;
            Olibros.LibroFisico   = NombreUsuario + "/" + fileName1;
            Olibros.ImagenPòrtada = NombreUsuario + "/" + NombreUsuario + "_" + FileNamePic;
            Olibros.Categoria     = Categoria;
            Olibros.EstatusLibro  = EstatusLibro;


            //Guardamos la imagen
            var path = string.Format("{0}\\{1}", originalDirectory.ToString(), NombreUsuario + "_" + FileNamePic);

            File.WriteAllBytes(path, Convert.FromBase64String(ImagenLibro));
            UsuariosDAO DaoUser = new UsuariosDAO();

            Olibros.Autor_ID = DaoUser.GetUserIDByName(NombreUsuario);
            string outputJSON;

            try
            {
                if (DaoLibros.SaveBook(Olibros) == 1)
                {
                    JsonResult OBJson = new JsonResult
                    {
                        Result = 1
                    };
                    outputJSON = ser.Serialize(OBJson);
                    Context.Response.Write(ser.Serialize(OBJson));
                }
            }
            catch (Exception)
            {
                JsonResult OBJson = new JsonResult
                {
                    Result = 0
                };
                outputJSON = ser.Serialize(OBJson);
                Context.Response.Write(ser.Serialize(OBJson));
            }
        }
예제 #34
0
        /// <summary>
        /// 获得团详情页分享Json
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        private JsonResult TeamJoinDetail(string URL)
        {
            string     TeamCodeStr  = "";
            string     OrderCodeStr = "";
            JsonResult json         = null;

            Uri    uri      = new Uri(URL);
            int    index    = uri.Query.IndexOf("?");
            string urlQuery = uri.Query.Substring(index + 1, uri.Query.Length - 1);

            string[] urlParams = urlQuery.Split('&');
            foreach (string param in urlParams)
            {
                string[] items = param.Split('=');
                if (items[0].Equals("TeamCode"))
                {
                    TeamCodeStr = items[1];
                }
                else if (items[0].Equals("OrderCode"))
                {
                    OrderCodeStr = items[1];
                }
            }
            //LogHelper.Info("------------Shared-----URL1:" + URL);

            IList <TeamDetailEntity> teamDetailList = null;

            if (!string.IsNullOrEmpty(TeamCodeStr))
            {
                /// 获取团详情信息
                teamDetailList = teamBll.GetTeamDetailList(TeamCodeStr);
                //LogHelper.Info("------------Shared-----teamDetailList:" + teamDetailList);
            }
            else if (!string.IsNullOrEmpty(OrderCodeStr))
            {
                TeamInfoEntity teamInfoEntity = teamBll.GetTeamInfoEntity(OrderCodeStr);
                //LogHelper.Info("------------Shared-----teamInfoEntity:" + teamInfoEntity);
                if (teamInfoEntity != null)
                {
                    TeamCodeStr = teamInfoEntity.TeamCode;
                    //LogHelper.Info("------------Shared-----TeamCodeStr:" + TeamCodeStr);

                    /// 获取团详情信息
                    teamDetailList = teamBll.GetTeamDetailList(TeamCodeStr);
                    //LogHelper.Info("------------Shared-----teamDetailList:" + teamDetailList);
                }
            }
            else
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_TeamCodeIsNull
                }, JsonRequestBehavior.AllowGet));
            }

            /// 判断集合是否为空
            if (teamDetailList == null || teamDetailList.Count() == 0)
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_TeamListIsNull
                }, JsonRequestBehavior.AllowGet));
            }

            //LogHelper.Info("------------Shared-----URL2:" + URL);
            //LogHelper.Info("------------Shared-----ImagePath:" + teamDetailList.First().ImagePath);

            // 获得商品净重、净含量信息,再重新装配数据集合
            List <TeamDetailEntity> teamDetailProductList = new List <TeamDetailEntity>();

            foreach (TeamDetailEntity product in teamDetailList)
            {
                string neight = commonBll.getProductDetailName(product.MainDicValue, product.SubDicValue, product.NetWeightUnit);
                product.NetWeightUnit = neight;
                teamDetailProductList.Add(product);
            }

            /// 获得团详情页分享对象
            TeamSharedModel teamSharedModel = GetTeamSharedInfo(teamDetailProductList);

            /// 获得微信配置信息
            JSSDKModel JsSdkModel = GetWechatParams(URL);

            if (JsSdkModel.type == (int)ShareUtils.JsonType.typeFailed)
            {
                return(Json(new
                {
                    type = JsSdkModel.type,
                    content = JsSdkModel.content
                }, JsonRequestBehavior.AllowGet));
            }

            //LogHelper.Info("------------Shared-------TeamCode:" + TeamCodeStr);

            // 获得团成员剩余数量
            int value = teamSharedModel.RestTeamMemberNum;

            /*LogHelper.Info("------------Shared----RestTeamMemberNum-----RestTeamMemberNum:" + value);
             * LogHelper.Info("------------Shared-----Title:" + teamSharedModel.Title);
             * LogHelper.Info("------------Shared-----ImagePath:" + teamSharedModel.ImagePath);
             * LogHelper.Info("------------Shared-----Description:" + teamSharedModel.Description);
             * LogHelper.Info("------------Shared-----URL3:" + teamSharedModel.Url);*/

            json = Json(new
            {
                type = JsSdkModel.type,
                data = new
                {
                    appId       = JsSdkModel.appId,
                    timestamp   = JsSdkModel.timestamp,
                    nonceStr    = JsSdkModel.nonceStr,
                    signature   = JsSdkModel.signature,
                    jsApiList   = JsSdkModel.jsApiList,
                    Title       = teamSharedModel.Title,
                    ImagePath   = teamSharedModel.ImagePath,
                    Description = teamSharedModel.Description,
                    Url         = URL
                }
            }, JsonRequestBehavior.AllowGet);

            return(json);
        }
예제 #35
0
        /// <summary>
        /// 拼生活详情页分享Json
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        private JsonResult PinLifeProductDetail(string URL)
        {
            string     sku  = "";
            string     pid  = "";
            JsonResult json = null;

            Uri    uri      = new Uri(URL);
            int    index    = uri.Query.IndexOf("?");
            string urlQuery = uri.Query.Substring(index + 1, uri.Query.Length - 1);

            string[] urlParams = urlQuery.Split('&');
            foreach (string param in urlParams)
            {
                string[] items = param.Split('=');
                if (items[0].Equals("sku"))
                {
                    sku = items[1];
                }
                else if (items[0].Equals("pid"))
                {
                    pid = items[1];
                }
            }
            LogHelper.Info("------------PinLifeDetail-----URL1:" + URL);

            IList <ProductInfoModel> productsDetail = new List <ProductInfoModel>();

            if (!string.IsNullOrEmpty(sku) && !string.IsNullOrEmpty(pid))
            {
                // 拼生活商品详情页
                productsDetail = productBll.GetProductFightDetailForShare(sku, base.ExchangeRate, Int32.Parse(pid));
                LogHelper.Info("------------PinLifeDetail-----productsDetail:" + productsDetail);
            }
            else
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_PinLife_ParamIsNull
                }, JsonRequestBehavior.AllowGet));
            }

            /// 判断集合是否为空
            if (productsDetail == null || productsDetail.Count() == 0)
            {
                return(Json(new
                {
                    type = (int)ShareUtils.JsonType.typeFailed,
                    content = ShareUtils.JsonContent_PinLifeDetailListIsNull
                }, JsonRequestBehavior.AllowGet));
            }

            LogHelper.Info("------------PinLifeDetail-----URL2:" + URL);
            LogHelper.Info("------------PinLifeDetail-----ImagePath:" + productsDetail.FirstOrDefault().ImagePath);

            // 获得商品净重、净含量信息,再重新装配数据集合
            List <ProductInfoModel> productDetailProductList = new List <ProductInfoModel>();

            foreach (ProductInfoModel product in productsDetail)
            {
                string neight = commonBll.getProductDetailName(product.MainDicValue, product.SubDicValue, product.NetWeightUnit);
                product.NetWeightUnit = neight;
                productDetailProductList.Add(product);
            }

            // 拼生活详情页分享信息
            ProductModel ProductViewModel = GetPinLifeDetailSharedInfo(productDetailProductList);

            /// 获得微信配置信息
            JSSDKModel JsSdkModel = GetWechatParams(URL);

            if (JsSdkModel.type == (int)ShareUtils.JsonType.typeFailed)
            {
                return(Json(new
                {
                    type = JsSdkModel.type,
                    content = JsSdkModel.content
                }, JsonRequestBehavior.AllowGet));
            }

            /*LogHelper.Info("------------PinLifeDetail-------sku:" + sku);
             * LogHelper.Info("------------PinLifeDetail-------pid:" + pid);
             * LogHelper.Info("------------Shared-----Title:" + ProductViewModel.Title);
             * LogHelper.Info("------------Shared-----ImagePath:" + ProductViewModel.ImagePath);
             * LogHelper.Info("------------Shared-----Description:" + ProductViewModel.Description);*/

            json = Json(new
            {
                type = JsSdkModel.type,
                data = new
                {
                    appId       = JsSdkModel.appId,
                    timestamp   = JsSdkModel.timestamp,
                    nonceStr    = JsSdkModel.nonceStr,
                    signature   = JsSdkModel.signature,
                    jsApiList   = JsSdkModel.jsApiList,
                    Title       = ProductViewModel.Title,
                    ImagePath   = ProductViewModel.ImagePath,
                    Description = ProductViewModel.Description,
                    Url         = URL
                }
            }, JsonRequestBehavior.AllowGet);

            return(json);
        }
예제 #36
0
        public JsonResult Action(StudentActionModel model)
        {
            bool   result;
            string msg = "";

            if (model.ID > 0)
            {
                Student objectFirst = service.GetByID(model.ID);
                try
                {
                    result = service.Update(objectFirst);
                }
                catch (Exception exc)
                {
                    result = false;
                    msg    = exc.Message.ToString();
                }
            }
            else
            {
                Student objectFirst = new Student
                {
                    FirstName        = model.FirstName,
                    LastName         = model.LastName,
                    CNIC             = model.CNIC,
                    FatherName       = model.FatherName,
                    FatherCNIC       = model.FatherCNIC,
                    FatherProfession = model.FatherProfession,
                    StudentContact   = model.StudentContact,
                    FatherContact    = model.FatherContact,
                    EmergencyContact = model.EmergencyContact,
                    DateOfBirth      = model.DateOfBirth,
                    BloodGroupID     = model.BloodGroupID,
                    Gender           = model.Gender,
                    MaritalStatus    = model.MaritalStatus,
                    CityID           = model.CityID,
                    PresentAddress   = model.PresentAddress,
                    PermenantAddress = model.PermenantAddress,
                    IP         = UserInfo.IP(),
                    Agent      = UserInfo.Agent(),
                    Location   = UserInfo.Location(),
                    ModifiedOn = DateTime.Now,
                    UserID     = UserHelperInfo.GetUserId()
                };
                try
                {
                    result = service.Save(objectFirst);
                }
                catch (DbEntityValidationException exc)
                {
                    foreach (var validationException in exc.EntityValidationErrors)
                    {
                        foreach (var ve in validationException.ValidationErrors)
                        {
                            msg += ve.PropertyName + "" + ve.ErrorMessage;
                        }
                    }
                    result = false;
                }
                catch (Exception exc)
                {
                    result = false;
                    msg    = exc.InnerException.ToString();
                }
            }

            JsonResult jsonResult = new JsonResult
            {
                Data = result ? (new { Success = true, Msg = msg }) : (new { Success = false, Msg = msg })
            };

            return(jsonResult);
        }
        public ActionResult Checkout(FullCheckOutModel checkoutModel)
        {
            try
            {
                Person personAddress = null;
                var    user          = _loggedInUser.GetLoggedInUser(System.Web.HttpContext.Current);

                if (user == null)
                {
                    throw new HttpException("Unable to find User");
                }

                //instead of this in future pull from cache, when an record in updated in database  insert to other table called cache and then have a windows service check that every 1 sec
                var listOfProducts = new Dictionary <long, long>();
                foreach (var productsData in checkoutModel.ProductsData)
                {
                    if (productsData.ProductData != null)
                    {
                        listOfProducts.Add(productsData.ProductData.Id, productsData.Quantity);
                    }
                }

                var products          = new ProductsQuery().GetFromDatabase(listOfProducts.Keys.ToList());
                var sameAsHomeAddress = checkoutModel.SameAddress;
                if (sameAsHomeAddress)
                {
                    personAddress = new PersonQuery().GetPersonWithAddress(user.Id);
                }
                using (var transaction = _saveToDatabase.GetTraction())
                {
                    decimal totalPayablePrice = 0;
                    var     order             = new Order()
                    {
                        OrderedTime       = DateTime.Now,
                        PersonId          = user.Id,
                        ShippingCharges   = checkoutModel.ShippingCharges,
                        TotalPayablePrice = totalPayablePrice
                    };
                    _saveToDatabase.Save(order);
                    var randorNumber = new Random(12);
                    foreach (var product in products)
                    {
                        var cost = 0M;
                        if (listOfProducts.TryGetValue(product.Id, out var quant))
                        {
                            cost = quant * product.Price;
                            totalPayablePrice = totalPayablePrice + cost;
                            var productOrder = new ProductOrder()
                            {
                                OrderId       = order.Id,
                                OrderDateTime = DateTime.Now,
                                ProductId     = product.Id,
                                Quantity      = quant,
                                Status        = Status.Success,
                                UpdatedBy     = user.FirstName
                            };
                            _saveToDatabase.Save(productOrder);


                            var shippingAddress = new ShippingAddress
                            {
                                AddressLine1 = sameAsHomeAddress ? personAddress.Address.AddressLine1 ?? checkoutModel.AddressLine1 : null,
                                AddressLine2 = sameAsHomeAddress ? personAddress.Address.AddressLine2 ?? checkoutModel.AddressLine2 : null,
                                //  ApartmentNo = checkoutModel.ApartmentNo,
                                CreateDate     = DateTime.Now,
                                CreateDateTime = DateTime.Now,
                                HouseNo        = checkoutModel.HouseNo,
                                //PoBox = checkoutModel.PoBox,
                                ProductOrderId    = productOrder.Id,
                                SameAsHomeAddress = sameAsHomeAddress,
                                State             = sameAsHomeAddress ? personAddress.Address.State ?? checkoutModel.State: null,
                                ZipCode           = sameAsHomeAddress ? personAddress.Address.ZipCode : checkoutModel.ZipCode,
                                ShippingCompany   = "My Company",
                                UpdateDate        = DateTime.Now,
                                UpdatedBy         = "System",
                                TrackingId        = randorNumber.Next(1000) //can call a webservice to shipping company and get data
                            };
                            _saveToDatabase.Save(shippingAddress);
                        }
                    }
                    _saveToDatabase.Update(order);
                    transaction.Complete();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var actionResult = new JsonResult()
            {
                Data = new { success = "Order Submitted", response = "/products" }, ContentType = "json", JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            return(actionResult);
        }
                        public async Task CreatesPackageOwnerRequestSendsEmailAndReturnsPendingState(Func <Fakes, User> getCurrentUser, Func <Fakes, User> getUserToAdd)
                        {
                            var fakes = Get <Fakes>();

                            var currentUser = getCurrentUser(fakes);
                            var userToAdd   = getUserToAdd(fakes);

                            var controller = GetController <JsonApiController>();

                            controller.SetCurrentUser(currentUser);

                            var packageOwnershipManagementServiceMock = GetMock <IPackageOwnershipManagementService>();
                            var messageServiceMock = GetMock <IMessageService>();

                            var pending = !(ActionsRequiringPermissions.HandlePackageOwnershipRequest.CheckPermissions(currentUser, userToAdd) == PermissionsCheckResult.Allowed);

                            if (pending)
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnershipRequestAsync(fakes.Package, currentUser, userToAdd))
                                .Returns(Task.FromResult(new PackageOwnerRequest {
                                    ConfirmationCode = "confirmation-code"
                                }))
                                .Verifiable();

                                messageServiceMock
                                .Setup(m => m.SendMessageAsync(It.IsAny <PackageOwnershipRequestMessage>(), false, false))
                                .Callback <IEmailBuilder, bool, bool>((msg, copySender, discloseSenderAddress) =>
                                {
                                    var message = msg as PackageOwnershipRequestMessage;
                                    Assert.Equal(currentUser, message.FromUser);
                                    Assert.Equal(userToAdd, message.ToUser);
                                    Assert.Equal(fakes.Package, message.PackageRegistration);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + "packages/FakePackage/", message.PackageUrl);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/confirm/confirmation-code", message.ConfirmationUrl);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/reject/confirmation-code", message.RejectionUrl);
                                    Assert.Equal("Hello World! Html Encoded &lt;3", message.HtmlEncodedMessage);
                                    Assert.Equal(string.Empty, message.PolicyMessage);
                                })
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendMessageAsync(
                                               It.Is <PackageOwnershipRequestInitiatedMessage>(
                                                   msg =>
                                                   msg.RequestingOwner == currentUser &&
                                                   msg.ReceivingOwner == owner &&
                                                   msg.NewOwner == userToAdd &&
                                                   msg.PackageRegistration == fakes.Package),
                                               false,
                                               false))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }
                            else
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnerAsync(fakes.Package, userToAdd, true))
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendMessageAsync(
                                               It.Is <PackageOwnerAddedMessage>(
                                                   msg =>
                                                   msg.ToUser == owner &&
                                                   msg.NewOwner == userToAdd &&
                                                   msg.PackageRegistration == fakes.Package),
                                               false,
                                               false))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }

                            JsonResult result = await controller.AddPackageOwner(fakes.Package.Id, userToAdd.Username, "Hello World! Html Encoded <3");

                            dynamic data = result.Data;
                            PackageOwnersResultViewModel model = data.model;

                            Assert.True(data.success);
                            Assert.Equal(userToAdd.Username, model.Name);
                            Assert.Equal(pending, model.Pending);

                            packageOwnershipManagementServiceMock.Verify();
                            messageServiceMock.Verify();
                        }
예제 #39
0
 public static JsonResult WithInfo(this JsonResult result, string message)
 {
     return(new AlertJsonDecoratorResult(result, "alert-info", message));
 }
예제 #40
0
        public ActionResult Te()
        {
            int      Tempoid     = 1;
            DateTime CurrentDate = new DateTime();

            CurrentDate = GetCurrentSession.CurrentDateTime();
            #region Print
            string joindata = string.Join(", ", "1,2,3");

            SqlParameter       param1          = new SqlParameter("@Var", joindata);
            List <rptCustomer> rptCustomerList = db.Database.SqlQuery <rptCustomer>("SP_PickUpboy @Var", param1).ToList();
            var    LoginList   = db.Logins.ToList();
            string PrintBy     = string.Empty;
            int    CurrentUser = (int)GetCurrentSession.CurrentUser();
            var    login       = LoginList.FirstOrDefault(t => t.LoginID == CurrentUser);
            if (login != null)
            {
                PrintBy = login.FirstName + " " + login.LastName;
            }

            //List<rptCustomer> rptCustomerList = context.Database.SqlQuery<rptCustomer>("SP_PickUpboy @Var", param1).ToList<rptCustomer>();
            DataTable dtBoyName = new DataTable();
            dtBoyName.Columns.Add("Name", typeof(string));


            var boy = db.PickUpBoys.FirstOrDefault(t => t.PickUpBoyID == Tempoid);
            if (boy != null)
            {
                dtBoyName.Rows.Add("Delivery Boy:-  " + boy.PickUpBoyName + "\t Print By:- " + PrintBy);
            }
            else
            {
                dtBoyName.Rows.Add("");
            }

            DataTable dtCustomer = new DataTable();
            dtCustomer.Columns.Add("LRNo", typeof(string));
            dtCustomer.Columns.Add("CustomerName", typeof(string));
            dtCustomer.Columns.Add("PayTypeStatus", typeof(string));
            dtCustomer.Columns.Add("Amount", typeof(decimal));
            dtCustomer.Columns.Add("Total", typeof(decimal));
            dtCustomer.Columns.Add("Damrage", typeof(decimal));
            dtCustomer.Columns.Add("Hamali", typeof(decimal));
            dtCustomer.Columns.Add("NoOfParcel", typeof(int));
            dtCustomer.Columns.Add("CustomerNumber", typeof(string));
            foreach (var item in rptCustomerList)
            {
                dtCustomer.Rows.Add(item.LRNo, item.CustomerName, item.PayTypeStatus, item.Amount,
                                    item.Total, item.Damrage, item.Hamali * item.NoOfParcel, item.NoOfParcel, item.CustomerNumber);
            }

            DataSet1 myds = new DataSet1();
            myds.Tables["DtPickupBoy"].Merge(dtCustomer);
            myds.Tables["DtBoyName"].Merge(dtBoyName);

            ReportDocument rptH = new ReportDocument();
            rptH.Load(Server.MapPath("~/Reports/rptPickUpboy.rpt"));
            rptH.SetDataSource(myds);
            Response.Buffer = false;
            Response.ClearContent();
            Response.ClearHeaders();

            string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string path         = Server.MapPath("~/PDF");
            AllClass.CreateDirectory(path);
            string fileName  = path + "/" + htmlfilename + ".pdf";
            string fileName2 = htmlfilename + ".pdf";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            rptH.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, fileName);

            JsonResult result = new JsonResult();
            result.Data = fileName2;
            return(result);

            #endregion
        }
예제 #41
0
 public static JsonResult WithError(this JsonResult result, string message)
 {
     return(new AlertJsonDecoratorResult(result, "alert-danger", message));
 }
예제 #42
0
        public async Task Test_TicketsController_GetTicketLogsForUser()
        {
            // Setup.
            SeedDatabase();
            TicketsController controllerUnderTest = new TicketsController(Database);

            // Check that the controller handles incorrect paramters.
            if (await controllerUnderTest.GetTicketLogsForUser(null, null, null) != null)
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }
            if (await controllerUnderTest.GetTicketLogsForUser("", "", "") != null)
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }
            if (await controllerUnderTest.GetTicketLogsForUser("not_a_number", "could_be_valid", "could_be_valid") != null)
            {
                Assert.Fail("Controller not handling incorrect parameters.");
            }

            // Setup (Get a valid User to test with).
            User user = Database.Users.First();

            if (user == null)
            {
                Assert.Fail("Seeded database not as expected for this test.");
            }
            string     userId        = user.Id;                                                           // Used as a cache to get the same User later on.
            JsonResult userTokenJson = await new UserController(Database).GetNewUserToken(user.UserName); // This Controller has been tested independently.

            if (userTokenJson == null)                                                                    // Check that we didn't get an error from the controller and that we can continue.
            {
                Assert.Fail("Problem getting User Token for testing.");
            }
            user = Database.Users.FirstOrDefault(u => u.Id == userId); // Re-get the User from the database, as UserController should have changed it.
            if (user == null)
            {
                Assert.Fail("Logic problem with test, cannot continue.");
            }

            // Test that the controller returns the ticket that was requested.
            JsonResult ticketLogsJson = await controllerUnderTest.GetTicketLogsForUser("1", user.UserName, user.UserToken);

            if (ticketLogsJson == null)
            {
                Assert.Fail("Recieved an error from the controller.");
            }
            if (ticketLogsJson.ContentType != "TicketLogs")
            {
                Assert.Fail("Recieved incorrect data from controller.");
            }
            dynamic ticketLogs = ticketLogsJson.Data;

            if (ticketLogs.Count != 3)
            {
                Assert.Fail("Did not receive the correct data from the controller.");
            }
            if (!(ticketLogs[0] is ApiTicketLogViewModel))
            {
                Assert.Fail("Recieved incorrect data type from controller.");
            }

            // TODO: Check for the handling of the User being internal/not internal.
        }
        public JsonResult FinancialDisplayFill(FinancialDisplayViewModel vm)
        {
            FinancialDisplaySettings SettingParameter = SetCurrentParameterSettings(vm);

            if (vm.ReportType == ReportType_TrialBalance)
            {
                if (vm.DisplayType == DisplayType_Balance)
                {
                    if (vm.IsShowDetail == true)
                    {
                        if (vm.IsFullHierarchy == true)
                        {
                            IEnumerable <TrialBalanceViewModel> TrialBalanceDetail = _FinancialDisplayService.GetTrialBalanceDetailWithFullHierarchy(SettingParameter);

                            if (TrialBalanceDetail != null)
                            {
                                JsonResult json = Json(new { Success = true, Data = TrialBalanceDetail.ToList() }, JsonRequestBehavior.AllowGet);
                                json.MaxJsonLength = int.MaxValue;
                                return(json);
                            }
                        }
                        else
                        {
                            IEnumerable <TrialBalanceViewModel> TrialBalanceDetail = _FinancialDisplayService.GetTrialBalanceDetail(SettingParameter);

                            if (TrialBalanceDetail != null)
                            {
                                JsonResult json = Json(new { Success = true, Data = TrialBalanceDetail.ToList() }, JsonRequestBehavior.AllowGet);
                                json.MaxJsonLength = int.MaxValue;
                                return(json);
                            }
                        }
                    }
                    else
                    {
                        IEnumerable <TrialBalanceViewModel> TrialBalance = _FinancialDisplayService.GetTrialBalance(SettingParameter);

                        if (TrialBalance != null)
                        {
                            JsonResult json = Json(new { Success = true, Data = TrialBalance.ToList() }, JsonRequestBehavior.AllowGet);
                            json.MaxJsonLength = int.MaxValue;
                            return(json);
                        }
                    }
                }
                else if (vm.DisplayType == DisplayType_Summary)
                {
                    if (vm.IsShowDetail == true)
                    {
                        if (vm.IsFullHierarchy == true)
                        {
                            IEnumerable <TrialBalanceSummaryViewModel> TrialBalanceSummary = _FinancialDisplayService.GetTrialBalanceDetailSummaryWithFullHierarchy(SettingParameter);

                            if (TrialBalanceSummary != null)
                            {
                                JsonResult json = Json(new { Success = true, Data = TrialBalanceSummary.ToList() }, JsonRequestBehavior.AllowGet);
                                json.MaxJsonLength = int.MaxValue;
                                return(json);
                            }
                        }
                        else
                        {
                            IEnumerable <TrialBalanceSummaryViewModel> TrialBalanceSummary = _FinancialDisplayService.GetTrialBalanceDetailSummary(SettingParameter);

                            if (TrialBalanceSummary != null)
                            {
                                JsonResult json = Json(new { Success = true, Data = TrialBalanceSummary.ToList() }, JsonRequestBehavior.AllowGet);
                                json.MaxJsonLength = int.MaxValue;
                                return(json);
                            }
                        }
                    }
                    else
                    {
                        IEnumerable <TrialBalanceSummaryViewModel> TrialBalanceSummary = _FinancialDisplayService.GetTrialBalanceSummary(SettingParameter);

                        if (TrialBalanceSummary != null)
                        {
                            JsonResult json = Json(new { Success = true, Data = TrialBalanceSummary.ToList() }, JsonRequestBehavior.AllowGet);
                            json.MaxJsonLength = int.MaxValue;
                            return(json);
                        }
                    }
                }
            }
            else if (vm.ReportType == ReportType_SubTrialBalance)
            {
                if (vm.DisplayType == DisplayType_Balance)
                {
                    IEnumerable <SubTrialBalanceViewModel> SubTrialBalance = _FinancialDisplayService.GetSubTrialBalance(SettingParameter);

                    if (SubTrialBalance != null)
                    {
                        JsonResult json = Json(new { Success = true, Data = SubTrialBalance.ToList() }, JsonRequestBehavior.AllowGet);
                        json.MaxJsonLength = int.MaxValue;
                        return(json);
                    }
                }
                else if (vm.DisplayType == DisplayType_Summary)
                {
                    IEnumerable <SubTrialBalanceSummaryViewModel> SubTrialBalanceSummary = _FinancialDisplayService.GetSubTrialBalanceSummary(SettingParameter);

                    if (SubTrialBalanceSummary != null)
                    {
                        JsonResult json = Json(new { Success = true, Data = SubTrialBalanceSummary.ToList() }, JsonRequestBehavior.AllowGet);
                        json.MaxJsonLength = int.MaxValue;
                        return(json);
                    }
                }
            }
            else if (vm.ReportType == ReportType_Ledger)
            {
                if (vm.LedgerAccount != null)
                {
                    IEnumerable <LedgerBalanceViewModel> LedgerBalance = _FinancialDisplayService.GetLedgerBalance(SettingParameter);

                    if (LedgerBalance != null)
                    {
                        JsonResult json = Json(new { Success = true, Data = LedgerBalance.ToList() }, JsonRequestBehavior.AllowGet);
                        json.MaxJsonLength = int.MaxValue;
                        return(json);
                    }
                }
            }


            return(Json(new { Success = true }, JsonRequestBehavior.AllowGet));
        }
예제 #44
0
        public ReceiptResponse GetReceipt(string txHash)
        {
            JsonResult response = (JsonResult)this.smartContractsController.GetReceipt(txHash);

            return((ReceiptResponse)response.Value);
        }
                        public async Task CreatesPackageOwnerRequestSendsEmailAndReturnsPendingState(Func <Fakes, User> getCurrentUser, Func <Fakes, User> getUserToAdd)
                        {
                            var fakes = Get <Fakes>();

                            var currentUser = getCurrentUser(fakes);
                            var userToAdd   = getUserToAdd(fakes);

                            var controller = GetController <JsonApiController>();

                            controller.SetCurrentUser(currentUser);

                            var packageOwnershipManagementServiceMock = GetMock <IPackageOwnershipManagementService>();
                            var messageServiceMock = GetMock <IMessageService>();

                            var pending = !(ActionsRequiringPermissions.HandlePackageOwnershipRequest.CheckPermissions(currentUser, userToAdd) == PermissionsCheckResult.Allowed);

                            if (pending)
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnershipRequestAsync(fakes.Package, currentUser, userToAdd))
                                .Returns(Task.FromResult(new PackageOwnerRequest {
                                    ConfirmationCode = "confirmation-code"
                                }))
                                .Verifiable();

                                messageServiceMock
                                .Setup(m => m.SendPackageOwnerRequest(
                                           currentUser,
                                           userToAdd,
                                           fakes.Package,
                                           TestUtility.GallerySiteRootHttps + "packages/FakePackage/",
                                           TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/confirm/confirmation-code",
                                           TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/reject/confirmation-code",
                                           "Hello World! Html Encoded &lt;3",
                                           ""))
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendPackageOwnerRequestInitiatedNotice(
                                               currentUser,
                                               owner,
                                               userToAdd,
                                               fakes.Package,
                                               It.IsAny <string>()))
                                    .Verifiable();
                                }
                            }
                            else
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnerAsync(fakes.Package, userToAdd))
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendPackageOwnerAddedNotice(
                                               owner,
                                               userToAdd,
                                               fakes.Package,
                                               It.IsAny <string>()))
                                    .Verifiable();
                                }
                            }

                            JsonResult result = await controller.AddPackageOwner(fakes.Package.Id, userToAdd.Username, "Hello World! Html Encoded <3");

                            dynamic data = result.Data;
                            PackageOwnersResultViewModel model = data.model;

                            Assert.True(data.success);
                            Assert.Equal(userToAdd.Username, model.Name);
                            Assert.Equal(pending, model.Pending);

                            packageOwnershipManagementServiceMock.Verify();
                            messageServiceMock.Verify();
                        }
예제 #46
0
        public ActionResult GetZoneAJAXData()
        {
            // Initialization.
            JsonResult result = new JsonResult();

            try
            {
                // Initialization.

                int SearchByResellerID = 0;
                int ifSearch           = 0;
                int totalRecords       = 0;
                int recFilter          = 0;
                // Initialization.
                string search   = Request.Form.GetValues("search[value]")[0];
                string draw     = Request.Form.GetValues("draw")[0];
                string order    = Request.Form.GetValues("order[0][column]")[0];
                string orderDir = Request.Form.GetValues("order[0][dir]")[0];
                int    startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
                int    pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);

                var ResellerID = Request.Form.Get("ResellerID");

                if (!string.IsNullOrEmpty(ResellerID))
                {
                    SearchByResellerID = int.Parse(ResellerID);
                }

                IEnumerable <Zone>    lstZone   = Enumerable.Empty <Zone>();
                IEnumerable <dynamic> finalItem = Enumerable.Empty <dynamic>();
                lstZone = db.Zone.AsQueryable();


                if (AppUtils.GetLoginRoleID() == AppUtils.ResellerRole)
                {
                    int loginResellerID = AppUtils.GetLoginUserID();
                    lstZone = db.Zone.Where(x => x.ResellerID == loginResellerID).AsQueryable();
                }
                else if (AppUtils.GetLoginRoleID() != AppUtils.ResellerRole && SearchByResellerID > 0)
                // mean data is loaded already and now admin is searching by reseller id for resller zone list
                {
                    lstZone = db.Zone.Where(x => x.ResellerID == SearchByResellerID).AsQueryable();
                }
                else
                {
                    lstZone = db.Zone.Where(x => x.ResellerID == null).AsQueryable();
                }

                if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
                {
                    ifSearch = (lstZone.Any()) ? lstZone.Where(p => p.ZoneName.ToString().ToLower().Contains(search.ToLower())).Count() : 0;
                    // Apply search
                    lstZone = lstZone.Where(p => p.ZoneName.ToString().ToLower().Contains(search.ToLower())).AsQueryable();
                }

                if (lstZone.Any())
                {
                    totalRecords = lstZone.Count();
                    finalItem    = lstZone.AsEnumerable().Skip(startRec).Take(pageSize)
                                   .Select(
                        s => new
                    {
                        ZoneID       = s.ZoneID,
                        ZoneName     = s.ZoneName,
                        UpdateStatus = ISP_ManagementSystemModel.AppUtils.HasAccessInTheList(ISP_ManagementSystemModel.AppUtils.Update_Zone) ? true : false
                    }).ToList();
                }

                // Sorting.
                finalItem = this.SortByColumnWithOrder(order, orderDir, finalItem);
                // Total record count.
                // totalRecords = secondpart.AsEnumerable().Count();//(!string.IsNullOrEmpty(search) &&  !string.IsNullOrWhiteSpace(search))? data.AsEnumerable().Count():
                // Filter record count.
                recFilter = (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search)) ? ifSearch : totalRecords;

                ////////////////////////////////////


                // Loading drop down lists.
                result = this.Json(new
                {
                    draw            = Convert.ToInt32(draw),
                    recordsTotal    = totalRecords,
                    recordsFiltered = recFilter,
                    data            = finalItem
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }
            // Return info.
            return(result);
        }
예제 #47
0
        public Task <IActionResult> GetAsync(string content)
        {
            JsonResult userid = new JsonResult(from c in User.Claims select new { c.Type, c.Value });

            return(Task.FromResult(Success(content)));
        }
예제 #48
0
        /// <summary>
        /// Retrieves receipts for all cases where a specific event was logged in a specific contract.
        /// </summary>
        public IList <ReceiptResponse> GetReceipts(string contractAddress, string eventName)
        {
            JsonResult response = (JsonResult)this.smartContractsController.ReceiptSearch(contractAddress, eventName).Result;

            return((IList <ReceiptResponse>)response.Value);
        }
예제 #49
0
        public ActionResult Get(string name)
        {
            var result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            switch (name)
            {
            case "Cards":
                result.Data = "This method is no longer supported for performance reasons. Use export/PlayerCards, export/EncounterCards or export/QuestCards instead. Thanks for your support!";     //cardRepository.Cards().Where(x => x.CardSet.SetType != SetType.CUSTOM).Select(x => new SimpleCard(x)).ToList();
                break;

            case "PlayerCards":
                result.Data = cardRepository.Cards().Where(x => x.CardSet.SetType != SetType.CUSTOM && IsPlayerCard(x)).Select(y => new SimpleCard(y)).ToList();
                break;

            case "EncounterCards":
                result.Data = cardRepository.Cards().Where(x => x.CardSet.SetType != SetType.CUSTOM && IsEncounterCard(x)).Select(y => new SimpleCard(y)).ToList();
                break;

            case "QuestCards":
                result.Data = cardRepository.Cards().Where(x => x.CardSet.SetType != SetType.CUSTOM && IsQuestCard(x)).Select(y => new SimpleCard(y)).ToList();
                break;

            case "Scenarios":
                var scenarios = new List <SimpleScenario>();
                foreach (var group in scenarioService.ScenarioGroups())
                {
                    foreach (var item in group.Scenarios)
                    {
                        var scenario = new SimpleScenario()
                        {
                            Title = item.Title, Number = (uint)item.Number
                        };

                        foreach (var quest in item.QuestCards.Select(x => x.Quest))
                        {
                            scenario.QuestCards.Add(new SimpleCard(quest));
                        }

                        foreach (var card in item.ScenarioCards)
                        {
                            scenario.ScenarioCards.Add(new SimpleScenarioCard()
                            {
                                EncounterSet      = card.EncounterSet,
                                Title             = card.Title,
                                NormalQuantity    = (uint)card.NormalQuantity,
                                EasyQuantity      = (uint)card.EasyQuantity,
                                NightmareQuantity = (uint)card.NightmareQuantity
                            });
                        }

                        scenarios.Add(scenario);
                    }
                }

                result.Data = scenarios;
                break;

            case "CardSets":
                result.Data = scenarioService.CardSets().Select(x => new SimpleCardSet {
                    Name = x.Name, Cycle = x.Cycle, SetType = x.SetType.ToString()
                }).ToList();
                break;

            case "EncounterSets":
                result.Data = scenarioService.EncounterSetNames();
                break;

            default:
                if (!string.IsNullOrEmpty(name))
                {
                    result.Data = "Unknown record type: " + name;
                }
                else
                {
                    result.Data = "Undefined record type";
                }
                break;
            }

            return(result);
        }
예제 #50
0
        public void PageModelActionTester_TestJsonResult_should_return_JsonResult()
        {
            JsonResult JsonResult = _pageTester.Action(x => x.Json).TestJsonResult();

            Assert.IsNotNull(JsonResult);
        }
예제 #51
0
 protected string ToJson(JsonResult model)
 {
     Jayrock.Json.JsonTextWriter writer = new Jayrock.Json.JsonTextWriter();
     Jayrock.Json.Conversion.JsonConvert.Export(model, writer);
     return writer.ToString();
 }
예제 #52
0
        public void NullContentIsNotOutput()
        {
            // Arrange
            string contentType = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();

            JsonResult result = new JsonResult
            {
                ContentType = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
예제 #53
0
        public IActionResult getAllString()
        {
            var result = new JsonResult(_stringService.getAll());

            return(result);
        }
예제 #54
0
        public void GetRequestBlocked()
        {
            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("GET").Verifiable();

            JsonResult result = new JsonResult();

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => result.ExecuteResult(mockControllerContext.Object),
                "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");

            mockControllerContext.Verify();
        }
예제 #55
0
        public void NullRecursionLimitDefaultIsUsed()
        {
            // Arrange
            Tuple<string, Tuple<string, Tuple<string, string>>> data =
                new Tuple<string, Tuple<string, Tuple<string, string>>>("key1",
                                                                        new Tuple<string, Tuple<string, string>>("key2",
                                                                                                                 new Tuple<string, string>("key3", "value")
                                                                            )
                    );
            string jsonData = "{\"Item1\":\"key1\",\"Item2\":{\"Item1\":\"key2\",\"Item2\":{\"Item1\":\"key3\",\"Item2\":\"value\"}}}";

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = "application/json").Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();

            JsonResult result = new JsonResult
            {
                Data = data
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
예제 #56
0
        public void RecursionLimitIsPassedToSerilizer()
        {
            // Arrange
            Tuple<string, Tuple<string, Tuple<string, string>>> data =
                new Tuple<string, Tuple<string, Tuple<string, string>>>("key1",
                                                                        new Tuple<string, Tuple<string, string>>("key2",
                                                                                                                 new Tuple<string, string>("key3", "value")
                                                                            )
                    );
            string jsonData = "{\"Item1\":\"key1\",\"Item2\":{\"Item1\":\"key2\",\"Item2\":{\"Item1\":\"key3\",\"Item2\":\"value\"}}}";

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = "application/json").Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();

            JsonResult result = new JsonResult
            {
                Data = data,
                RecursionLimit = 2
            };

            // Act & Assert
            Assert.Throws<ArgumentException>(
                () => result.ExecuteResult(mockControllerContext.Object),
                "RecursionLimit exceeded.");
        }
예제 #57
0
        public void MaxJsonLengthIsPassedToSerializer()
        {
            // Arrange
            string data = new String('1', 2100000);
            string jsonData = "\"" + data + "\"";

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = "application/json").Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();

            JsonResult result = new JsonResult
            {
                Data = data,
                MaxJsonLength = 2200000
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
예제 #58
0
        public void NullMaxJsonLengthDefaultIsUsed()
        {
            // Arrange
            string data = new String('1', 2100000);

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = "application/json").Verifiable();

            JsonResult result = new JsonResult
            {
                Data = data
            };

            // Act & Assert 
            Assert.Throws<InvalidOperationException>(
                () => result.ExecuteResult(mockControllerContext.Object),
                "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.");
        }
예제 #59
-1
        public void ExecuteResult()
        {
            // Arrange
            object data = _jsonData;
            string contentType = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);
            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("POST").Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();

            JsonResult result = new JsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
예제 #60
-1
        public void ProcessRequest(HttpContext context)
        {
            JsonResult jsonResult = new JsonResult();
            //参数处理
            string operationType = context.Request.Form["op"];
            int intOperation;
            if (!int.TryParse(operationType, out intOperation))
            {
                intOperation = 0;
            }
            switch (intOperation)
            {
                case 1:
                {
                    jsonResult.Status = 1;
                    jsonResult.Msg = "Success";
                    context.Response.Write(JsonConvert.SerializeObject(jsonResult));
                    break;

                }
                default:
                {
                    context.Response.ContentType = "application/json";
                    var result = _accountDescriptionDataAccess.GetAccountInfoModelsList(" OrderStatus =3");
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    break;
                }
            }
        }