Example #1
0
        public async Task ObjectResult_WithMultipleContentTypesAndAcceptHeaders_PerformsContentNegotiation(
            IEnumerable<string> contentTypes, string acceptHeader, string expectedHeader)
        {
            // Arrange
            var expectedContentType = expectedHeader;
            var input = "testInput";
            var stream = new MemoryStream();

            var httpResponse = new Mock<HttpResponse>();
            var tempContentType = string.Empty;
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object, acceptHeader);

            var result = new ObjectResult(input);

            // Set the content type property explicitly.
            result.ContentTypes = contentTypes.Select(contentType => MediaTypeHeaderValue.Parse(contentType)).ToList();
            result.Formatters = new List<IOutputFormatter>
                                            {
                                                new CannotWriteFormatter(),
                                                new JsonOutputFormatter(),
                                            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // should always select the Json Output formatter even though it is second in the list.
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
        public void OnActionExecuted([NotNull] ActionExecutedContext context)
        {
            var httpResponseException = context.Exception as HttpResponseException;
            if (httpResponseException != null)
            {
                var request = context.HttpContext.GetHttpRequestMessage();
                var response = httpResponseException.Response;

                if (response != null && response.RequestMessage == null)
                {
                    response.RequestMessage = request;
                }

                var objectResult = new ObjectResult(response)
                {
                    DeclaredType = typeof(HttpResponseMessage)
                };

                context.Result = objectResult;

                // Its marked as handled as in webapi because an HttpResponseException
                // was considered as a 'success' response.
                context.ExceptionHandled = true;
            }
        }
        public GameData GameAndAreaAndRoomResultsFromDb(ObjectResult<ReadGameStateForPlayer_Result> gameStateResults)
        {
            GameState gameState = null;
            AreaData areaData = null;

            gameState = gameStateResults.Select(x => new GameState() { LastTime = x.LastTime, StopTime = x.StopTime }).SingleOrDefault();

            var areaResults = gameStateResults.GetNextResult<ReadArea_Result>();
            areaData = AreaAndRoomResultsFromDb(areaResults);

            return new GameData(gameState, areaData.Item1, areaData.Item2, areaData.Item3, areaData.Item4);
        }
        public AreaData AreaAndRoomResultsFromDb(ObjectResult<ReadArea_Result> areaResults)
        {
            Area area = null;
            RoomData roomData = null;

            area = TypeAdapter.Adapt<Area>(areaResults.Single());

            var roomResults = areaResults.GetNextResult<ReadRoom_Result>();
            roomData = RoomResultsFromDB(roomResults);

            return new AreaData(area, roomData.Item1, roomData.Item2, roomData.Item3);
        }
Example #5
0
        public async Task ExecuteAsync_ContentTypeProvidedFromResponseAndObjectResult_UsesResponseContentType()
        {
            // Arrange
            var executor = CreateCustomObjectResultExecutor();
            var httpContext = new DefaultHttpContext();
            var actionContext = new ActionContext() { HttpContext = httpContext };
            httpContext.Request.Headers[HeaderNames.Accept] = "application/xml"; // This will not be used
            httpContext.Response.ContentType = "text/plain";
            var result = new ObjectResult("input");
            result.Formatters.Add(new TestXmlOutputFormatter());
            result.Formatters.Add(new TestJsonOutputFormatter());
            result.Formatters.Add(new TestStringOutputFormatter()); // This will be chosen based on the content type

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

            // Assert
            Assert.IsType<TestStringOutputFormatter>(executor.SelectedOutputFormatter);
            MediaTypeAssert.Equal("text/plain; charset=utf-8", httpContext.Response.ContentType);
        }
Example #6
0
        private List<ObjectResult> parseObjectListWithMetadata(string responseStr)
        {
            List<ObjectResult> objs = new List<ObjectResult>();
            try
            {
                XmlDocument d = new XmlDocument();
                d.LoadXml(responseStr);

                XmlNodeList olist = d.GetElementsByTagName("Object");
                log.TraceEvent(TraceEventType.Verbose, 0, "Found " + olist.Count + " results");
                foreach (XmlNode xn in olist)
                {
                    ObjectResult obj = new ObjectResult();
                    // Get the objectId
                    obj.Id = new ObjectId(getChildByName("ObjectID", xn.ChildNodes).InnerText);

                    // Next, get the metadata
                    obj.meta = new MetadataList();
                    XmlNode sMetaNode = getChildByName("SystemMetadataList", xn.ChildNodes);
                    XmlNode uMetaNode = getChildByName("UserMetadataList", xn.ChildNodes);

                    if (sMetaNode != null)
                    {
                        foreach (XmlNode metaNode in sMetaNode.ChildNodes)
                        {
                            if (!metaNode.LocalName.Equals("Metadata"))
                            {
                                continue;
                            }

                            string mName = getChildByName("Name", metaNode.ChildNodes).InnerText;
                            string mValue = getChildByName("Value", metaNode.ChildNodes).InnerText;

                            obj.meta.AddMetadata(new Metadata(mName, mValue, false));
                        }
                    }

                    if (uMetaNode != null)
                    {
                        foreach (XmlNode metaNode in uMetaNode.ChildNodes)
                        {
                            if (!metaNode.LocalName.Equals("Metadata"))
                            {
                                continue;
                            }

                            string mName = getChildByName("Name", metaNode.ChildNodes).InnerText;
                            string mValue = getChildByName("Value", metaNode.ChildNodes).InnerText;
                            string mListable = getChildByName("Listable", metaNode.ChildNodes).InnerText;

                            obj.meta.AddMetadata(new Metadata(mName, mValue, "true".Equals(mListable)));
                        }
                    }

                    objs.Add(obj);
                }

            }
            catch (XmlException e)
            {
                throw new EsuException("Error parsing xml object list", e);
            }

            return objs;
        }
        //[Authorize(Roles = "AddMenuRole")]
        public IActionResult Create([FromBody] MenuRoleViewModel menuRoleViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IActionResult result    = new ObjectResult(false);
            GenericResult addResult = null;

            try
            {
                if (menuRoleViewModel.MenuLink == "/")
                {
                    menuRoleViewModel.MenuLink = "";
                }

                var menuTrangChu = _menuRoleService.GetMenuRoleByName("Home");


                int IdMenuCap1 = menuTrangChu.MenuId;



                MenuRole menuRole = new MenuRole();


                menuRole = Mapper.Map <MenuRoleViewModel, MenuRole>(menuRoleViewModel);

                if (menuRole.MenuId == IdMenuCap1)
                {
                    menuRole.MenuLevel = 1;
                }

                if (menuRole.MenuParent == IdMenuCap1)
                {
                    menuRole.MenuLevel = 2;
                }
                else
                {
                    menuRole.MenuLevel = 3;
                }
                menuRole.MenuId = 0;
                _menuRoleService.Add(menuRole);
                _menuRoleService.Save();
                addResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Thêm menu thành công"
                };
            }
            catch (Exception ex)
            {
                addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            result = new ObjectResult(addResult);
            return(result);
        }
Example #8
0
        public IActionResult CreateToken([FromForm] AuthenticationModel authen)
        {
            IActionResult response  = Unauthorized();
            var           objResult = new ObjectResult(String.Empty);

            try
            {
                if (ModelState.IsValid) // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API
                {
                    if (authen.grant_type.ToLower() == GRANT_TYPE_CLIENT_CREDENTIALS)
                    {
                        if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null)
                        {
                            if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null)
                            {
                                var appAudObj = GetAppAudiencesById(authen.client_id).Result;

                                if (appAudObj != null)
                                {
                                    if (appAudObj.ExpiryDate > DateTime.UtcNow)
                                    {
                                        if (appAudObj.AppSecretKey == authen.client_secret)
                                        {
                                            var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_CLIENT_CREDENTIALS, authen.authen_to_system, authen.code);
                                            var accessTokenObj  = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_CLIENT_CREDENTIALS);

                                            var tokenResp = new TokenResponse();
                                            tokenResp.token_type               = "Bearer";
                                            tokenResp.access_token             = accessTokenObj.AccessToken;
                                            tokenResp.expires_in               = _config["Jwt:Expires"];
                                            tokenResp.refresh_token            = refreshTokenObj.RefreshToken;
                                            tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"];

                                            response = Ok(tokenResp);
                                        }
                                        else
                                        {
                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid.");
                                        }
                                    }
                                    else
                                    {
                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ").");
                                    }
                                }
                                else
                                {
                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid.");
                                }
                            }
                            else
                            {
                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty.");
                            }
                        }
                        else
                        {
                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty.");
                        }
                    }
                    else if (authen.grant_type.ToLower() == GRANT_TYPE_PASSWORD)
                    {
                        if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null)
                        {
                            if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null)
                            {
                                if (authen.username != string.Empty && authen.username != "null" && authen.username != null)
                                {
                                    if (authen.password != string.Empty && authen.password != "null" && authen.password != null)
                                    {
                                        if (authen.authen_to_system != string.Empty && authen.authen_to_system != "null" && authen.authen_to_system != null)
                                        {
                                            var appAudObj = GetAppAudiencesById(authen.client_id).Result;

                                            if (appAudObj != null)
                                            {
                                                if (appAudObj.ExpiryDate > DateTime.UtcNow)
                                                {
                                                    if (appAudObj.AppSecretKey == authen.client_secret)
                                                    {
                                                        var IsValidated = false;

                                                        switch (authen.authen_to_system.ToLower())
                                                        {
                                                        case "mtl-agent":
                                                            // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL AGENT SYSTEM
                                                            break;

                                                        case "mtl-smileclub":
                                                            // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL SMILE CLUB SYSTEM
                                                            break;

                                                        case "mtl-employee":
                                                            // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL EMPLOYEE SYSTEM
                                                            IsValidated = true;
                                                            break;
                                                        }

                                                        if (IsValidated)
                                                        {
                                                            var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_PASSWORD, authen.authen_to_system, authen.code);
                                                            var accessTokenObj  = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_PASSWORD);

                                                            var tokenResp = new TokenResponse();
                                                            tokenResp.token_type               = "Bearer";
                                                            tokenResp.access_token             = accessTokenObj.AccessToken;
                                                            tokenResp.expires_in               = _config["Jwt:Expires"];
                                                            tokenResp.refresh_token            = refreshTokenObj.RefreshToken;
                                                            tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"];

                                                            response = Ok(tokenResp);
                                                        }
                                                        else
                                                        {
                                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Username and Password is not valid for the system (" + authen.authen_to_system + ").");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid.");
                                                    }
                                                }
                                                else
                                                {
                                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ").");
                                                }
                                            }
                                            else
                                            {
                                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid.");
                                            }
                                        }
                                        else
                                        {
                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Authentication System is empty.");
                                        }
                                    }
                                    else
                                    {
                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_Password, "Unauthorized, Password is empty.");
                                    }
                                }
                                else
                                {
                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_Username, "Unauthorized, Username is empty.");
                                }
                            }
                            else
                            {
                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty.");
                            }
                        }
                        else
                        {
                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty.");
                        }
                    }
                    else if (authen.grant_type.ToLower() == GRANT_TYPE_AUTHORIZATION_CODE)
                    {
                        if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null)
                        {
                            if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null)
                            {
                                if (authen.code != string.Empty && authen.code != "null" && authen.code != null)
                                {
                                    if (authen.redirect_uri != string.Empty && authen.redirect_uri != "null" && authen.redirect_uri != null)
                                    {
                                        var appAudObj = GetAppAudiencesById(authen.client_id).Result;

                                        if (appAudObj != null)
                                        {
                                            if (appAudObj.ExpiryDate > DateTime.UtcNow)
                                            {
                                                if (appAudObj.AppSecretKey == authen.client_secret)
                                                {
                                                    var authCode = GetAuthorizationCodesById(authen.code).Result;

                                                    if (authCode != null)
                                                    {
                                                        if (authCode.ClientAppId == authen.client_id)
                                                        {
                                                            if (DateTime.Parse(authCode.ExpiryDateTime.Replace("Z", ".0000000")) > DateTime.Parse(DateTimes.ConvertToUtcDateTimeInThaiTimeZone(DateTime.UtcNow, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon).Replace("Z", ".0000000")))
                                                            {
                                                                var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_AUTHORIZATION_CODE, authen.authen_to_system, authen.code);
                                                                var accessTokenObj  = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_AUTHORIZATION_CODE);

                                                                var tokenResp = new TokenResponse();
                                                                tokenResp.token_type               = "Bearer";
                                                                tokenResp.access_token             = accessTokenObj.AccessToken;
                                                                tokenResp.expires_in               = _config["Jwt:Expires"];
                                                                tokenResp.refresh_token            = refreshTokenObj.RefreshToken;
                                                                tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"];

                                                                response = Ok(tokenResp);
                                                            }
                                                            else
                                                            {
                                                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is expired (" + authCode.ExpiryDateTime + ").");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is invalid (AuthorizationCode is not belong to Client App Id).");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is invalid.");
                                                    }
                                                }
                                                else
                                                {
                                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid.");
                                                }
                                            }
                                            else
                                            {
                                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ").");
                                            }
                                        }
                                        else
                                        {
                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid.");
                                        }
                                    }
                                    else
                                    {
                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_RedirectUri, "Unauthorized, Client App Redirect Uri is empty.");
                                    }
                                }
                                else
                                {
                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code is empty.");
                                }
                            }
                            else
                            {
                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty.");
                            }
                        }
                        else
                        {
                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty.");
                        }
                    }
                    else if (authen.grant_type.ToLower() == GRANT_TYPE_REFRESH_TOKEN)
                    {
                        if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null)
                        {
                            if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null)
                            {
                                if (authen.refresh_token != string.Empty && authen.refresh_token != "null" && authen.refresh_token != null)
                                {
                                    var appAudObj = GetAppAudiencesById(authen.client_id).Result;

                                    if (appAudObj != null)
                                    {
                                        if (appAudObj.ExpiryDate > DateTime.UtcNow)
                                        {
                                            if (appAudObj.AppSecretKey == authen.client_secret)
                                            {
                                                var rftkObj = GetRefreshTokenByToken(authen.refresh_token).Result;

                                                if (rftkObj != null)
                                                {
                                                    if (rftkObj.AppAudienceId == authen.client_id)
                                                    {
                                                        if (DateTime.Parse(rftkObj.ExpiryDateTime.Replace("Z", ".0000000")) > DateTime.Parse(DateTimes.ConvertToUtcDateTimeInThaiTimeZone(DateTime.UtcNow, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon).Replace("Z", ".0000000")) && rftkObj.Status == true)
                                                        {
                                                            var alg = GetLastestAccessTokenAlgorithmByRefreshToken(authen.refresh_token).Result;

                                                            if (rftkObj.GrantType == GRANT_TYPE_PASSWORD)
                                                            {
                                                                var userId = GetUserIdByRefreshToken(authen.refresh_token).Result;

                                                                if (userId != null)
                                                                {
                                                                    var accessTokenObj = BuildAccessToken(userId, authen.client_id, authen.refresh_token, alg, GRANT_TYPE_REFRESH_TOKEN);

                                                                    var tokenResp = new TokenResponse();
                                                                    tokenResp.token_type               = "Bearer";
                                                                    tokenResp.access_token             = accessTokenObj.AccessToken;
                                                                    tokenResp.expires_in               = _config["Jwt:Expires"];
                                                                    tokenResp.refresh_token            = authen.refresh_token;
                                                                    tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"];

                                                                    response = Ok(tokenResp);
                                                                }
                                                                else
                                                                {
                                                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is invalid (UserId is not found).");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                var accessTokenObj = BuildAccessToken(authen.username, authen.client_id, authen.refresh_token, alg, GRANT_TYPE_REFRESH_TOKEN);

                                                                var tokenResp = new TokenResponse();
                                                                tokenResp.token_type               = "Bearer";
                                                                tokenResp.access_token             = accessTokenObj.AccessToken;
                                                                tokenResp.expires_in               = _config["Jwt:Expires"];
                                                                tokenResp.refresh_token            = authen.refresh_token;
                                                                tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"];

                                                                response = Ok(tokenResp);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is expired (" + rftkObj.ExpiryDateTime + ").");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is invalid (RefreshToken is not belong to Client App Id).");
                                                    }
                                                }
                                                else
                                                {
                                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is not found.");
                                                }
                                            }
                                            else
                                            {
                                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid.");
                                            }
                                        }
                                        else
                                        {
                                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ").");
                                        }
                                    }
                                    else
                                    {
                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid.");
                                    }
                                }
                                else
                                {
                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken is empty.");
                                }
                            }
                            else
                            {
                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty.");
                            }
                        }
                        else
                        {
                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty.");
                        }
                    }
                    else
                    {
                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Grant Type (" + authen.grant_type.ToLower() + ") is invalid.");
                    }
                }
                else // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API
                {
                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model (grant_type: '" + authen.grant_type.ToLower() + "', client_id: '" + authen.client_id + "', user_id: '" + authen.username + "', refresh_token: '" + authen.refresh_token + "') is invalid.");
                }
            }
            catch (Exception ex)
            {
                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Exception occurred (" + ex.Message + " - " + ex.Source + " - " + ex.StackTrace + " - " + ex.InnerException + " - " + ex.HelpLink + ").");
            }

            return(response);
        }
        public IActionResult ApplyCheck([FromBody] dynamic dynamic)
        {
            this.UpdateSql("his");
            JObject j        = Methods.dynamicToJObject(dynamic);
            string  ItemList = string.Empty;

            Console.WriteLine("请求日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n预约检查新型冠状核酸检测的入参" + j.ToString());
            //判断参数的准确性
            if (!j.ContainsKey("CardNO"))
            {
                return(new ObjectResult(new { msg = "请求失败", data = "参数错误!没有找到参数名为CardNO的参数", code = "500" }));
            }
            if (!j.ContainsKey("Items"))
            {
                return(new ObjectResult(new { msg = "请求失败", data = "参数错误!没有找到参数名为Items的参数", code = "500" }));
            }
            else
            {
                string[] Itemslist = Methods.getStringToT <string[]>(j.GetValue("Items", StringComparison.OrdinalIgnoreCase).ToString());
                for (int i = 0; i < Itemslist.Length; i++)
                {
                    if (i == Itemslist.Length - 1)
                    {
                        ItemList += Itemslist[i];
                    }
                    else
                    {
                        ItemList += Itemslist[i] + "|";
                    }
                }
            }
            if (!j.ContainsKey("peopleType"))
            {
                return(new ObjectResult(new { msg = "请求失败", data = "参数错误!没有找到参数名为peopleType的参数", code = "500" }));
            }
            if (!j.ContainsKey("date"))
            {
                return(new ObjectResult(new { msg = "请求失败", data = "参数错误!没有找到参数名为date的参数", code = "500" }));
            }
            List <OracleParameter> oralist = new List <OracleParameter>();

            //入参
            oralist.Add(Methods.GetInput("CARD_NO", j.GetValue("CardNo", StringComparison.OrdinalIgnoreCase).ToString()));
            oralist.Add(Methods.GetInput("Item_Code", ItemList));
            oralist.Add(Methods.GetInput("people_type", j.GetValue("peopleType", StringComparison.OrdinalIgnoreCase).ToString()));
            try
            {
                oralist.Add(Methods.GetInput("PRE_DATE", OracleDbType.Varchar2, Convert.ToDateTime(j.GetValue("date", StringComparison.OrdinalIgnoreCase).ToString()).ToString("yyyy-MM-dd HH:mm:ss")));
            }
            catch (Exception ex)
            {
                return(new ObjectResult(new { msg = "请求失败", data = "时间格式错误" + ex.Message, code = "500" }));
            }
            //出参
            oralist.Add(Methods.GetOutput("ReturnSet", OracleDbType.RefCursor, 1024));
            oralist.Add(Methods.GetOutput("ErrStr", OracleDbType.Varchar2, 100));
            oralist.Add(Methods.GetOutput("ReturnCode", OracleDbType.Int32, 20));
            //执行
            var          ds  = Methods.SqlQuery(db, "PKG_ZHYY_MZ.PRC_CHECKITEM_APPLY", oralist.ToArray());
            ObjectResult obj = Methods.GetResult(oralist, ds, "ErrStr");

            Console.WriteLine("返回数据:\n" + JsonConvert.SerializeObject(obj.Value));
            return(obj);
        }
        public IActionResult GetByFilter([FromQuery] string filter, string format)
        {
            string entityAsJson = "";

            try
            {
                _logger.LogInformation("CPAPI: GetByDiagnosticEventFilter");

                // Deserialize the ontology filter
                DiagnoticEventFilter oFilter = new DiagnoticEventFilter();
                if (filter != null && filter.Length > 0)
                {
                    _logger.LogDebug("Deserializing ontology filter of length: " + filter.Length);
                    oFilter = JsonConvert.DeserializeObject <DiagnoticEventFilter>(filter);
                }

                // Check if a format has been requested
                string dataFormat = string.Empty;
                if (format != null && format != "")
                {
                    dataFormat = format.ToLower();
                }

                // Create the filters
                List <DataFactory.Filter> filters = new List <DataFactory.Filter>();
                foreach (string s in oFilter.eventtypes)
                {
                    DataFactory.Filter etFilter = new DataFactory.Filter("Event", s, "eq");
                }

                // Call the data factory
                DataFactory.DataConfig   providerConfig = Utils.GetDataConfig();
                List <POCO.CPDiagnostic> diags          = DataFactory.Diagnostics.GetDiagnosticEntries(providerConfig, filters);

                // Check the data format request
                switch (dataFormat)
                {
                case "chartline":
                {
                    // Pre-sort the data by event type and date of event (RowKey)
                    //diags.Sort((x, y) => string.Compare(x.RowKey, y.RowKey));
                    diags = diags.OrderBy(x => x.Event).ThenBy(x => x.RowKey).ToList();

                    ChartLineData chartData = new ChartLineData();

                    // Pre-populate all the dates for the chart
                    foreach (POCO.CPDiagnostic diagitem in diags)
                    {
                        string itemDate = diagitem.RowKey.Substring(0, 10);

                        // Check if the label exists
                        if (!chartData.labels.Contains(itemDate))
                        {
                            chartData.labels.Add(itemDate);
                        }
                    }

                    // Sort the label data in the chart data object
                    chartData.labels.Sort((x, y) => string.Compare(x, y));

                    // Line chart colors
                    string[] chartColors = new string[] { "#000099", "#006666", "#0099cc", "#660099", "#666633", "#669999"
                                                          , "#66cc66", "#990099", "#996666", "#99cc66", "#cc00ff", "#cc9933", "#ccff99", "#ccff99", "#ff99ff"
                                                          , "#ffcc33", "#ff0000", "#ffcccc", "#cc99ff", "#99cc00" };

                    // Transform the event data
                    ChartLineDataset currentDataset = null;
                    string           currentEvent   = string.Empty;
                    string           currentDate    = string.Empty;
                    int    countDataset             = 0;
                    int    countDataInDay           = 0;
                    double sumAverages = 0;
                    Dictionary <string, double> eventAverageForDay = new Dictionary <string, double>();

                    foreach (POCO.CPDiagnostic diagitem in diags)
                    {
                        string itemDate = diagitem.RowKey.Substring(0, 10);

                        // Check if the event has been set
                        if (currentEvent == string.Empty)
                        {
                            // First event in list - init vars
                            currentDataset = new ChartLineDataset();
                            currentDataset.backgroundColor = chartColors[countDataset % 20];
                            currentDataset.label           = diagitem.Event;
                            currentEvent = diagitem.Event;
                            currentDate  = itemDate;
                            if (diagitem.TotalMilliseconds != 0)
                            {
                                sumAverages    = diagitem.NumBytes / diagitem.TotalMilliseconds;
                                countDataInDay = 1;
                            }
                            else
                            {
                                sumAverages    = 0;
                                countDataInDay = 0;
                            }
                            countDataset++;
                        }
                        else
                        {
                            // Check if the event has changed from the current event
                            if (currentEvent != diagitem.Event)
                            {
                                //// New event - finalise previous event and add data
                                if (countDataInDay != 0)
                                {
                                    eventAverageForDay.Add(currentDate, sumAverages / countDataInDay);
                                }

                                // Populate the dataset by matching the labels (X-axis) to our averages
                                foreach (string s in chartData.labels)
                                {
                                    if (eventAverageForDay.ContainsKey(s))
                                    {
                                        currentDataset.data.Add(eventAverageForDay[s]);
                                    }
                                    else
                                    {
                                        currentDataset.data.Add(0);
                                    }
                                }

                                // Add the dataset to our chart data
                                chartData.datasets.Add(currentDataset);

                                // Now set the new event and date
                                // and reset the eventAverage data
                                eventAverageForDay             = new Dictionary <string, double>();
                                currentDataset                 = new ChartLineDataset();
                                currentDataset.backgroundColor = chartColors[countDataset % 20];
                                currentDataset.label           = diagitem.Event;
                                currentEvent = diagitem.Event;
                                currentDate  = itemDate;
                                if (diagitem.TotalMilliseconds != 0)
                                {
                                    sumAverages    = diagitem.NumBytes / diagitem.TotalMilliseconds;
                                    countDataInDay = 1;
                                }
                                else
                                {
                                    sumAverages    = 0;
                                    countDataInDay = 0;
                                }
                                countDataset++;
                            }
                            else
                            {
                                // Check if the date has changed
                                if (currentDate != itemDate)
                                {
                                    // New date - finalise previous date data
                                    if (countDataInDay != 0)
                                    {
                                        eventAverageForDay.Add(currentDate, sumAverages / countDataInDay);
                                    }

                                    // Set the new date
                                    currentDate = itemDate;

                                    // Reset date and count vars
                                    if (diagitem.TotalMilliseconds != 0)
                                    {
                                        sumAverages    = diagitem.NumBytes / diagitem.TotalMilliseconds;
                                        countDataInDay = 1;
                                    }
                                    else
                                    {
                                        sumAverages    = 0;
                                        countDataInDay = 0;
                                    }
                                }
                                else
                                {
                                    // Same date - add to previous data
                                    if (diagitem.TotalMilliseconds != 0)
                                    {
                                        sumAverages += diagitem.NumBytes / diagitem.TotalMilliseconds;
                                        countDataInDay++;
                                    }
                                }
                            }
                        }
                    }

                    // end of loop - check if there is a dataset to add
                    if (currentDataset != null)
                    {
                        // TODO final calculations
                        // HACK
                        //currentDataset.data.Add(1 * countDataset);
                        //currentDataset.data.Add(2 * countDataset);
                        //currentDataset.data.Add(3 * countDataset);
                        //currentDataset.data.Add(4 * countDataset);

                        // Add the dataset to our chart data
                        chartData.datasets.Add(currentDataset);
                    }

                    // Serialize the chart data
                    entityAsJson = JsonConvert.SerializeObject(chartData, Formatting.Indented);

                    break;
                }

                default:
                {
                    entityAsJson = JsonConvert.SerializeObject(diags, Formatting.Indented);
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                string exceptionMsg = "Diagnostics GET exception: " + ex.Message;
                //log.Info("Exception occurred extracting text from uploaded file \r\nError: " + ex.Message);
                if (ex.InnerException != null)
                {
                    exceptionMsg = exceptionMsg + "[" + ex.InnerException.Message + "]";
                }

                _logger.LogError(exceptionMsg);
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
            }

            ObjectResult result = new ObjectResult(entityAsJson);

            return(result);
        }
Example #11
0
        public async Task ObjectResult_WithSingleContentType_TheContentTypeIsIgnoredIfTheTypeIsString()
        {
            // Arrange
            var contentType = "application/json;charset=utf-8";
            var expectedContentType = "text/plain; charset=utf-8";

            // string value.
            var input = "1234";
            var httpResponse = GetMockHttpResponse();
            var actionContext = CreateMockActionContext(httpResponse.Object);

            // Set the content type property explicitly to a single value.
            var result = new ObjectResult(input);
            result.ContentTypes = new List<MediaTypeHeaderValue>();
            result.ContentTypes.Add(MediaTypeHeaderValue.Parse(contentType));

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
Example #12
0
        public void SelectFormatter_WithNoMatchingAcceptHeadersAndRequestContentType_PicksFormatterBasedOnObjectType
            (string acceptHeader)
        {
            // For no accept headers,
            // can write is called twice once for the request Content-Type and once for the type match pass.
            // For each additional accept header, it is called once.
            // Arrange
            var acceptHeaderCollection = string.IsNullOrEmpty(acceptHeader) ?
                null : MediaTypeHeaderValue.ParseList(new[] { acceptHeader }).ToArray();
            var stream = new MemoryStream();
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object,
                                                        requestAcceptHeader: acceptHeader,
                                                        requestContentType: "application/xml");
            var input = "testInput";
            var result = new ObjectResult(input);
            var mockCountingFormatter = new Mock<IOutputFormatter>();

            var context = new OutputFormatterContext()
            {
                HttpContext = actionContext.HttpContext,
                Object = input,
                DeclaredType = typeof(string)
            };
            var mockCountingSupportedContentType = MediaTypeHeaderValue.Parse("application/text");
            mockCountingFormatter.Setup(o => o.CanWriteResult(context,
                                           It.Is<MediaTypeHeaderValue>(mth => mth == null)))
                                .Returns(true);
            mockCountingFormatter.Setup(o => o.CanWriteResult(context, mockCountingSupportedContentType))
                                 .Returns(true);

            // Set more than one formatters. The test output formatter throws on write.
            result.Formatters = new List<IOutputFormatter>
                                    {
                                        new CannotWriteFormatter(),
                                        mockCountingFormatter.Object,
                                    };

            // Act
            var formatter = result.SelectFormatter(context, result.Formatters);

            // Assert
            Assert.Equal(mockCountingFormatter.Object, formatter);
            mockCountingFormatter.Verify(v => v.CanWriteResult(context, null), Times.Once());
            
            // CanWriteResult is invoked for the following cases:
            // 1. For each accept header present
            // 2. Request Content-Type
            // 3. Type based match
            var callCount = (acceptHeaderCollection == null ? 0 : acceptHeaderCollection.Count()) + 2;
            mockCountingFormatter.Verify(v => v.CanWriteResult(context,
                                              It.IsNotIn<MediaTypeHeaderValue>(mockCountingSupportedContentType)),
                                              Times.Exactly(callCount));
        }
Example #13
0
 /// <summary>
 /// Function: ToList
 /// Converts ObjectResult to Generic List
 /// </summary>
 /// <typeparam name="T1"></typeparam>
 /// <typeparam name="T2"></typeparam>
 /// <param name="Source"></param>
 /// <param name="Destination"></param>
 public static void ToList <T1, T2>(ObjectResult <T1> Source, List <T2> Destination) where T2 : new()
 {
     Destination.AddRange(Source.Select(CreateMapping <T1, T2>()));
 }
Example #14
0
        public IActionResult GetByRecordAssociationFilter([FromQuery] string filter)
        {
            string entityAsJson = "";
            List <POCO.RecordAssociationSubjectObject> subjectObjectEntities = new List <POCO.RecordAssociationSubjectObject>();

            try
            {
                _logger.LogInformation("CPAPI: Get By Record Association Filter");

                // Deserialize the ontology filter
                Controllers.RecordAssociationFilter oFilter = new Controllers.RecordAssociationFilter();
                if (filter != null && filter.Length > 0)
                {
                    _logger.LogDebug("Deserializing Record Association filter of length: " + filter.Length);
                    oFilter = JsonConvert.DeserializeObject <Controllers.RecordAssociationFilter>(filter);
                }

                // Check if a filter has been supplied
                if (oFilter.recordassociations.Count == 0)
                {
                    // Nothing to filter by - return invalid filter
                    return(StatusCode((int)System.Net.HttpStatusCode.NoContent));
                }

                // Create the filters for the datafactory
                List <DataFactory.Filter> filters = new List <DataFactory.Filter>();
                if (oFilter.recordassociations.Count > 0)
                {
                    string combinedFilter = "";
                    foreach (RecordAssociation rif in oFilter.recordassociations)
                    {
                        string cleanFilterPKey = Utils.CleanTableKey(rif.recorduri);    // Utils.CleanTableKey(rif.recorduri);
                        string cleanFilterRKey = Utils.CleanTableKey(rif.recordassociationuri);

                        if (cleanFilterPKey != "")
                        {
                            DataFactory.Filter pkfilt = new DataFactory.Filter("PartitionKey", cleanFilterPKey, "eq");
                            filters.Add(pkfilt);
                        }
                        // Check if an item key has been provided
                        if (cleanFilterRKey != "")
                        {
                            DataFactory.Filter rkfilt = new DataFactory.Filter("RowKey", cleanFilterRKey, "eq");
                            filters.Add(rkfilt);
                        }
                    }
                }
                else
                {
                    _logger.LogInformation("RecordKeyPhraseFilter query BLANK");
                }

                DataFactory.DataConfig dataCfg = Utils.GetDataConfig();

                List <POCO.RecordAssociationSubjectObject> subjectobject = DataFactory.Record.GetRecordAssociationSubjectObject(dataCfg, filters);

                //CloudTable table = Utils.GetCloudTableNoCreate("stlprecordassociationsubjectobject", _logger);

                //// Create a default query
                //TableQuery<SubjectObjectEntity> query = new TableQuery<SubjectObjectEntity>();
                //string combinedFilter = "";
                //if (oFilter.recordassociations.Count > 0)
                //{
                //    foreach (string rafilter in oFilter.recordassociations)
                //    {
                //        string cleanFilterPKey = Utils.CleanTableKey(rafilter);

                //        string pkquery = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, cleanFilterPKey);

                //        if (combinedFilter != "")
                //        {
                //            combinedFilter = TableQuery.CombineFilters(combinedFilter, TableOperators.Or, pkquery);
                //        }
                //        else
                //        {
                //            combinedFilter = pkquery;
                //        }
                //    }
                //}

                //// Create final combined query
                //query = new TableQuery<SubjectObjectEntity>().Where(combinedFilter);

                //List<SubjectObjectEntity> SubjectObjectEntityEntities = new List<SubjectObjectEntity>();
                //TableContinuationToken token = null;

                //var runningQuery = new TableQuery<SubjectObjectEntity>()
                //{
                //    FilterString = query.FilterString,
                //    SelectColumns = query.SelectColumns
                //};

                //do
                //{
                //    runningQuery.TakeCount = query.TakeCount - SubjectObjectEntityEntities.Count;

                //    Task<TableQuerySegment<SubjectObjectEntity>> tSeg = table.ExecuteQuerySegmentedAsync<SubjectObjectEntity>(runningQuery, token);
                //    tSeg.Wait();
                //    token = tSeg.Result.ContinuationToken;
                //    SubjectObjectEntityEntities.AddRange(tSeg.Result);

                //} while (token != null && (query.TakeCount == null || SubjectObjectEntityEntities.Count < query.TakeCount.Value) && SubjectObjectEntityEntities.Count < 1000);    //!ct.IsCancellationRequested &&

                // Return only distinct entrys
                List <string> SubjectObjectEntityKeys = new List <string>();
                foreach (POCO.RecordAssociationSubjectObject ne in subjectobject)
                {
                    if (!SubjectObjectEntityKeys.Contains(ne.RowKey))
                    {
                        // Add the entity to the output
                        // and the key
                        subjectObjectEntities.Add(ne);
                        SubjectObjectEntityKeys.Add(ne.RowKey);
                    }
                }
                subjectObjectEntities.Sort((x, y) => String.Compare(x.RowKey, y.RowKey));

                // Serialize
                entityAsJson = JsonConvert.SerializeObject(subjectObjectEntities, Formatting.Indented);
            }
            catch (Exception ex)
            {
                string exceptionMsg = "Subject Object GET BY RECORD FILTER exception: " + ex.Message;
                //log.Info("Exception occurred extracting text from uploaded file \r\nError: " + ex.Message);
                if (ex.InnerException != null)
                {
                    exceptionMsg = exceptionMsg + "[" + ex.InnerException.Message + "]";
                }

                _logger.LogError(exceptionMsg);
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
            }

            ObjectResult result = new ObjectResult(entityAsJson);

            return(result);
        }
Example #15
0
        private async Task InvokeActionFilterAsync()
        {
            Debug.Assert(_actionExecutingContext != null);

            var item = _cursor.GetNextFilter <IActionFilter, IAsyncActionFilter>();

            try
            {
                if (item.FilterAsync != null)
                {
                    _diagnosticSource.BeforeOnActionExecution(_actionExecutingContext, item.FilterAsync);

                    await item.FilterAsync.OnActionExecutionAsync(_actionExecutingContext, InvokeActionFilterAwaitedAsync);

                    if (_actionExecutedContext == null)
                    {
                        // If we get here then the filter didn't call 'next' indicating a short circuit
                        _logger.ActionFilterShortCircuited(item.FilterAsync);

                        _actionExecutedContext = new ActionExecutedContext(
                            _actionExecutingContext,
                            _filters,
                            _controller)
                        {
                            Canceled = true,
                            Result   = _actionExecutingContext.Result,
                        };
                    }

                    _diagnosticSource.AfterOnActionExecution(_actionExecutedContext, item.FilterAsync);
                }
                else if (item.Filter != null)
                {
                    _diagnosticSource.BeforeOnActionExecuting(_actionExecutingContext, item.Filter);

                    item.Filter.OnActionExecuting(_actionExecutingContext);

                    _diagnosticSource.AfterOnActionExecuting(_actionExecutingContext, item.Filter);

                    if (_actionExecutingContext.Result != null)
                    {
                        // Short-circuited by setting a result.
                        _logger.ActionFilterShortCircuited(item.Filter);

                        _actionExecutedContext = new ActionExecutedContext(
                            _actionExecutingContext,
                            _filters,
                            _controller)
                        {
                            Canceled = true,
                            Result   = _actionExecutingContext.Result,
                        };
                    }
                    else
                    {
                        await InvokeActionFilterAsync();

                        Debug.Assert(_actionExecutedContext != null);

                        _diagnosticSource.BeforeOnActionExecuted(_actionExecutedContext, item.Filter);

                        item.Filter.OnActionExecuted(_actionExecutedContext);

                        _diagnosticSource.BeforeOnActionExecuted(_actionExecutedContext, item.Filter);
                    }
                }
                else
                {
                    // All action filters have run, execute the action method.
                    IActionResult result = null;

                    try
                    {
                        _diagnosticSource.BeforeActionMethod(
                            _controllerContext,
                            _actionExecutingContext.ActionArguments,
                            _actionExecutingContext.Controller);

                        var actionMethodInfo = _controllerContext.ActionDescriptor.MethodInfo;

                        var arguments = ControllerActionExecutor.PrepareArguments(
                            _actionExecutingContext.ActionArguments,
                            _executor);

                        _logger.ActionMethodExecuting(_actionExecutingContext, arguments);

                        var returnType = _executor.MethodReturnType;

                        if (returnType == typeof(void))
                        {
                            _executor.Execute(_controller, arguments);
                            result = new EmptyResult();
                        }
                        else if (returnType == typeof(Task))
                        {
                            await(Task) _executor.Execute(_controller, arguments);
                            result = new EmptyResult();
                        }
                        else if (_executor.TaskGenericType == typeof(IActionResult))
                        {
                            result = await(Task <IActionResult>) _executor.Execute(_controller, arguments);
                            if (result == null)
                            {
                                throw new InvalidOperationException(
                                          Resources.FormatActionResult_ActionReturnValueCannotBeNull(typeof(IActionResult)));
                            }
                        }
                        else if (_executor.IsTypeAssignableFromIActionResult)
                        {
                            if (_executor.IsMethodAsync)
                            {
                                result = (IActionResult)await _executor.ExecuteAsync(_controller, arguments);
                            }
                            else
                            {
                                result = (IActionResult)_executor.Execute(_controller, arguments);
                            }

                            if (result == null)
                            {
                                throw new InvalidOperationException(
                                          Resources.FormatActionResult_ActionReturnValueCannotBeNull(_executor.TaskGenericType ?? returnType));
                            }
                        }
                        else if (!_executor.IsMethodAsync)
                        {
                            var resultAsObject = _executor.Execute(_controller, arguments);
                            result = new ObjectResult(resultAsObject)
                            {
                                DeclaredType = returnType,
                            };
                        }
                        else if (_executor.TaskGenericType != null)
                        {
                            var resultAsObject = await _executor.ExecuteAsync(_controller, arguments);

                            result = new ObjectResult(resultAsObject)
                            {
                                DeclaredType = _executor.TaskGenericType,
                            };
                        }
                        else
                        {
                            // This will be the case for types which have derived from Task and Task<T> or non Task types.
                            throw new InvalidOperationException(Resources.FormatActionExecutor_UnexpectedTaskInstance(
                                                                    _executor.MethodInfo.Name,
                                                                    _executor.MethodInfo.DeclaringType));
                        }

                        _logger.ActionMethodExecuted(_actionExecutingContext, result);
                    }
                    finally
                    {
                        _diagnosticSource.AfterActionMethod(
                            _controllerContext,
                            _actionExecutingContext.ActionArguments,
                            _actionExecutingContext.Controller,
                            result);
                    }

                    _actionExecutedContext = new ActionExecutedContext(
                        _actionExecutingContext,
                        _filters,
                        _controller)
                    {
                        Result = result
                    };
                }
            }
            catch (Exception exception)
            {
                // Exceptions thrown by the action method OR filters bubble back up through ActionExcecutedContext.
                _actionExecutedContext = new ActionExecutedContext(
                    _actionExecutingContext,
                    _filters,
                    _controller)
                {
                    ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception)
                };
            }

            Debug.Assert(_actionExecutedContext != null);
        }
        public IActionResult SearchResults([FromBody] SearchSelectionsBindingModel searchSelections)
        {
            List <TreeNodes>  selectedSkills  = searchSelections.UniqueNodeArray;
            List <FocusNodes> selectedFocuses = searchSelections.UniqueFocusNodeArray;

            if (ModelState.IsValid)
            {
                ////Initialize the companies in the tables
                var allCompanies = GetAllCompanies();
                var allCompsInCompanySkillsTable  = new List <CompanySkills>();
                var allCompsInCompanyDetailsTable = new List <CompanyDetails>();
                var allCompsInCompanyFocusTable   = new List <CompanyFocus>();
                foreach (var company in allCompanies)
                {
                    allCompsInCompanySkillsTable.AddRange(company.CompanySkills);
                    allCompsInCompanyDetailsTable.AddRange(company.CompanyDetails);
                    allCompsInCompanyFocusTable.AddRange(company.CompanyFocuses);
                }

                var tempCompList   = new List <Companies>();
                var tempFocusMatch = new List <Companies>();

                var focuses = new List <int>();
                var skills  = new List <int>();
                var details = new List <int>();

                foreach (var focusName in _context.Focus)
                {
                    foreach (var selectedFocusName in selectedFocuses)
                    {
                        if (selectedFocusName.Name == focusName.FocusType)
                        {
                            focuses.Add(focusName.FocusId);
                        }
                    }
                }
                foreach (var skillName in _context.SkillSet)
                {
                    foreach (var selectedSkillName in selectedSkills)
                    {
                        if (selectedSkillName.Name == skillName.SkillName)
                        {
                            skills.Add(skillName.SkillId);
                        }
                    }
                }
                foreach (var detailName in _context.SkillDetail)
                {
                    foreach (var selectedDetailName in selectedSkills)
                    {
                        if (selectedDetailName.Name == detailName.DetailName)
                        {
                            details.Add(detailName.SkillDetailId);
                        }
                    }
                }

                foreach (var company in allCompanies)
                {
                    foreach (var focus in _context.CompanyFocus.Where(c => c.CompanyId == company.CompanyId))
                    {
                        foreach (var selectedFocus in focuses.Where(f => f == focus.FocusId))
                        {
                            tempFocusMatch.Add(company);
                        }
                    }
                }

                List <Companies> uniqueFocusMatch = tempFocusMatch.Distinct().ToList();

                foreach (var comp in uniqueFocusMatch)
                {
                    var foundCompSkills = _context.CompanySkills.Where(c => c.CompanyId == comp.CompanyId).ToList();

                    foreach (var compSkill in foundCompSkills)
                    {
                        foreach (var skill in skills.Where(s => s == compSkill.SkillId))
                        {
                            if (compSkill.Company.SkillList == null)
                            {
                                compSkill.Company.SkillList = new List <SkillSet>();
                            }
                            compSkill.Company.SkillList.Add(compSkill.SkillSet);
                            tempCompList.Add(compSkill.Company);
                        }
                    }
                }

                foreach (var comp in uniqueFocusMatch)
                {
                    var foundCompDetails = _context.CompanyDetails.Where(c => c.CompanyId == comp.CompanyId).ToList();


                    foreach (var compDetail in foundCompDetails)
                    {
                        foreach (var detail in details.Where(s => s == compDetail.SkillDetailId))
                        {
                            if (compDetail.Company.DetailList == null)
                            {
                                compDetail.Company.DetailList = new List <SkillDetail>();
                            }
                            compDetail.Company.DetailList.Add(compDetail.SkillDetail);
                            tempCompList.Add(compDetail.Company);
                        }
                    }
                }

                var sortedList = from company in tempCompList
                                 group company by company into match
                                 orderby match.Count() descending
                                 select match.Key;


                List <Companies> matches = sortedList.Distinct().ToList();

                var result = new ObjectResult(matches);
                return(result);
            }
            else
            {
                return(NotFound());
            }
        }
        public IActionResult Post([FromBody] Welcome welcome)
        {
            var           reports    = welcome.FormattedJson;
            var           project    = welcome.Project;
            IActionResult _result    = new ObjectResult(false);
            GenericResult _addResult = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }



                //ADD
                var version = _OverviewEcommerceSumService.GetVersionFinal(project["PROJECT_ID"]);

                _OverviewEcommerceSumService.RemoveVersionOld(project["PROJECT_ID"]);


                var rows = reports.Reports[0].Data.Rows;
                if (rows == null)
                {
                    _addResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Không có dữ liệu trong 30 ngày gần nhất"
                    };
                    _result = new ObjectResult(_addResult);
                    return(_result);
                }
                for (int i = 0; i < rows.Length; i++)
                {
                    //  var productName = rows[i].Dimensions[0];
                    var values = rows[i].Metrics[0].Values;

                    //    decimal moeny = Decimal.Parse(values[0], System.Globalization.NumberStyles.Any);
                    //  var moeny= Double.Parse(values[0], System.Globalization.NumberStyles.Float);

                    //string[] moeny = values[0].ToString().Split('E');
                    //var x = Double.Parse(moeny[0])*(10^moeny)
                    OverviewEcommerce newOverviewEcommerceSum = new OverviewEcommerce
                    {
                        OVERVIEW_ECOMMERCE_ID = 0,
                        SESSIONS           = values[0],
                        PAGEVIEWS          = values[1],
                        TIMEONPAGE         = values[2],
                        TRANSACTIONREVENUE = values[3],
                        PRODUCTADDSTOCART  = values[4],
                        PRODUCTCHECKOUTS   = values[5],
                        PRODUCTDETAILVIEWS = values[6],
                        USERS      = values[7],
                        NEWS_USERS = values[8],
                        //ITEM_REVENUE = values[0],
                        //PRODUCT_DETAIL_VIEWS = values[1],
                        //QUANTITY_CHECKED_OUT = values[2],
                        //QUANTITY_ADDED_TO_CART = values[3],

                        CREATE_DT     = DateTime.Now,
                        RECORD_STATUS = "1",
                        VERSION_INT   = version + 1,
                        VERSION       = (version + 1).ToString(),

                        PROJECT_ID = project["PROJECT_ID"],
                        DOMAIN     = project["DOMAIN"]
                    };
                    _OverviewEcommerceSumService.Add(newOverviewEcommerceSum);
                    _OverviewEcommerceSumService.Save();
                }

                //OverviewEcommerceSum _newOverviewEcommerce = PropertyCopy.Copy<OverviewEcommerceSum, DomainViewModel>(overviewEcommerce);


                //_newOverviewEcommerce.CREATE_DT = DateTime.Now;
                //_newOverviewEcommerce.PROJECT_ID = 1;



                _addResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Add success."
                };
            }
            catch (Exception ex)
            {
                _addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_addResult);
            return(_result);
        }
        public override void OnException(ExceptionContext context)
        {
            bool          isDevelopment = _hostingEnv.IsDevelopment();
            var           ex            = context.Exception;
            string        stackTrace    = (isDevelopment) ? context.Exception.StackTrace : string.Empty;
            string        message       = ex.Message;
            string        error         = string.Empty;
            IActionResult actionResult;

            switch (ex)
            {
            case DbUpdateConcurrencyException ce:
                // Returns a 400
                error        = "Concurrency Issue";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksUniqueIndexException une:
                // Return 400
                error        = "Duplicate value detected!";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidEntityIdException une:
                // Return 404
                error        = "Can't find entity; invalid primary key value given.";
                actionResult = new NotFoundObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidContactTypeException une:
                // Return 400
                error        = "Invalid ContactTypeID.";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidAddressTypeException une:
                // Return 400
                error        = "Invalid AddressTypeID.";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksNullEntityObjectException une:
                // Return 404
                error        = "Can't find entity; invalid primary key value given!";
                actionResult = new NotFoundObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidStateProvinceIdException une:
                // Return 400
                error        = "Invalid state or province code.";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidPhoneTypeException une:
                // Return 400
                error        = "Invalid phone type ID.";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksInvalidDeleteOperationException une:
                // Return 400
                error        = "Invalid delete operation, would result in orphaned child records.";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            case AdventureWorksException awe:
                // Return 400
                error        = "AdventureWorksException";
                actionResult = new BadRequestObjectResult(new { error = error, message = message, StackTrace = stackTrace });
                _logger.LogError($"{error} : {message}");
                break;

            default:
                error        = "General Error";
                actionResult = new ObjectResult(new { error = error, message = message, StackTrace = stackTrace })
                {
                    StatusCode = 500
                };
                _logger.LogError($"{error} : {message}");
                break;
            }

            context.Result = actionResult;
        }
        public IActionResult GetByFilter([FromHeader] string spfilefilter)
        {
            string entityAsJson = "";

            try
            {
                _logger.LogInformation("CPAPI: Get");

                // Validate the filter
                if (spfilefilter == null || spfilefilter.Length == 0)
                {
                    _logger.LogDebug("Filter not provided, returning blank");
                    return(new ObjectResult("[]"));
                }

                // Deserialize the filter
                SPFileFilter oFilter = new SPFileFilter();
                if (spfilefilter != null && spfilefilter.Length > 0)
                {
                    _logger.LogDebug("Deserializing filter of length: " + spfilefilter.Length);
                    oFilter = JsonConvert.DeserializeObject <SPFileFilter>(spfilefilter);
                }

                string storageAccountConnectionString = Utils.GetSecretOrEnvVar(ConfigurationProperties.AzureStorageAccountConnectionString, Configuration, _logger).Trim();
                // validate tika base address
                if (storageAccountConnectionString == "")
                {
                    _logger.LogWarning("Azure storage account connection string not set");
                    return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
                }
                else
                {
                    _logger.LogDebug("Azure storage account connection string loaded");
                }

                // Process the records
                CloudStorageAccount account = CloudStorageAccount.Parse(storageAccountConnectionString);

                // Create the table client.
                //log.Info("Creating cloud table client");
                CloudTableClient tableClient = account.CreateCloudTableClient();

                // Create the table if it doesn't exist.
                //log.Info("Getting table reference");
                CloudTable table   = tableClient.GetTableReference("stlpo365spfiles");
                Task       tCreate = table.CreateIfNotExistsAsync();
                tCreate.Wait();

                // Create a default query
                TableQuery <SPFileProcessingStatusEntity> query = new TableQuery <SPFileProcessingStatusEntity>();
                if (oFilter.spfiles.Count > 0)
                {
                    string combinedFilter = "";
                    foreach (SPFileFilterEntry filterentry in oFilter.spfiles)
                    {
                        string cleanFilterPKey = Utils.CleanTableKey(filterentry.spfileabsoluteuri);
                        string pkquery         = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, cleanFilterPKey);
                        combinedFilter = pkquery;
                    }
                    // Create final combined query
                    query = new TableQuery <SPFileProcessingStatusEntity>().Where(combinedFilter);
                }
                List <SPFileProcessingStatusEntity> spfileEntities = new List <SPFileProcessingStatusEntity>();
                TableContinuationToken token = null;

                var runningQuery = new TableQuery <SPFileProcessingStatusEntity>()
                {
                    FilterString  = query.FilterString,
                    SelectColumns = query.SelectColumns
                };

                do
                {
                    runningQuery.TakeCount = query.TakeCount - spfileEntities.Count;

                    Task <TableQuerySegment <SPFileProcessingStatusEntity> > tSeg = table.ExecuteQuerySegmentedAsync <SPFileProcessingStatusEntity>(runningQuery, token);
                    tSeg.Wait();
                    token = tSeg.Result.ContinuationToken;
                    spfileEntities.AddRange(tSeg.Result);
                } while (token != null && (query.TakeCount == null || spfileEntities.Count < query.TakeCount.Value));    //!ct.IsCancellationRequested &&


                //no sorting
                //spfileEntities.Sort((x, y) => String.Compare(x.Label, y.Label));

                entityAsJson = JsonConvert.SerializeObject(spfileEntities, Formatting.Indented);
            }
            catch (Exception ex)
            {
                string exceptionMsg = "SPFile batch status GET exception: " + ex.Message;
                //log.Info("Exception occurred extracting text from uploaded file \r\nError: " + ex.Message);
                if (ex.InnerException != null)
                {
                    exceptionMsg = exceptionMsg + "[" + ex.InnerException.Message + "]";
                }

                _logger.LogError(exceptionMsg);
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError));
            }

            ObjectResult result = new ObjectResult(entityAsJson);

            return(result);
        }
