public HttpResponseMessage Get(string name)
        {
            try
            {
                var deployment = unitOfWork.GetInstance <Deployment>().Find(d => d.Name == name).FirstOrDefault();
                if (deployment != null)
                {
                    //if the required deployment exists, return the deployment
                    ServiceResponse = new APIResponseModel("Deployment available", HttpStatusCode.OK, deployment, false);
                }
                else
                {
                    //if no deploment exists with the required name, notify user that no deployment with such name exists
                    ServiceResponse = new APIResponseModel("Deployment does not exist", HttpStatusCode.InternalServerError, deployment, true);
                }
            }
            catch (Exception ex)
            {
                //if an error occurs, return error message with code
                ServiceResponse = new APIResponseModel("Failed to get deployments", HttpStatusCode.InternalServerError, null, true);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
            }

            //return successful response
            return(Request.CreateResponse(HttpStatusCode.OK, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
        }
 public HttpResponseMessage List()
 {
     try
     {
         var deployments = unitOfWork.GetInstance <Deployment>().GetAll();
         if (deployments != null && deployments.Count() > 0)
         {
             //if deployments exist, return the available deployments
             ServiceResponse = new APIResponseModel("Deployments available", HttpStatusCode.OK, deployments, false);
         }
         else
         {
             //if no deploments exist, notify user that no deployments are available
             ServiceResponse = new APIResponseModel("No deployments available at the moment", HttpStatusCode.OK, deployments, false);
         }
     }
     catch (Exception ex)
     {
         //if an error occurs, return error message with code
         ServiceResponse = new APIResponseModel("Failed to get deployments", HttpStatusCode.InternalServerError, null, true);
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
     }
     //return successful response
     return(Request.CreateResponse(HttpStatusCode.OK, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
 }
Exemple #3
0
    //private static string baseUrl = "http://localhost:5050";

    public static APIResponseModel MakeRequest(string endpoint, string method = "POST", string json = "{}")
    {
        string           result   = "{}";
        APIResponseModel response = new APIResponseModel();

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(APIManager.baseUrl + endpoint);

        if (method == "POST")
        {
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = method;
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
        }

        httpWebRequest.GetRequestStream();

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result   = streamReader.ReadToEnd();
            response = APIResponseModel.CreateFromJSON(result);
        }

        return(response);
    }
        public HttpResponseMessage Delete(string name)
        {
            try
            {
                var existingDeployment = unitOfWork.GetInstance <Deployment>().Find(d => d.Name == name).FirstOrDefault();
                if (existingDeployment == null)
                {
                    //if a deployment with the specified name does not exist, notify user
                    ServiceResponse = new APIResponseModel("A deployment with this name does not exists!", HttpStatusCode.InternalServerError, null, true);
                }
                else
                {
                    //if a deployment with the secified name is found, proceed to delete
                    unitOfWork.GetInstance <Deployment>().Remove(existingDeployment);
                    unitOfWork.Complete();

                    //notify user of successful deployment delete
                    ServiceResponse = new APIResponseModel("Deployment has been successfully deleted!", HttpStatusCode.OK, null, false);
                }
            }
            catch (Exception ex)
            {
                //if an error occurs, return error message with code
                ServiceResponse = new APIResponseModel("Failed to delete deployment", HttpStatusCode.InternalServerError, null, true);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
            }

            //return successful response
            return(Request.CreateResponse(HttpStatusCode.OK, ServiceResponse, JsonMediaTypeFormatter.DefaultMediaType));
        }
Exemple #5
0
        public static async Task <APIResponseModel <NTModel> > SaveAsync(Func <string, Task> action, string message)
        {
            APIResponseModel <NTModel> api;

            try
            {
                await action(null);

                api = new APIResponseModel <NTModel>()
                {
                    Result = APIResult.Success, Model = null, Message = message
                };
            }
            catch (NTException exp)
            {
                api = new APIResponseModel <NTModel>()
                {
                    Result = APIResult.ValidationException, Model = new NTModel()
                    {
                        Data = exp.Errors
                    }, Message = exp.Message
                };
            }
            catch (System.Exception exp)
            {
                api = new APIResponseModel <NTModel>()
                {
                    Result = APIResult.Exception, Model = null, Message = exp.GetBaseException().Message
                };
            }

            return(api);
        }
Exemple #6
0
        protected async Task <APIResponseModel <T> > UpdateResourceAsync <T>(string url, object content)
        {
            using (var client = new HttpClient())
            {
                string apiServiceUrl = SharedClass.ApiServerUrl + (Lang == Language.English ? "en" : "ar") + "/";

                client.BaseAddress = new Uri(apiServiceUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //Model will be serialized automatically.
                var response = await client.PutAsJsonAsync(url, content);

                var result = new APIResponseModel <T>();

                if (response.IsSuccessStatusCode)
                {
                    //ReadAsAsync permits to deserialize the response content
                    var responseContent = await response.Content.ReadAsAsync <T>();

                    result.Result     = responseContent;
                    result.StatusCode = response.StatusCode;
                    return(result);
                }
                result.Result        = default(T);
                result.StatusCode    = response.StatusCode;
                result.StatusMessage = response.CreateApiException();
                return(result);
            }
        }
Exemple #7
0
 public CourseSessionController()
 {
     _courseBs           = new CourseBs();
     _courseSessionBs    = new CourseSessionBs();
     _courseSessionModel = new CourseSessionModel();
     apiResponse         = new APIResponseModel();
 }
        public void ShouldReturnApiResponseModelForRandomNumberMathFact()
        {
            // Arrange
            APIResponseModel apiResponseModel = new APIResponseModel();

            apiResponseModel.Number = 2030;
            apiResponseModel.Type   = "math";
            apiResponseModel.Text   = "some text";
            apiResponseModel.Found  = true;

            Mock <IRestClient> mockIRestClient = new Mock <IRestClient>();

            mockIRestClient.Setup(x => x.Execute <APIResponseModel>(It.IsAny <IRestRequest>()))
            .Returns(new RestResponse <APIResponseModel>
            {
                StatusCode = HttpStatusCode.OK,
                Data       = apiResponseModel,
            });

            NumfactsAPIClient numfactsAPIClient = new NumfactsAPIClient(mockIRestClient.Object);

            // Act
            APIResponseModel response = numfactsAPIClient.GetNumFact();

            // Assert
            Assert.AreEqual(2030, response.Number);
            Assert.AreEqual("math", response.Type);
            Assert.AreEqual("some text", response.Text);
            Assert.IsTrue(response.Found);
        }
        public HttpResponseMessage getOrders(bool chefOrCashier, int customerId, string fromDate, string toDate, string email, bool needUnpaidOnly)
        {
            GetOrdersRequestModel requestModel = new GetOrdersRequestModel();

            requestModel.chefOrCashier  = chefOrCashier;
            requestModel.customerId     = customerId;
            requestModel.fromDate       = fromDate;
            requestModel.toDate         = toDate;
            requestModel.email          = email;
            requestModel.needUnpaidOnly = needUnpaidOnly;
            if (requestModel.email.Equals("0"))
            {
                requestModel.email = null;
            }
            if (requestModel.fromDate.Equals("0"))
            {
                requestModel.fromDate = null;
            }
            if (requestModel.toDate.Equals("0"))
            {
                requestModel.toDate = null;
            }
            if (requestModel.customerId == 0)
            {
                requestModel.customerId = 0;
            }
            ErrorModel       errorModel       = null;
            OrderProvider    orderProvider    = new OrderProvider();
            var              orders           = orderProvider.getOrders(requestModel, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = orders;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
Exemple #10
0
 public CategoryController()
 {
     _categoryModel  = new CategoryModel();
     _categoryBs     = new CategoryBs();
     _userCategoryBs = new UserCategoryMappingBs();
     apiResponse     = new APIResponseModel();
 }
        public APIResponseModel GetNumFact()
        {
            // Define return variable
            APIResponseModel apiResponseModel = null;

            // Instantiate RestClient and RestRequest objects.
            RestRequest request = new RestRequest(Method.GET);

            // Add API authentication headers
            request.AddHeader(APIConstants.HEADER_HOST_NAME, APIConstants.HEADER_HOST_VALUE);
            request.AddHeader(APIConstants.HEADER_KEY_NAME, APIConstants.HEADER_KEY_VALUE);

            // Add parameters
            request.AddParameter(APIConstants.FRAGMENT_PARAM, true, ParameterType.QueryString);
            request.AddParameter(APIConstants.JSON_PARAM, true, ParameterType.QueryString);

            // Execute request
            var response = _client.Execute <APIResponseModel>(request);

            // Return data or throw exception
            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                apiResponseModel = response.Data;
            }
            else
            {
                throw new Exception(ErrorConstants.API_CONNECTION_ERROR);
            }

            return(apiResponseModel);
        }
Exemple #12
0
 public VolunteerController()
 {
     apiResponse     = new APIResponseModel();
     _VolunteerModel = new VolunteerModel();
     _VolunteerBs    = new VolunteerBs();
     _MasjidBs       = new MasjidBs();
 }
    private APIResponseModel CreatePlayer(string username, string hashedPassword, string email, string salt)
    {
        APIResponseModel response = new APIResponseModel();
        UserModel        user     = new UserModel()
        {
            username = username,
            email    = email,
            password = hashedPassword,
            salt     = salt
        };

        string json = user.SaveToString();

        //make the request to the remote API
        response = APIManager.MakeRequest(endpoint, "POST", json);

        if (response.status == 201)
        {
            user.token = response.token;
            Scenes.LoadGameView();
            Debug.Log("New user created");
        }
        else
        {
            Debug.Log(response.description);
            Debug.Log("Status code: " + response.status);
        }

        modalPanel.SetActive(false);

        return(response);
    }
Exemple #14
0
        public async Task <APIResponseModel <EmployeeModel> > Get(int pageNumber, int pageSize)
        {
            // Simple query to return all results mapped to the emplyee model while also using a limit and a selection based on page number and page size
            var results = await _applicationContext.Employee.Select(e => new EmployeeModel
            {
                Id           = e.Id,
                FirstName    = e.FirstName,
                LastName     = e.LastName,
                Organisation = new OrganisationModel
                {
                    OrganisationName   = e.Organisation.OrganisationName,
                    OrganisationNumber = e.Organisation.OrganisationNumber,
                    AddressLine1       = e.Organisation.AddressLine1,
                    AddressLine2       = e.Organisation.AddressLine2,
                    AddressLine3       = e.Organisation.AddressLine3,
                    AddressLine4       = e.Organisation.AddressLine4,
                    Town     = e.Organisation.Town,
                    Postcode = e.Organisation.Postcode
                }
            })
                          .OrderBy(e => e.FirstName)
                          .Skip(pageSize * (pageNumber - 1))
                          .Take(pageSize)
                          .ToListAsync();

            // mapping to an APIResponseModel to allow me to pass back number of pages to tell me how many page number buttons to render
            var response = new APIResponseModel <EmployeeModel>
            {
                data          = results,
                numberOfPages = (await _applicationContext.Employee.CountAsync() - 1) / pageSize + 1
            };

            return(response);
        }
Exemple #15
0
        public ActionResult CanManageCarOrNot()
        {
            var apiResponseModel = new APIResponseModel();

            try
            {
                var token = Request.Params["TOKEN"]?.ToString();

                var currentCustomer = _cacheService.Get <Customer>(token);
                if (currentCustomer == null)
                {
                    apiResponseModel.errorcode = "-1";
                    apiResponseModel.errormsg  = "重新登录";
                    return(Json(apiResponseModel));
                }
                bool canManagerCarOrNot = _permissionService.Authorize(StandardPermissionProvider.ManageCar, currentCustomer);
                apiResponseModel.errorcode = canManagerCarOrNot ? "0" : "-1";
                apiResponseModel.errormsg  = canManagerCarOrNot ? "成功" : "无权限";
                return(Json(apiResponseModel));
            }
            catch (Exception e)
            {
                apiResponseModel.errorcode = "-1";
                apiResponseModel.errormsg  = e.Message;
                return(Json(apiResponseModel));
            }
        }
Exemple #16
0
        public async void UpdateUser()
        {
            // Arrange
            this.SubscriptionDbContext.Users.AddRange(
                new UserEntity()
            {
                ID = 1, FirstName = "Yared", LastName = "Dejene", Email = "*****@*****.**", Role = "Administrator", Password = "******", IsDeleted = false
            },
                new UserEntity()
            {
                ID = 2, FirstName = "Tadese", LastName = "Tesfu", Email = "*****@*****.**", Role = "Superadmin", Password = "******", IsDeleted = false
            });

            await this.SaveChangesAsync(this.SubscriptionDbContext);

            UserModel model = new UserModel()
            {
                ID = 2, FirstName = "Tadese", LastName = "Taye"
            };

            // Act
            APIResponseModel <NTModel> ntModel = await this.Controller.UpdateUser(model);

            // Assert
            UserEntity entity = this.SubscriptionDbContext.Users.Where(e => e.ID == 2).First();

            Assert.Equal(entity.FirstName, "Tadese");
            Assert.Equal(ntModel.Message, SubscriptionMessages.UserUpdatedSuccess);
        }
Exemple #17
0
        public ActionResult WeChatLogin(string code)
        {
            var apiResponseModel = new APIResponseModel();

            if (string.IsNullOrWhiteSpace(code))
            {
                apiResponseModel.errorcode = "-1";
                apiResponseModel.errormsg  = "临时登录凭证不能为空";
                return(Json(apiResponseModel));
            }

            try
            {
                var weChatApi = new WeChatAPI();
                var result    = weChatApi.Authorization(code);
                var authModel = JsonUtil.Deserialize <AuthResponseModel>(result);
                if (string.IsNullOrWhiteSpace(authModel.openid))
                {
                    apiResponseModel.errorcode = "-1";
                    apiResponseModel.errormsg  = "错误";
                    apiResponseModel.data      = authModel;
                    return(Json(apiResponseModel));
                }

                var customer = _customerService.GetCustomerByOpenId(authModel.openid);
                if (customer == null)
                {
                    customer = new Customer()
                    {
                        OpenId              = authModel.openid,
                        CreatedOnUtc        = DateTime.Now,
                        LastLoginDateUtc    = DateTime.Now,
                        LastActivityDateUtc = DateTime.Now
                    };
                    _customerService.InsertCustomer(customer);
                }

                var token = Guid.NewGuid().ToString();
                if (_cacheService.IsSet(token))
                {
                    _cacheService.Remove(token);
                }

                _cacheService.Set(token, customer, 60);

                apiResponseModel.errorcode = "0";
                apiResponseModel.errormsg  = "登录成功";
                apiResponseModel.data      = token;
                return(Json(apiResponseModel));
            }
            catch (Exception e)
            {
                apiResponseModel.errorcode = "11";
                apiResponseModel.errormsg  = e.Message;
                apiResponseModel.data      = null;
                return(Json(apiResponseModel));
            }
        }
Exemple #18
0
 public QuestionController()
 {
     _courseTestModel       = new CourseTestModel();
     _courseTestBs          = new CourseTestBs();
     apiResponse            = new APIResponseModel();
     _courseBs              = new CourseBs();
     _courseTestAnswerBs    = new CourseTestAnswerBs();
     _courseTestAnswerModel = new CourseTestAnswerModel();
 }
Exemple #19
0
 public AccountController()
 {
     _userModel          = new UserModel();
     _userRegistrationBs = new UserRegistrationBs();
     _loginBs            = new LoginBs();
     _categoryBs         = new CategoryBs();
     _userGroupBs        = new UserGroupBS();
     apiResponse         = new APIResponseModel();
 }
        public HttpResponseMessage login(UserLoginRequestModel userLoginRequestModel)
        {
            AuthProvider authProvider = new AuthProvider();
            ErrorModel   errorModel   = new ErrorModel();

            APIResponseModel responseModel = new APIResponseModel();

            responseModel.Response = authProvider.login(userLoginRequestModel, out errorModel);
            responseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, responseModel));
        }
Exemple #21
0
 // Returns the appropriate output prefix for the fact depending on what the user requested.
 private static string MathOrTriviaFactPrefix(APIResponseModel responseModel)
 {
     if (responseModel.Type == APIConstants.MATH_FACT)
     {
         return(OutputConstants.MATH_FACT_PREFIX);
     }
     else
     {
         return(OutputConstants.TRIVIA_FACT_PREFIX);
     }
 }
        public HttpResponseMessage readyToPay(ReadyForPaymentRequestModel readyForPaymentRequest)
        {
            ErrorModel       errorModel       = null;
            OrderProvider    provider         = new OrderProvider();
            var              status           = provider.readyToPay(readyForPaymentRequest, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = status;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
Exemple #23
0
        public void ShouldCreateEmptyModel()
        {
            // Arrange / Act
            APIResponseModel apiResponseModel = new APIResponseModel();

            // Assert
            Assert.AreEqual(null, apiResponseModel.Text);
            Assert.AreEqual(null, apiResponseModel.Type);
            Assert.AreEqual(0, apiResponseModel.Number);
            Assert.IsFalse(apiResponseModel.Found);
        }
        public HttpResponseMessage changePassword(ChangePasswordRequestModel changePasswordRequest)
        {
            ErrorModel       errorModel       = null;
            UserProvider     userProvider     = new UserProvider();
            var              result           = userProvider.changePassword(changePasswordRequest, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = result;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
        public HttpResponseMessage getOrdersHistory(string startDate, string endDate)
        {
            OrderProvider    orderProvider    = new OrderProvider();
            ErrorModel       errorModel       = null;
            var              orders           = orderProvider.getOrdersHistory(startDate, endDate, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = orders;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
        public HttpResponseMessage editProfile(EditProfileRequestModel editProfileRequestModel)
        {
            ErrorModel       errorModel       = null;
            UserProvider     userProvider     = new UserProvider();
            var              result           = userProvider.editProfile(editProfileRequestModel, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = result;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
        public HttpResponseMessage changePaymentStatus(ChangePaymentStatusRequestModel changePaymentStatusRequest)
        {
            ErrorModel       errorModel       = null;
            OrderProvider    provider         = new OrderProvider();
            var              status           = provider.changePaymentStatus(changePaymentStatusRequest, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = status;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
        public async Task <IActionResult> JSEndpoint(int id)
        {
            APIConsumer externalAPI     = new APIConsumer();
            string      requestedRecord = await externalAPI.ReadAsync(id);

            APIResponseModel externalResponse = new APIResponseModel();

            externalResponse.APIResponse = requestedRecord + "(Passed through JS endpoint controller, rather than direct from JQuery, x1)";

            return(View("JSEndpoint", externalResponse));
        }
        public HttpResponseMessage addToCart(AddToCartRequestModel addToCartRequestModel)
        {
            CartProvider     cartProvider     = new CartProvider();
            ErrorModel       errorModel       = null;
            var              cartStatus       = cartProvider.addToCart(addToCartRequestModel, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = cartStatus;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }
        public HttpResponseMessage getCustomerNoticationData(int customerId, int capacity)
        {
            NotificationProvider notificationProvider = new NotificationProvider();
            ErrorModel           errorModel           = null;
            var data = notificationProvider.getNotificationsDataCustomer(customerId, capacity, out errorModel);
            APIResponseModel aPIResponseModel = new APIResponseModel();

            aPIResponseModel.Response = data;
            aPIResponseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, aPIResponseModel));
        }