Example #20
0
        public IActionResult Get()
        {
            var characterList = new ObjectResult(_service.GetListOfCharacterNamesAndIds());

            return(new ObjectResult(characterList));
        }
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordViewModel model)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                ApplicationUser appUser = null;
                if (!String.IsNullOrEmpty(model.Id))
                {
                    appUser = await _userManager.FindByIdAsync(model.Id);
                }
                else if (!String.IsNullOrEmpty(model.UserName))
                {
                    appUser = await _userManager.FindByNameAsync(model.UserName);
                }
                //else
                //{
                //    appUser = await _userManager.FindByIdAsync(model.Id);
                //}

                if (appUser != null)
                {
                    var result =
                        await
                        _userManager.ChangePasswordAsync(appUser, model.OldPassword, model.NewPassword);

                    if (result.Succeeded)
                    {
                        _authenticationResult = new GenericResult()
                        {
                            Succeeded = true,
                            Message   = "Đổi mật khẩu thành công",
                        };
                    }

                    else
                    {
                        _authenticationResult = new GenericResult()
                        {
                            Succeeded = false,
                            Message   = "Đổi mật khẩu thất bại",
                        };
                    }
                }
                else
                {
                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Không tìm thấy ID",
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
Example #22
0
        public async Task ObjectResult_WithSingleContentType_TheGivenContentTypeIsSelected()
        {
            // Arrange
            var expectedContentType = "application/json; charset=utf-8";

            // non string value.
            var input = 123;
            var httpResponse = new DefaultHttpContext().Response;
            httpResponse.Body = new MemoryStream();
            var actionContext = CreateMockActionContext(httpResponse);

            // Set the content type property explicitly to a single value.
            var result = new ObjectResult(input);
            result.ContentTypes = new List<MediaTypeHeaderValue>();
            result.ContentTypes.Add(MediaTypeHeaderValue.Parse(expectedContentType));

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expectedContentType, httpResponse.ContentType);
        }
        public async Task <IActionResult> Login([FromBody] LoginViewModel model)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                //   var user23 = _userManager.FindByNameAsync(model.Username).Result.Claims;

                var user = await _userManager.FindByNameAsync(model.Username);

                if (user == null)
                {
                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = false,
                        Message      = "Tài khoản không tồn tại",
                        access_token = null,
                        expires_in   = 0
                    };
                    _result = new ObjectResult(_authenticationResult);
                    return(_result);
                }
                if (user.LockoutEnabled == false)
                {
                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = false,
                        Message      = "Tài khoản của bạn đã bị khóa",
                        access_token = null,
                        expires_in   = 0
                    };
                    _result = new ObjectResult(_authenticationResult);
                    return(_result);
                }
                var result = await _userManager.CheckPasswordAsync(user, model.Password);

                if (result)
                {
                    //var adminRole = await _roleManager.FindByNameAsync("Admin");
                    //if (adminRole == null)
                    //{
                    //    adminRole = new IdentityRole("Admin");
                    //    await _roleManager.CreateAsync(adminRole);
                    //}
                    //await _roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.Role, "projects.create"));


                    //var accountManagerRole = await _roleManager.FindByNameAsync("Account Manager");

                    //if (accountManagerRole == null)
                    //{
                    //    accountManagerRole = new IdentityRole("Account Manager");
                    //    await _roleManager.CreateAsync(accountManagerRole);

                    //    await _roleManager.AddClaimAsync(accountManagerRole, new Claim(, "account.manage"));
                    //}


                    var principal = _signInManager.CreateUserPrincipalAsync(user).Result.Claims.ToList();

                    var xfd = _userManager.GetClaimsAsync(user).Result;


                    // ClaimsIdentity claim = new ClaimsIdentity();
                    // _signInManager.
                    var now    = DateTime.UtcNow;
                    var claims = new Claim[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, model.Username),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                    };
                    var claimslist = claims.ToList();
                    foreach (var claim in principal)
                    {
                        claimslist.Add(claim);
                    }
                    ;

                    // Create the JWT security token and encode it.
                    var jwt = new JwtSecurityToken(
                        issuer: _jwtOptions.Issuer,
                        audience: _jwtOptions.Audience,
                        claims: principal,
                        notBefore: _jwtOptions.NotBefore,
                        expires: _jwtOptions.Expiration,
                        signingCredentials: _jwtOptions.SigningCredentials);

                    var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                    // Serialize and return the response
                    var response = new
                    {
                        access_token = encodedJwt,
                        expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                    };


                    if (!String.IsNullOrEmpty(model.TokenFirebase))
                    {
                        user.APPTOKEN = model.TokenFirebase;
                        await _userManager.UpdateAsync(user);
                    }

                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = true,
                        Message      = "Đăng nhập thành công",
                        access_token = encodedJwt,
                        expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                    };
                }
                else
                {
                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = false,
                        Message      = "Đăng nhập thất bại vui lòng kiểm tra lại thông tin",
                        access_token = null,
                        expires_in   = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
Example #24
0
        public async Task ObjectResult_MultipleFormattersSupportingTheSameContentType_SelectsTheFirstFormatterInList()
        {
            // Arrange
            var input = "testInput";
            var stream = new MemoryStream();

            var httpResponse = GetMockHttpResponse();
            var actionContext = CreateMockActionContext(httpResponse.Object, requestAcceptHeader: null);
            var result = new ObjectResult(input);

            // It should select the mock formatter as that is the first one in the list.
            var contentTypes = new[] { "application/json", "text/custom" };
            var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse("text/custom");

            // Get a  mock formatter which supports everything.
            var mockFormatter = GetMockFormatter();

            result.ContentTypes = contentTypes.Select(contentType => MediaTypeHeaderValue.Parse(contentType)).ToList();
            result.Formatters = new List<IOutputFormatter>
                                        {
                                            mockFormatter.Object,
                                            new JsonOutputFormatter(),
                                            new CannotWriteFormatter()
                                        };
            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Verify that mock formatter was chosen.
            mockFormatter.Verify(o => o.WriteAsync(It.IsAny<OutputFormatterContext>()));
        }
        protected void ButtonPrintAndProcess_Click(object sender, EventArgs e)
        {
            ModelTMSContainer _ControlObjectContext = new ModelTMSContainer(Session["CustomerConnectString"].ToString(), Session);

            // start transaction
            using (TransactionScope TS = new TransactionScope())
            {
                try
                {
                    // create new invoice
                    Invoice NewInvoice = new Invoice();
                    NewInvoice.Relation = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RelationSet", "Id", Guid.Parse(DropDownListCustomers.SelectedValue))) as Relation;
                    if (DropDownListLocations.SelectedValue != "")
                    {
                        NewInvoice.Location = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.LocationSet", "Id", Guid.Parse(DropDownListLocations.SelectedValue))) as Location;
                    }
                    NewInvoice.Description     = TextBoxInvoiceDescription.Text;
                    NewInvoice.InvoiceNote     = TextBoxInvoiceNote.Text;
                    NewInvoice.InvoiceType     = LabelInvoiceType.Text;
                    NewInvoice.BookingDateTime = Common.CurrentClientDateTime(Session);
                    NewInvoice.InvoiceNote     = TextBoxInvoiceNote.Text;
                    _ControlObjectContext.AddToInvoiceSet(NewInvoice);

                    // add order lines
                    for (int i = 0; i < GridViewOpenOrders.Rows.Count; i++)
                    {
                        if ((GridViewOpenOrders.Rows[i].Cells[0].Controls[1] as CheckBox).Checked)
                        {
                            // load order
                            string Query = "SELECT VALUE it FROM OrderSet as it WHERE it.OrderNumber = @OrderNumber";
                            ObjectQuery <Order> query = new ObjectQuery <Order>(Query, _ControlObjectContext);
                            query.Parameters.Add(new ObjectParameter("OrderNumber", Convert.ToInt64(GridViewOpenOrders.Rows[i].Cells[2].Text)));
                            ObjectResult <Order> ilines = query.Execute(MergeOption.AppendOnly);
                            Order TempOrder             = ilines.First <Order>();

                            // save location in the invoice if this was unknown yet
                            if ((TempOrder.Location != null) && (NewInvoice.Location == null))
                            {
                                NewInvoice.Location = TempOrder.Location;

                                if (NewInvoice.Ledger == null)
                                // set ledger for this invoice (default bank)
                                {
                                    NewInvoice.Ledger = NewInvoice.Location.BankLedger;
                                }
                            }

                            // add to invoice
                            NewInvoice.AddOrderToInvoice(_ControlObjectContext, TempOrder);
                        }
                    }

                    // subtract advance payments
                    WebUserControlEditAdvancePayments1.LoadAPLines();
                    for (int i = 0; i < WebUserControlEditAdvancePayments1.AdvancePaymentLines.Count; i++)
                    {
                        Guid TempGuid;
                        TempGuid = (WebUserControlEditAdvancePayments1.AdvancePaymentLines[i] as RelationAdvancePayment).Id;

                        // load the work or advance payment object
                        RelationAdvancePayment CurrAP   = null;
                        RelationWork           CurrWork = null;
                        try
                        {
                            CurrAP = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RelationAdvancePaymentSet", "Id", TempGuid)) as RelationAdvancePayment;
                            NewInvoice.AddAdvancePaymentCorrection(_ControlObjectContext, CurrAP, (WebUserControlEditAdvancePayments1.AdvancePaymentLines[i] as RelationAdvancePayment).Amount, (WebUserControlEditAdvancePayments1.AdvancePaymentLines[i] as RelationAdvancePayment).Description);
                        }
                        catch (Exception) { };
                        try
                        {
                            CurrWork = _ControlObjectContext.GetObjectByKey(new EntityKey("ModelTMSContainer.RelationWorkSet", "Id", TempGuid)) as RelationWork;
                            NewInvoice.AddWorkCorrection(_ControlObjectContext, CurrWork, (WebUserControlEditAdvancePayments1.AdvancePaymentLines[i] as RelationAdvancePayment).Amount, (WebUserControlEditAdvancePayments1.AdvancePaymentLines[i] as RelationAdvancePayment).Description);
                        }
                        catch (Exception) { };
                    }

                    // process the invoice
                    if (LabelGeneratedInvoiceId.Text != "")
                    {
                        // use old invoice id as group code
                        NewInvoice.GroupCode = new Guid(LabelGeneratedInvoiceId.Text);
                    }
                    NewInvoice.GenerateInvoiceNumber(_ControlObjectContext);
                    //NewInvoice.ProcessInvoice(_ControlObjectContext, NewInvoice.GroupCode); DO NOT PROCESS INVOICE !!! CUSTOMER HAS TO DO THAT SEPERATELY !!!
                    LabelGeneratedInvoiceId.Text = NewInvoice.Id.ToString();

                    // and save to persistent storage
                    _ControlObjectContext.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);

                    // commit the transaciton
                    TS.Complete();

                    // when success advance panel
                    CurrentPage = 5;
                    EnableCurrentPageElements();
                }
                catch (Exception ex)
                {
                    // rollback transaction
                    TS.Dispose();

                    // inform user
                    Common.InformUserOnTransactionFail(ex, Page);
                }
            }
        }
Example #26
0
        public async Task ObjectResult_NoFormatterFound_Returns406()
        {
            // Arrange
            var stream = new MemoryStream();
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);
            var input = "testInput";
            var result = new ObjectResult(input);

            // Set more than one formatters. The test output formatter throws on write.
            result.Formatters = new List<IOutputFormatter>
                                    {
                                        new CannotWriteFormatter(),
                                    };
            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Asserts that content type is not text/custom.
            httpResponse.VerifySet(r => r.StatusCode = StatusCodes.Status406NotAcceptable);
        }
 private static string ResponseJson(ObjectResult response)
 {
     return(JsonConvert.SerializeObject(response.Value));
 }
        /// <summary>
        /// Updates existing transformer entity based on provided transformerId with updated transformer model entity
        /// </summary>
        /// <param name="transformer">Transformer model entity</param>
        /// <param name="transformerId">Transformer Id</param>
        /// <returns></returns>
        public async Task <IActionResult> ExecuteUpdate(Transformer transformer, int transformerId)
        {
            IActionResult response;

            try
            {
                var validationResults = new List <ValidationResult>();
                var isValid           = Validator.TryValidateObject(transformer, new ValidationContext(transformer, serviceProvider: null, items: null), validationResults);

                if (!isValid)
                {
                    response = new ObjectResult(string.Join(", ", validationResults.Select(s => s.ErrorMessage)))
                    {
                        StatusCode = StatusCodes.Status412PreconditionFailed
                    };
                }
                else
                {
                    TransformerAllegiance transformerAllegiance = await _transformerRepository.getTransformerAllegiance(s => s.TransformerAllegianceId == transformer.AllegianceId);

                    if (transformerAllegiance == null)
                    {
                        response = new NotFoundObjectResult("Transformer allegiance not found!!");
                    }
                    else
                    {
                        Transformer transformerExistCheck = await _transformerRepository.getTransformer(s => (s.Name.ToLower().Trim() == transformer.Name.ToLower().Trim() &&
                                                                                                              s.AllegianceId == transformer.AllegianceId
                                                                                                              )
                                                                                                        );

                        if (transformerExistCheck != null)
                        {
                            TransformerAllegiance transformerAllegianceType = await _transformerRepository.getTransformerAllegiance(s => s.TransformerAllegianceId == transformer.AllegianceId);

                            response = new ObjectResult($"{transformer.Name} with {transformerAllegianceType.AllegianceName} already exists and hence cannot be updated !!");
                        }
                        else
                        {
                            Transformer botToUpdate = await _transformerRepository.getTransformer(s => s.TransformerId == transformerId);

                            if (botToUpdate != null)
                            {
                                botToUpdate.AllegianceId = transformer.AllegianceId;
                                botToUpdate.Name         = transformer.Name;
                                botToUpdate.Strength     = transformer.Strength;
                                botToUpdate.Intelligence = transformer.Intelligence;
                                botToUpdate.Speed        = transformer.Speed;
                                botToUpdate.Endurance    = transformer.Endurance;
                                botToUpdate.Rank         = transformer.Rank;
                                botToUpdate.Courage      = transformer.Courage;
                                botToUpdate.Firepower    = transformer.Firepower;
                                botToUpdate.Skill        = transformer.Skill;

                                int returnVal = await _transformerRepository.TransformerUpdate(botToUpdate);

                                response = (returnVal > 0 ? new OkObjectResult("Transformer updated successfully") : new ObjectResult("Transformer was not updated"));
                            }
                            else
                            {
                                response = new NotFoundObjectResult($"Transformer with TransformerId = {transformerId} not found!!");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response = new ObjectResult(ex);
            }
            return(response);
        }
        /// <summary>
        /// 异步接口日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            string       token = context.HttpContext.Request.Headers["ApiToken"].ParseToString();
            OperatorInfo user  = await Operator.Instance.Current(token);

            if (user != null)
            {
                // 根据传入的Token,设置CustomerId
                if (context.ActionArguments != null && context.ActionArguments.Count > 0)
                {
                    PropertyInfo property = context.ActionArguments.FirstOrDefault().Value.GetType().GetProperty("Token");
                    if (property != null)
                    {
                        property.SetValue(context.ActionArguments.FirstOrDefault().Value, token, null);
                    }
                    switch (context.HttpContext.Request.Method.ToUpper())
                    {
                    case "GET":
                        break;

                    case "POST":
                        property = context.ActionArguments.FirstOrDefault().Value.GetType().GetProperty("CustomerId");
                        if (property != null)
                        {
                            property.SetValue(context.ActionArguments.FirstOrDefault().Value, user.UserId, null);
                        }
                        break;
                    }
                }
            }
            var resultContext = await next();

            sw.Stop();

            #region 保存日志
            LogApiEntity logApiEntity = new LogApiEntity();
            logApiEntity.ExecuteUrl = context.HttpContext.Request.Path;
            logApiEntity.LogStatus  = OperateStatusEnum.Success.ParseToInt();

            #region 获取Post参数
            switch (context.HttpContext.Request.Method.ToUpper())
            {
            case "GET":
                logApiEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                break;

            case "POST":
                if (context.ActionArguments?.Count > 0)
                {
                    logApiEntity.ExecuteUrl  += context.HttpContext.Request.QueryString.Value.ParseToString();
                    logApiEntity.ExecuteParam = TextHelper.GetSubString(JsonConvert.SerializeObject(context.ActionArguments), 4000);
                }
                else
                {
                    logApiEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                }
                break;
            }
            #endregion

            if (resultContext.Exception != null)
            {
                #region 异常获取
                StringBuilder sbException = new StringBuilder();
                Exception     exception   = resultContext.Exception;
                sbException.AppendLine(exception.Message);
                while (exception.InnerException != null)
                {
                    sbException.AppendLine(exception.InnerException.Message);
                    exception = exception.InnerException;
                }
                sbException.AppendLine(TextHelper.GetSubString(resultContext.Exception.StackTrace, 8000));
                #endregion

                logApiEntity.ExecuteResult = sbException.ToString();
                logApiEntity.LogStatus     = OperateStatusEnum.Fail.ParseToInt();
            }
            else
            {
                ObjectResult result = context.Result as ObjectResult;
                if (result != null)
                {
                    logApiEntity.ExecuteResult = JsonConvert.SerializeObject(result.Value);
                    logApiEntity.LogStatus     = OperateStatusEnum.Success.ParseToInt();
                }
            }
            if (user != null)
            {
                logApiEntity.BaseCreatorId = user.UserId;
            }
            logApiEntity.ExecuteParam  = TextHelper.GetSubString(logApiEntity.ExecuteParam, 4000);
            logApiEntity.ExecuteResult = TextHelper.GetSubString(logApiEntity.ExecuteResult, 4000);
            logApiEntity.ExecuteTime   = sw.ElapsedMilliseconds.ParseToInt();

            Action taskAction = async() =>
            {
                // 让底层不用获取HttpContext
                logApiEntity.BaseCreatorId = logApiEntity.BaseCreatorId ?? 0;

                await new LogApiBLL().SaveForm(logApiEntity);
            };
            AsyncTaskHelper.StartTask(taskAction);
            #endregion
        }
        public async Task <IActionResult> Round(RoundViewModel newRound)
        {
            IActionResult   _result          = new ObjectResult(false);
            NextRoundResult _nextRoundResult = null;
            GenericResult   _genericResult   = null;

            try
            {
                if (ModelState.IsValid)
                {
                    Game game = _gameRepository.GetSingle(newRound.GameId);
                    if (game != null)
                    {
                        if (game.ValidateMove(newRound.Move1) && game.ValidateMove(newRound.Move2))
                        {
                            Round lastRound = _gameRepository.GetLastRound(game.Id);
                            int   roundNo   = lastRound != null ? lastRound.RoundNo + 1 : 1;

                            Round roundToAdd = new Round()
                            {
                                Move1   = newRound.Move1,
                                Move2   = newRound.Move2,
                                Game    = game,
                                RoundNo = roundNo
                            };

                            bool gameOver = PlayRound(roundToAdd);

                            _roundRepository.Add(roundToAdd);
                            _roundRepository.Commit();

                            if (gameOver == true && game.WinnerId == game.Player1Id)
                            {
                                _nextRoundResult = new NextRoundResult()
                                {
                                    Succeded = true,
                                    GameOver = true,
                                    Winner   = game.Player1,
                                    Round    = roundToAdd
                                };
                            }
                            else if (gameOver == true && game.WinnerId == game.Player2Id)
                            {
                                _nextRoundResult = new NextRoundResult()
                                {
                                    Succeded = true,
                                    GameOver = true,
                                    Winner   = game.Player2,
                                    Round    = roundToAdd
                                };
                            }
                            else
                            {
                                _nextRoundResult = new NextRoundResult()
                                {
                                    Succeded = true,
                                    GameOver = false,
                                    Winner   = roundToAdd.Winner,
                                    Round    = roundToAdd
                                };
                            }

                            _result = new ObjectResult(_nextRoundResult);
                            return(_result);
                        }
                        else
                        {
                            var json = JsonConvert.SerializeObject(newRound);
                            _genericResult = new GenericResult()
                            {
                                Succeeded = false,
                                Message   = "Move1 " + newRound.Move1 + " or Move2 " + newRound.Move2 + " are invalid for the game settings"
                            };

                            _loggingRepository.Add(new Error()
                            {
                                Message = "Invalid Move1 or Move2 POST api/game/round Move1 " + newRound.Move1 + " Move2 " + newRound.Move2, DateCreated = DateTime.Now
                            });
                            _loggingRepository.Commit();
                            _result = new ObjectResult(_genericResult);
                            return(_result);
                        }
                    }
                    else
                    {
                        var json = JsonConvert.SerializeObject(newRound);
                        _genericResult = new GenericResult()
                        {
                            Succeeded = false,
                            Message   = "Game with id " + newRound.GameId + " was not found"
                        };

                        _loggingRepository.Add(new Error()
                        {
                            Message = "Invalid Model POST api/game/round " + json, DateCreated = DateTime.Now
                        });
                        _loggingRepository.Commit();
                        _result = new ObjectResult(_genericResult);
                        return(_result);
                    }
                }
                else
                {
                    var json = JsonConvert.SerializeObject(newRound);
                    _genericResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Invalid parameter fields " + json
                    };

                    _loggingRepository.Add(new Error()
                    {
                        Message = "Invalid Model POST api/game/round " + json, DateCreated = DateTime.Now
                    });
                    _loggingRepository.Commit();
                    _result = new ObjectResult(_genericResult);
                    return(_result);
                }
            }
            catch (Exception ex)
            {
                _genericResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
                _result = new ObjectResult(_genericResult);
                return(_result);
            }
        }
        public IActionResult EnrollStudent(EnrollStudentRequest request)
        {
            EnrollStudentResponse esr = new EnrollStudentResponse()
            {
            };

            using (var con = new SqlConnection(ConString))
                using (var com = new SqlCommand())
                {
                    con.Open();
                    var tran = con.BeginTransaction();
                    com.Connection  = con;
                    com.Transaction = tran;
                    try
                    {
                        com.CommandText = "SELECT IdStudy AS idStudies FROM Studies WHERE Name=@name";
                        com.Parameters.AddWithValue("name", request.Studies);
                        var dr = com.ExecuteReader();
                        if (!dr.Read())
                        {
                            dr.Close();
                            tran.Rollback();
                            return(new NotFoundResult());
                        }

                        int idStudies = (int)dr["idStudies"];
                        dr.Close();

                        com.CommandText = "SELECT IndexNumber FROM Student WHERE IndexNumber= '" + request.IndexNumber + "'";

                        dr = com.ExecuteReader();
                        if (dr.Read())
                        {
                            dr.Close();
                            tran.Rollback();
                            return(new BadRequestResult());
                        }
                        dr.Close();

                        int idEnrollment;

                        com.CommandText = "SELECT IdEnrollment FROM Enrollment WHERE IdEnrollment = (SELECT MAX(IdEnrollment) FROM Enrollment)";
                        dr = com.ExecuteReader();

                        if (!dr.Read())
                        {
                            idEnrollment = 1;
                            dr.Close();
                            com.CommandText = "INSERT INTO Enrollment(IdEnrollment, Semester, IdStudy, StartDate) VALUES (" + idEnrollment + ", 1, " + idStudies + ", GetDate())";
                            com.ExecuteNonQuery();
                        }
                        idEnrollment = (int)dr["IdEnrollment"];
                        dr.Close();

                        string   sDateFormat = "dd.MM.yyyy";
                        DateTime BirthDate   = DateTime.ParseExact(request.BirthDate.ToString(), sDateFormat, CultureInfo.InvariantCulture);

                        com.CommandText = $"Insert INTO Student VALUES (@IndexNumber, @FirstName, @LastName, @BirthDate, @IdEnrollment)";
                        com.Parameters.AddWithValue("IndexNumber", request.IndexNumber);
                        com.Parameters.AddWithValue("FirstName", request.FirstName);
                        com.Parameters.AddWithValue("LastName", request.LastName);
                        com.Parameters.AddWithValue("BirthDate", BirthDate);
                        com.Parameters.AddWithValue("IdEnrollment", idEnrollment);
                        com.ExecuteNonQuery();

                        esr.IdEnrollment = idEnrollment;
                        esr.IdStudy      = idStudies;
                        esr.Semester     = 1;
                        esr.StartDate    = DateTime.Now;
                        tran.Commit();
                        tran.Dispose();

                        ObjectResult objectResult = new ObjectResult(esr);
                        objectResult.StatusCode = 201;
                        return(objectResult);
                    }
                    catch (SqlException exc)
                    {
                        tran.Rollback();
                        return(new BadRequestResult());
                    }
                }
            throw new NotImplementedException();
        }
Example #32
0
        //[Authorize(Roles ="UploadFilesToContract")]
        public async Task <ObjectResult> UploadFiles()
        {
            GenericResult gr = new GenericResult();

            var files      = Request.Form.Files;
            var contractID = Request.Form["CONTRACT_ID"];
            var rootPath   = _env.ContentRootPath;
            var pathRoot   = Path.Combine(rootPath, "\\Container\\ContractFilesFromCustomer");
            var folderPath = Path.Combine(pathRoot, contractID);

            List <CmsContractFileUpload> data = new List <CmsContractFileUpload>();

            if (files != null)
            {
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                foreach (var item in files)
                {
                    if (item != null && item.Length > 0)
                    {
                        var finalPath = Path.Combine(folderPath, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-tt") + item.FileName);
                        using (var stream = new FileStream(finalPath, FileMode.Create))
                        {
                            await item.CopyToAsync(stream);

                            FileInfo info = new FileInfo(finalPath);

                            var t = new CmsContractFileUpload()
                            {
                                CONTRACT_ID   = contractID,
                                FILE_NAME     = info.Name,
                                PATH          = info.FullName,
                                FILE_SIZE     = info.Length,
                                FILE_TYPE     = info.Extension,
                                AUTH_STATUS   = "A",
                                RECORD_STATUS = "1",
                                CREATE_DT     = DateTime.Now,
                                TYPE          = "O"
                            };

                            data.Add(t);
                        }
                    }
                }
                gr.Message   = "Upload file thành công!";
                gr.Succeeded = true;
                gr.Data      = data;
            }
            else
            {
                gr.Message   = "Không có files được tải lên!";
                gr.Data      = "";
                gr.Succeeded = false;
            }
            ObjectResult obj = new ObjectResult(gr);

            return(obj);
        }
Example #33
0
        /// <summary>
        /// Performs the query composition after action is executed. It first tries to retrieve the IQueryable from the
        /// returning response message. It then validates the query from uri based on the validation settings on
        /// <see cref="EnableQueryAttribute"/>. It finally applies the query appropriately, and reset it back on
        /// the response message.
        /// </summary>
        /// <param name="actionExecutedContext">The context related to this action, including the response message,
        /// request message and HttpConfiguration etc.</param>
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext == null)
            {
                throw Error.ArgumentNull("actionExecutedContext");
            }

            HttpRequest request = actionExecutedContext.HttpContext.Request;

            if (request == null)
            {
                throw Error.Argument("actionExecutedContext", SRResources.ActionExecutedContextMustHaveRequest);
            }

            ActionDescriptor actionDescriptor = actionExecutedContext.ActionDescriptor;

            if (actionDescriptor == null)
            {
                throw Error.Argument("actionExecutedContext", SRResources.ActionContextMustHaveDescriptor);
            }

            HttpResponse response = actionExecutedContext.HttpContext.Response;

            // Check is the response is set and successful.
            if (response != null && IsSuccessStatusCode(response.StatusCode) && actionExecutedContext.Result != null)
            {
                // actionExecutedContext.Result might also indicate a status code that has not yet
                // been applied to the result; make sure it's also successful.
                StatusCodeResult statusCodeResult = actionExecutedContext.Result as StatusCodeResult;
                if (statusCodeResult == null || IsSuccessStatusCode(statusCodeResult.StatusCode))
                {
                    ObjectResult responseContent = actionExecutedContext.Result as ObjectResult;
                    if (responseContent != null)
                    {
                        //throw Error.Argument("actionExecutedContext", SRResources.QueryingRequiresObjectContent,
                        //    actionExecutedContext.Result.GetType().FullName);

                        // Get collection from SingleResult.
                        IQueryable   singleResultCollection = null;
                        SingleResult singleResult           = responseContent.Value as SingleResult;
                        if (singleResult != null)
                        {
                            // This could be a SingleResult, which has the property Queryable.
                            // But it could be a SingleResult() or SingleResult<T>. Sort by number of parameters
                            // on the property and get the one with the most parameters.
                            PropertyInfo propInfo = responseContent.Value.GetType().GetProperties()
                                                    .OrderBy(p => p.GetIndexParameters().Count())
                                                    .Where(p => p.Name.Equals("Queryable"))
                                                    .LastOrDefault();

                            singleResultCollection = propInfo.GetValue(singleResult) as IQueryable;
                        }

                        // Execution the action.
                        object queryResult = OnActionExecuted(
                            responseContent.Value,
                            singleResultCollection,
                            new WebApiActionDescriptor(actionDescriptor as ControllerActionDescriptor),
                            new WebApiRequestMessage(request),
                            (elementClrType) => GetModel(elementClrType, request, actionDescriptor),
                            (queryContext) => CreateAndValidateQueryOptions(request, queryContext),
                            (statusCode) => actionExecutedContext.Result = new StatusCodeResult((int)statusCode),
                            (statusCode, message, exception) => actionExecutedContext.Result = CreateBadRequestResult(message, exception));

                        if (queryResult != null)
                        {
                            responseContent.Value = queryResult;
                        }
                    }
                }
            }
        }
Example #34
0
 private async Task WhenTheMessageIsPosted()
 {
     _result = await _controller.Post(_projectId, _message);
 }
Example #35
0
        public IActionResult enrollStudent(Student student)
        {
            try
            {
                Enrollement enrollment = new Enrollement();

                var con = new SqlConnection(sqlConGlobal);
                var com = new SqlCommand();


                com.Connection = con;
                con.Open();
                SqlTransaction transaction = con.BeginTransaction();
                com.Transaction = transaction;

                List <string[]> resultSet = new List <string[]>();

                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "BEGIN " +
                                  "DECLARE @idStudy int = (SELECT Studies.IdStudy FROM Studies" +
                                  "WHERE Studies.Name = @studiesName); " +
                                  "DECLARE @idEnrollment int = (SELECT TOP 1 Enrollment.IdEnrollment FROM Enrollment " +
                                  "ORDER BY Enrollment.IdEnrollment DESC) + 1; " +
                                  "INSERT INTO Enrollment(IdEnrollment, Semester, IdStudy, StartDate)" +
                                  "VALUES (@idEnrollment, 1, @idStudy, CURRENT_TIMESTAMP) ; " +
                                  "Select @idEnrollment;" +
                                  "END";
                if (com.Connection.State != ConnectionState.Open)
                {
                    com.Connection.Open();
                }

                SqlDataReader dr;
                dr = com.ExecuteReader();

                while (dr.Read())
                {
                    string[] tmp = new string[dr.FieldCount];
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        tmp[i] = dr.GetValue(i).ToString();
                    }

                    resultSet.Add(tmp);
                }


                com.CommandType = CommandType.Text;
                com.Parameters.Clear();

                if (resultSet.Count == 0)
                {
                    return(new BadRequestResult());
                }

                com.CommandText = "SELECT * FROM Student WHERE Student.IndexNumber = @indexNumber";
                com.Parameters.AddWithValue("indexNumber", student.IndexNumber);

                dr = com.ExecuteReader();
                if (dr.Read())
                {
                    return(new BadRequestResult());
                }
                dr.Close();

                com.CommandText = "DECLARE @datetmp date = PARSE(@bdate as date USING 'en-GB');" +
                                  " INSERT INTO Student(IndexNumber, FirstName, LastName, BirthDate, IdEnrollment, Password, Salt)" +
                                  " VALUES (@indexNumber, @name, @lname, @datetmp, '1', @pass, @salt)";
                com.Parameters.Clear();
                com.Parameters.AddWithValue("indexNumber", student.IndexNumber);

                byte[] randomBytes = new byte[256 / 4];
                var    generator   = RandomNumberGenerator.Create();

                generator.GetBytes(randomBytes);
                var resultSalt = Convert.ToBase64String(randomBytes);
                var pass       = generateHash("pas" + student.IndexNumber, resultSalt);

                com.Parameters.AddWithValue("pass", pass);
                com.Parameters.AddWithValue("salt", resultSalt);
                com.Parameters.AddWithValue("name", student.FirstName);
                com.Parameters.AddWithValue("lname", student.LastName);
                com.Parameters.AddWithValue("bdate", student.BirthDate);
                com.ExecuteNonQuery();

                com.Parameters.Clear();

                com.Parameters.AddWithValue("indexNumber", student.IndexNumber);

                List <string[]> resultSet2 = new List <string[]>();

                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "DECLARE @datetmp date = PARSE(@bdate as date USING 'en-GB'); INSERT INTO Student VALUES(@indexNumber, @fname, @lname, @datetmp, @idEnrollment)";
                com.Parameters.Clear();
                if (com.Connection.State != ConnectionState.Open)
                {
                    com.Connection.Open();
                }

                dr = com.ExecuteReader();

                while (dr.Read())
                {
                    string[] tmp = new string[dr.FieldCount];
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        tmp[i] = dr.GetValue(i).ToString();
                    }

                    resultSet2.Add(tmp);
                }

                dr.Close();
                com.CommandType = CommandType.Text;
                com.Parameters.Clear();


                enrollment.IdEnrollment = resultSet2[0][0];
                enrollment.IdStudy      = resultSet2[0][2];
                enrollment.Semester     = resultSet2[0][1];
                enrollment.StartDate    = resultSet2[0][3];

                transaction.Commit();
                ObjectResult objectResult = new ObjectResult(enrollment);
                objectResult.StatusCode = 200;
                return(objectResult);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new BadRequestResult());
            }
        }
Example #36
0
        private void LoadData()
        {
            vgridCompanyInfo.DataSource = null;
            m_objCompany = null;
            this.Enabled = false;
            m_objDatabaseModel = new BrightPlatformEntities(UserSession.EntityConnection);

            if (m_AccountId > 0)
                m_objCompany = ObjectCompany.GetCompanyDetails(m_AccountId, m_objDatabaseModel).Execute(MergeOption.AppendOnly);

            if (m_objCompany != null) {
                vgridCompanyInfo.DataSource = m_objCompany;
                this.LoadStatistics();
                this.LoadCompanySubCampaignRemarks();
                this.Enabled = true;
            }
        }
        public static IActionResult ToActionResult(this ICommandResult item)
        {
            var actionResult = new ObjectResult(item);

            return(actionResult);
        }
Example #38
0
        public async Task NoAcceptAndContentTypeHeaders_406Formatter_DoesNotTakeEffect()
        {
            // Arrange
            var expectedContentType = "application/json; charset=utf-8";

            var input = 123;
            var httpResponse = new DefaultHttpContext().Response;
            httpResponse.Body = new MemoryStream();
            var actionContext = CreateMockActionContext(
                outputFormatters: new IOutputFormatter[] 
                {
                    new HttpNotAcceptableOutputFormatter(),
                    new JsonOutputFormatter()
                },
                response: httpResponse,
                requestAcceptHeader: null,
                requestContentType: null,
                requestAcceptCharsetHeader: null);

            var result = new ObjectResult(input);
            result.ContentTypes = new List<MediaTypeHeaderValue>();
            result.ContentTypes.Add(MediaTypeHeaderValue.Parse(expectedContentType));

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expectedContentType, httpResponse.ContentType);
        }
Example #39
0
        //     [Authorize(Roles = "EditUserGroup")]
        public async Task <IActionResult> PutAsync(int id, [FromBody] ApplicationGroupViewModel appGroupViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            IActionResult result        = new ObjectResult(false);
            GenericResult genericResult = null;

            var listRoleRemoveList = _appRoleService.GetListRoleByGroupId(appGroupViewModel.ID).ToList();
            //    List<ApplicationRoleViewModel> listRoleRemoveList2 = Mapper.Map<IEnumerable<IdentityRole>, IEnumerable<ApplicationRoleViewModel>>(listRoleRemoveList).ToList();

            var appGroup = _appGroupService.GetDetail(appGroupViewModel.ID);

            try
            {
                appGroup.UpdateApplicationGroup(appGroupViewModel);
                //    appGroup = PropertyCopy.Copy<ApplicationGroup, ApplicationGroupViewModel>(appGroupViewModel);
                _appGroupService.Update(appGroup);
                _appGroupService.Save();

                //save group
                var listRoleGroup = new List <ApplicationRoleGroup>();

                var roleByUser = appGroupViewModel.Roles.Where(x => x.Check).ToList();
                foreach (var role in roleByUser)
                {
                    listRoleGroup.Add(new ApplicationRoleGroup()
                    {
                        GroupId = appGroup.ID,
                        RoleId  = role.Id
                    });
                }

                //add role to user
                var listUserInGroup = _appGroupService.GetListUserByGroupId(appGroup.ID).ToList();

                //Xóa tất cả role thuộc group
                var listRoleRemoveName = listRoleRemoveList.Select(x => x.Name).ToArray();
                foreach (var user2 in listUserInGroup)
                {
                    foreach (var roleName in listRoleRemoveName)
                    {
                        await _userManager.RemoveFromRoleAsync(user2, roleName);
                    }
                }

                _appRoleService.AddRolesToGroup(listRoleGroup, appGroup.ID);

                _appRoleService.Save();

                var listRole = _appRoleService.GetListRoleByGroupId(appGroup.ID).ToList();

                var listRoleName = listRole.Select(x => x.Name).ToArray();
                foreach (var user in listUserInGroup)
                {
                    foreach (var roleName in listRoleName)
                    {
                        await _userManager.AddToRoleAsync(user, roleName);
                    }
                }


                genericResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Cập nhật nhóm người dùng thành công"
                };
            }
            catch (Exception ex)
            {
                genericResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = "Cập nhật nhóm người dùng thất bại" + ex.Message
                };
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }


            result = new ObjectResult(genericResult);
            return(result);
        }
Example #40
0
        public async Task ObjectResult_FallsBackOn_FormattersInOptions()
        {
            // Arrange
            var formatter = GetMockFormatter();
            var actionContext = CreateMockActionContext(
                new[] { formatter.Object },
                setupActionBindingContext: false);
            
            // Set the content type property explicitly to a single value.
            var result = new ObjectResult("someValue");

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            formatter.Verify(o => o.WriteAsync(It.IsAny<OutputFormatterContext>()));
        }
Example #41
0
        public async Task ObjectResult_Execute_NullContent_SetsStatusCode()
        {
            // Arrange
            var stream = new MemoryStream();
            var expectedStatusCode = StatusCodes.Status201Created;
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var formatters = new IOutputFormatter[]
            {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };
            var actionContext = CreateMockActionContext(formatters,
                                                        httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);
            var result = new ObjectResult(null);
            result.StatusCode = expectedStatusCode;

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            httpResponse.VerifySet(r => r.StatusCode = expectedStatusCode);
            Assert.Equal(0, httpResponse.Object.Body.Length);
        }
Example #42
0
        public async Task ObjectResult_MultipleContentTypes_PicksFirstFormatterWhichSupportsAnyOfTheContentTypes()
        {
            // Arrange
            var expectedContentType = "application/json; charset=utf-8";
            var input = "testInput";
            var httpResponse = GetMockHttpResponse();
            var actionContext = CreateMockActionContext(httpResponse.Object, requestAcceptHeader: null);
            var result = new ObjectResult(input);

            // It should not select TestOutputFormatter,
            // This is because it should accept the first formatter which supports any of the two contentTypes.
            var contentTypes = new[] { "application/custom", "application/json" };

            // Set the content type and the formatters property explicitly.
            result.ContentTypes = contentTypes.Select(contentType => MediaTypeHeaderValue.Parse(contentType))
                                              .ToList();
            result.Formatters = new List<IOutputFormatter>
                                    {
                                        new CannotWriteFormatter(),
                                        new JsonOutputFormatter(),
                                    };
            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Asserts that content type is not text/custom.
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
Example #43
0
        public async Task ObjectResult_PerformsContentNegotiation_OnAllMediaRangeAcceptHeaderMediaType(
            string acceptHeader,
            string expectedResponseContentType)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: acceptHeader,
                                    respectBrowserAcceptHeader: true);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
Example #44
0
        public async Task ObjectResult_NoContentTypeSetWithAcceptHeaders_PicksFormatterOnAcceptHeaders()
        {
            // Arrange
            var expectedContentType = "application/json; charset=utf-8";
            var input = "testInput";
            var stream = new MemoryStream();

            var httpResponse = GetMockHttpResponse();
            var actionContext =
                CreateMockActionContext(httpResponse.Object,
                                        requestAcceptHeader: "text/custom;q=0.1,application/json;q=0.9",
                                        requestContentType: "application/custom");
            var result = new ObjectResult(input);

            // Set more than one formatters. The test output formatter throws on write.
            result.Formatters = new List<IOutputFormatter>
                                    {
                                        new CannotWriteFormatter(),
                                        new JsonOutputFormatter(),
                                    };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Asserts that content type is not text/custom. i.e the formatter is not TestOutputFormatter.
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
        public async Task <IActionResult> New(GameViewModel game)
        {
            IActionResult _result        = new ObjectResult(false);
            GenericResult _gameNewResult = null;

            try
            {
                if (ModelState.IsValid)
                {
                    MembershipContext _player1Context = _membershipService.ValidatePlayer(game.Player1Name);
                    MembershipContext _player2Context = _membershipService.ValidatePlayer(game.Player2Name);

                    Player _player1 = _player1Context.Player;
                    Player _player2 = _player2Context.Player;

                    if (_player1 == null)
                    {
                        _player1 = _membershipService.CreatePlayer(game.Player1Name);
                    }

                    if (_player2 == null)
                    {
                        _player2 = _membershipService.CreatePlayer(game.Player1Name);
                    }

                    Game newGame = new Game()
                    {
                        Player1   = _player1,
                        Player2   = _player2,
                        StartedAt = DateTime.Now
                    };

                    _gameRepository.Add(newGame);
                    _gameRepository.Commit();

                    _result = new ObjectResult(newGame);
                    return(_result);
                }
                else
                {
                    var json = JsonConvert.SerializeObject(game);
                    _gameNewResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Invalid parameter fields " + json
                    };

                    _loggingRepository.Add(new Error()
                    {
                        Message = "Invalid Model POST api/game " + json, DateCreated = DateTime.Now
                    });
                    _loggingRepository.Commit();
                    _result = new ObjectResult(_gameNewResult);
                    return(_result);
                }
            }
            catch (Exception ex)
            {
                _gameNewResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
                _result = new ObjectResult(_gameNewResult);
                return(_result);
            }
        }
Example #46
0
            ObjectResult_NoContentTypeSetWithNoAcceptHeadersAndNoRequestContentType_PicksFirstFormatterWhichCanWrite()
        {
            // Arrange
            var stream = new MemoryStream();
            var expectedContentType = "application/json; charset=utf-8";
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);
            var input = "testInput";
            var result = new ObjectResult(input);

            // Set more than one formatters. The test output formatter throws on write.
            result.Formatters = new List<IOutputFormatter>
                                    {
                                        new CannotWriteFormatter(),
                                        new JsonOutputFormatter(),
                                    };
            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Asserts that content type is not text/custom.
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);
        }
Example #47
0
        public void TrimOrGetLastAccessTimeStop(Context context, IList <Tuple <ContentHashWithLastAccessTimeAndReplicaCount, bool> > input, ObjectResult <IList <ContentHashWithLastAccessTimeAndReplicaCount> > result)
        {
            if (context.IsEnabled)
            {
                var stringResult = result.Succeeded ? string.Join(",", result.Data) : result.ErrorMessage;
                TracerOperationFinished(context, result, $"{Name}.{TrimOrGetLastAccessTimeCallName}({input.Count}) stop {result.DurationMs}ms result=[{stringResult}]");
            }

            _trimOrGetLastAccessTimeCallCounter.Completed(result.Duration.Ticks);
        }
Example #48
0
        public async Task ObjectResult_Execute_CallsContentResult_SetsContent()
        {
            // Arrange
            var expectedContentType = "text/plain; charset=utf-8";
            var input = "testInput";
            var stream = new MemoryStream();

            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupProperty<string>(o => o.ContentType);
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var actionContext = CreateMockActionContext(httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);

            // Act
            var result = new ObjectResult(input);
            await result.ExecuteResultAsync(actionContext);

            // Assert
            httpResponse.VerifySet(r => r.ContentType = expectedContentType);

            // The following verifies the correct Content was written to Body
            Assert.Equal(input.Length, httpResponse.Object.Body.Length);
        }
Example #49
0
        public IActionResult RegisterUser([FromBody]  RegistrationViewModel newUser)
        {
            IActionResult _result             = new ObjectResult(false);
            GenericResult _registrationResult = null;

            try
            {
                if (ModelState.IsValid)
                {
                    if (newUser.RoleID != 0)
                    {
                        if (newUser.RoleID == 1 || newUser.RoleID == 2)
                        {
                            EmplonomyUser user = _empluser.RegisterManager(newUser.EmailAddress, newUser.Password, newUser.FirstName, newUser.LastName, newUser.PhoneCell, newUser.DepartmentID);

                            if (user != null)
                            {
                                _registrationResult = new GenericResult()
                                {
                                    Succeeded = true,
                                    Message   = "Registration succeeded"
                                };
                            }
                        }

                        if (newUser.RoleID == 3)
                        {
                            EmplonomyUser user = _empluser.RegisterUser(newUser.EmailAddress, newUser.Password, newUser.FirstName, newUser.LastName, newUser.PhoneCell, newUser.DepartmentID);
                            if (user != null)
                            {
                                _registrationResult = new GenericResult()
                                {
                                    Succeeded = true,
                                    Message   = "Registration succeeded"
                                };
                            }
                        }
                    }
                }
                else
                {
                    _registrationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Invalid fields."
                    };
                }
            }

            catch (Exception ex)
            {
                _registrationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_registrationResult);
            return(_result);
        }
Example #50
0
        public async Task ObjectResult_Execute_CallsJsonResult_SetsContent()
        {
            // Arrange
            var expectedContentType = "application/json; charset=utf-8";
            var nonStringValue = new { x1 = 10, y1 = "Hello" };
            var httpResponse = Mock.Of<HttpResponse>();
            httpResponse.Body = new MemoryStream();
            var actionContext = CreateMockActionContext(httpResponse);
            var tempStream = new MemoryStream();
            var tempHttpContext = new Mock<HttpContext>();
            var tempHttpResponse = new Mock<HttpResponse>();

            tempHttpResponse.SetupGet(o => o.Body).Returns(tempStream);
            tempHttpResponse.SetupProperty<string>(o => o.ContentType);
            tempHttpContext.SetupGet(o => o.Request).Returns(new DefaultHttpContext().Request);
            tempHttpContext.SetupGet(o => o.Response).Returns(tempHttpResponse.Object);
            var tempActionContext = new ActionContext(tempHttpContext.Object,
                                                      new RouteData(),
                                                      new ActionDescriptor());
            var formatterContext = new OutputFormatterContext()
            {
                HttpContext = tempActionContext.HttpContext,
                Object = nonStringValue,
                DeclaredType = nonStringValue.GetType()
            };
            var formatter = new JsonOutputFormatter();
            formatter.WriteResponseHeaders(formatterContext);
            await formatter.WriteAsync(formatterContext);

            // Act
            var result = new ObjectResult(nonStringValue);
            await result.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expectedContentType, httpResponse.ContentType);
            Assert.Equal(tempStream.ToArray(), ((MemoryStream)actionContext.HttpContext.Response.Body).ToArray());
        }
        public RoomData RoomResultsFromDB(ObjectResult<ReadRoom_Result> roomResults)
        {
            Room room = null;
            IEnumerable<RoomState> roomStates = null;
            IEnumerable<ParagraphState> paragraphStates = null;

            room = roomResults.Select(x => TypeAdapter.Adapt<Room>(x)).FirstOrDefault();

            var roomStateResults = roomResults.GetNextResult<ReadRoomStatesForPlayerRoom_Result>();
            roomStates = roomStateResults.Select(x => TypeAdapter.Adapt<RoomState>(x)).ToList();

            var paragraphStateResults = roomStateResults.GetNextResult<ReadParagraphStatesForPlayerRoom_Result>();
            paragraphStates = paragraphStateResults.Select(x => TypeAdapter.Adapt<ParagraphState>(x)).ToList();

            var nounResults = paragraphStateResults.GetNextResult<ReadNounsForPlayerRoom_Result>();
            IEnumerable<Noun> nouns = nounResults.Select(x => TypeAdapter.Adapt<Noun>(x)).ToList();

            foreach (var paragraphState in paragraphStates)
                paragraphState.Nouns = nouns.Where(x => x.ParagraphState == paragraphState.Id).ToArray();

            return new RoomData(room, roomStates, paragraphStates);
        }
Example #52
0
        public void ObjectResult_Create_CallsContentResult_InitializesValue()
        {
            // Arrange
            var input = "testInput";
            var actionContext = CreateMockActionContext();

            // Act
            var result = new ObjectResult(input);

            // Assert
            Assert.Equal(input, result.Value);
        }
Example #53
0
        public ActionResult PesquisaTempoReal()
        {
            tcc_imoveisEntities tcc = new tcc_imoveisEntities();

            ObjectResult <AtributosGerais_Result> atributos = tcc.ListaAtributosGerais();
            var listAtributos = atributos.ToList();

            string sessionId = System.Web.HttpContext.Current.Session.SessionID;


            ObjectResult <int?> insert = tcc.InserePesquisa(sessionId, "runtime_search_" + sessionId);
            List <int?>         id     = insert.ToList();

            if (id.ElementAt(0) != null)
            {
                int idPesquisa = Convert.ToInt32(id.ElementAt(0));

                System.Web.HttpContext.Current.Session.Add("pesquisa_id", idPesquisa);

                //varre os atributos validos no banco de dados
                foreach (var atributo in listAtributos)
                {
                    //varre as chaves vindas do post
                    foreach (string key in Request.Form.AllKeys)
                    {
                        //verifica se as chaves são validas
                        //verifica se o valor recuperado por post é referente a atributo.IdTipoDado
                        if (Regex.IsMatch(key, @"^" + atributo.IdImovelAtributoTipo.ToString() + "_[0-2]"))
                        {
                            if (!string.IsNullOrEmpty(Request.Form[key]))
                            {
                                string valor    = Request.Form[key];
                                string condicao = Request["condicao_" + key];

                                tcc.InsereAtributoPesquisa(idPesquisa,
                                                           atributo.IdImovelAtributoTipo,
                                                           HttpUtility.HtmlDecode(condicao),
                                                           valor);
                            }
                        }
                    }
                }

                //verifica se foi passado um poligono para ser gravado
                //verifica se a string esta no formato de poligono
                if (!string.IsNullOrEmpty(Request.Form["polygon"]) && Util.IsPolygon(Request.Form["polygon"]))
                {
                    string poligono = Util.ToPolygon(Request["polygon"]);
                    tcc.InserePoligono(idPesquisa, Util.ToPolygon(poligono));
                }

                //verifica se contem um ponto central para busca por raio
                //verifica se existeu ma distancia para busca por raio
                if (!string.IsNullOrEmpty(Request.Form["ponto_central"]) && !string.IsNullOrEmpty(Request.Form["distancia"]))
                {
                    string ponto = Request.Form["ponto_central"]; //
                    if (Util.IsPolygon(ponto))
                    {
                    }
                    ponto = "POINT" + ponto.Replace(",", "");
                    string distancia = Request.Form["distancia"];

                    tcc.InsereRaio(idPesquisa, ponto, distancia);
                }


                return(RedirectToAction("ListaResult", new { id = idPesquisa }));
            }
            return(RedirectToAction("/Map/BuscaGeral"));
        }
Example #54
0
        public async Task ObjectResult_WithStream_DoesNotSetContentType_IfNotProvided()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: null,
                                    requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = It.IsAny<string>(), Times.Never());
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Example #55
0
        public async Task ObjectResult_WithStream_SetsExplicitContentType()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/json",
                                    requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/foo");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Example #56
0
        public async Task ObjectResult_WithStringType_WritesTextPlain_Ignoring406Formatter()
        {
            // Arrange
            var expectedData = "Hello World!";
            var objectResult = new ObjectResult(expectedData);
            var outputFormatters = new IOutputFormatter[] 
            {
                new HttpNotAcceptableOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };

            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/json");

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "text/plain; charset=utf-8");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Example #57
0
        public async Task ObjectResult_MatchAllContentType_Throws(string content, string invalidContentType)
        {
            // Arrange
            var contentTypes = content.Split(',');
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            objectResult.ContentTypes = contentTypes.Select(contentType => MediaTypeHeaderValue.Parse(contentType))
                                                    .ToList();
            var actionContext = CreateMockActionContext();

            // Act & Assert
            var exception = await Assert.ThrowsAsync<InvalidOperationException>(
                () => objectResult.ExecuteResultAsync(actionContext));

            var expectedMessage = string.Format("The content-type '{0}' added in the 'ContentTypes' property is " +
              "invalid. Media types which match all types or match all subtypes are not supported.",
              invalidContentType);
            Assert.Equal(expectedMessage, exception.Message);
        }
Example #58
0
        public async Task ObjectResult_WildcardAcceptMediaType_AndExplicitResponseContentType(
            string acceptHeader,
            string expectedResponseContentType,
            bool respectBrowserAcceptHeader)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    acceptHeader,
                                    respectBrowserAcceptHeader: respectBrowserAcceptHeader);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
Example #59
-1
        public void Show(int pSubCampaignId, int pAccountId, int pContactId)
        {
            try {
                this.Enabled = false;
                StandardQuestionData = null;
                gcStandardQuestion.DataSource = null;
                StandardQuestionData = StandardQuestion.GetStandardQuestions(pSubCampaignId, pAccountId, pContactId);
                if (StandardQuestionData == null)
                    return;

                gcStandardQuestion.DataSource = StandardQuestionData;
                gvStandardQuestion.Columns["question"].Group();
                gvStandardQuestion.Columns["campaign"].Group();
                gvStandardQuestion.Columns["created_date"].Group();
                gvStandardQuestion.ExpandAllGroups();
                this.Enabled = true;
            }
            catch (Exception e) {
                NotificationDialog.Error("Bright Sales", e.InnerException.Message);
            }
        }
Example #60
-1
        public async Task ObjectResult_WithMultipleContentTypes_Ignores406Formatter()
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/json"));
            var outputFormatters = new IOutputFormatter[] 
            {
                new HttpNotAcceptableOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "{\"Name\":\"John\"}";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/non-existing",
                                    requestContentType: "application/non-existing");

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/json; charset=utf-8");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }