public async Task <IActionResult> Edit([Bind] PatientResponseViewModel patientResponseViewModel)
        {
            PatientDTO patient = patientResponseViewModel.PatientResponse;
            string     url     = $"{PatientsApiUrl}Update";

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Put(accessToken, url, patient);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                AppContextHelper.SetToastMessage("Patient has been successfully updated", MessageType.Success, 1, Response);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                AppContextHelper.SetToastMessage("Failed to update patient", MessageType.Danger, 1, Response);
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }

            patientResponseViewModel.PatientStatuses = await GetPatientStatuses();

            patientResponseViewModel.IdentificationTypes = await GetIdentificationTypes();

            patientResponseViewModel.TransmissionClassifications = await GetClassifications();

            return(View(patientResponseViewModel));
        }
Example #2
0
        private void downloadMedia(int i)
        {
            string url = "http://37.148.210.36:8081/media?userId=" + userId + "&mediaId=" + mediaList[i].mediaId;

            byte[] array = null;
            HttpResponseHandler myHandler1 = (int statusCode, string responseText, byte[] responseData) =>
            {
                if (statusCode == 200)
                {
                    if (responseData != null)
                    {
                        byte[]           itemBGBytes = responseData;
                        AndroidJavaClass jc          = new AndroidJavaClass("android.os.Environment");
                        string           path        = jc.CallStatic <AndroidJavaObject>("getExternalStoragePublicDirectory", jc.GetStatic <string>("DIRECTORY_DCIM")).Call <string>("getAbsolutePath");
                        path = Path.Combine(path, "CommunicaptionMedias");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        string path2 = path + mediaList[i].fileName + ".jpg";
                        if (!File.Exists(path2))
                        {
                            File.WriteAllBytes(path2, itemBGBytes);
                            showAndroidToastMessage("Media saved successfully.");
                        }
                    }
                }
            };

            HttpRequest.Send(this, "GET", url, null, array, myHandler1);
        }
        public async Task <IActionResult> Create([Bind] ResponseTeamMemberDTO responseTeamMember)
        {
            string url = $"{CoreApiUrl}ResponseTeamMembers/Add";

            //Clean up phoner number
            var sanitizedNumber = PhoneNumberSanitizer.Sanitize(responseTeamMember.PhoneNumber, "+265");

            responseTeamMember.PhoneNumber = sanitizedNumber;
            var fullName = $"{responseTeamMember.FirstName} {responseTeamMember.Surname}";

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Post(accessToken, url, responseTeamMember);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                var identityResponse = await HttpRequestFactory.Post($"{IdentityServerAuthority}/api/Users/RegisterUser", new UserDTO { PhoneNumber = responseTeamMember.PhoneNumber, FullName = fullName });

                if (identityResponse.StatusCode == HttpStatusCode.Created)
                {
                    AppContextHelper.SetToastMessage("User account has been successfully created", MessageType.Danger, 1, Response);
                }
                AppContextHelper.SetToastMessage("Response team member has been successfully created", MessageType.Success, 1, Response);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                AppContextHelper.SetToastMessage("Failed to create response team member", MessageType.Danger, 1, Response);
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }

            return(View(responseTeamMember));
        }
    public void requestGet <T>(string baseHttpUrl, BaseParams baseParams, HttpResponseHandler <T> responseHandler)
    {
        string httpUrl = baseHttpUrl + baseParams.dataToUrlStr();

        LogUtil.log("requestGet:" + httpUrl);
        StartCoroutine(SendGet(httpUrl, responseHandler));
    }
 public ScriptController(IConfigurationRepository configurationRepository, IScriptManagementLogic scriptLogic, IPowershellEngine powershell)
 {
     this.powershell              = powershell;
     this.scriptLogic             = scriptLogic;
     this.configurationRepository = configurationRepository;
     this.http = new HttpResponseHandler(this);
 }
        private void validatePin()
        {
            pin = pinArea.GetComponent <InputField>().text;
            Debug.Log(pin);
            string url = "http://37.148.210.36:8081/connectWithHololens?pin=" + pin;

            byte[] array = null;
            HttpResponseHandler myHandler1 = (int statusCode, string responseText, byte[] responseData) =>
            {
                Debug.Log(statusCode);
                if (statusCode == 200)
                {
                    if (responseData != null)
                    {
                        var p = JsonConvert.DeserializeObject <UserId>(responseText);
                        userId = int.Parse(p.userId);
                        SettingsController.SetUserId(userId);
                        Debug.Log(SettingsController.GetUserId());
                        SceneManager.LoadScene("OptionsUI");
                    }
                    else
                    {
                        SceneManager.LoadScene("Welcome");
                    }
                }
            };

            HttpRequest.Send(this, "POST", url, null, array, myHandler1);
        }
Example #7
0
        public async Task <IActionResult> Index(int teamMemberId)
        {
            if (teamMemberId == 0)
            {
                if (_teamMemberId == 0)
                {
                    return(RedirectToAction("Index", "ResponseTeamMembers"));
                }
            }
            else
            {
                _teamMemberId = teamMemberId;
                var teamMember = await GetResponseTeamMember(teamMemberId);

                _teamMemberName = $"{teamMember.FirstName} {teamMember.OtherNames} {teamMember.Surname}";
            }
            ViewBag.TeamMemberName = _teamMemberName;

            string url = $"{CoreApiUrl}ResponseTeamMappings/GetByMember?teamMemberId={_teamMemberId}";
            var    ResponseTeamMembers = Enumerable.Empty <TeamMappingResponse>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                ResponseTeamMembers = response.ContentAsType <IEnumerable <TeamMappingResponse> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(ResponseTeamMembers));
        }
Example #8
0
        public async Task <IActionResult> Create([Bind] DataCenterResponseViewModel dataCenterResponseViewModel)
        {
            DataCenterDTO dataCenter = dataCenterResponseViewModel.DataCenterResponse;
            string        url        = $"{CoreApiUrl}DataCenters/Add";

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Post(accessToken, url, dataCenter);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                AppContextHelper.SetToastMessage("Identification type has been successfully created", MessageType.Success, 1, Response);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                AppContextHelper.SetToastMessage("Failed to create identification type", MessageType.Danger, 1, Response);
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            dataCenterResponseViewModel.Districts = await GetDistricts();

            dataCenterResponseViewModel.FacilityTypes = await GetFacilityTypes();

            return(View(dataCenterResponseViewModel));
        }
Example #9
0
            /// <summary>
            /// Get responses
            /// </summary>
            /// <param name="action">indicating the action</param>
            /// <param name="clientData">indicating the client data</param>
            /// <param name="resetToBegin">indicating the get response position</param>
            /// <param name="count">indicating the count</param>
            /// <param name="clientId">indicating the client id</param>
            void IResponseService.GetResponses(string action, string clientData, GetResponsePosition resetToBegin, int count, string clientId)
            {
                if (this.useAzureQueue)
                {
                    string azureResponseQueueUri;
                    string azureResponseBlobUri;

                    this.controller.GetResponsesAQ(action, clientData, resetToBegin, count, clientId, this.sessionHash, out azureResponseQueueUri, out azureResponseBlobUri);

                    // then retrieve the responses async from the azure queue proxy
                    if (!this.azureQueueProxy.IsResponseClientInitialized && !string.IsNullOrEmpty(azureResponseQueueUri) && !string.IsNullOrEmpty(azureResponseBlobUri))
                    {
                        this.azureQueueProxy.InitResponseClient(azureResponseQueueUri, azureResponseBlobUri);
                    }

                    // check if there is already a handler with the same action and clientData
                    foreach (IResponseHandler h in this.handlers)
                    {
                        if (h.Action().Equals(action, StringComparison.InvariantCulture) && h.ClientData().Equals(clientData, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return;
                        }
                    }

                    AzureQueueResponseHandler handler = new AzureQueueResponseHandler(this.azureQueueProxy, action, clientData, resetToBegin, count, clientId, this.callback, this);
                    this.handlers.Add(handler);
                    handler.Completed += new EventHandler(this.HandlerCompleted);
                }
                else
                {
                    HttpResponseHandler handler = new HttpResponseHandler(this.controller, action, clientData, resetToBegin, count, clientId, this.callback, this);
                    this.handlers.Add(handler);
                    handler.Completed += new EventHandler(this.HandlerCompleted);
                }
            }
Example #10
0
        private void loadOcrMedia()
        {
            string url = "http://37.148.210.36:8081/gallery?userId=" + userId;

            byte[] array = null;
            string downloadData;
            HttpResponseHandler myHandler1 = (int statusCode, string responseText, byte[] responseData) =>
            {
                Debug.Log(statusCode);
                if (statusCode == 200)
                {
                    Debug.Log(responseText);
                    if (responseText != null)
                    {
                        downloadData = responseText;
                        //downloadData = downloadData.Substring(10, downloadData.Length - 12);
                        Debug.Log(downloadData);
                        mediaList = JsonConvert.DeserializeObject <List <OcrMedia> >(downloadData);
                        foreach (var item in mediaList)
                        {
                            addItem(item.title, item.picture, item.artId);
                        }
                    }
                }
            };

            HttpRequest.Send(this, "GET", url, null, array, myHandler1);
        }
Example #11
0
        public async Task <IActionResult> Index(int centerId)
        {
            if (centerId == 0)
            {
                if (_centerId == 0)
                {
                    return(RedirectToAction("Index", "DataCenters"));
                }
            }
            else
            {
                _centerId = centerId;
                var dataCenter = await GetDataCenter(centerId);

                _centerName = dataCenter.CenterName;
            }
            ViewBag.CenterName = _centerName;
            string url = $"{CoreApiUrl}HealthCareWorkers/GetByDataCenter?centerId={_centerId}";
            var    healthCareWorkers = Enumerable.Empty <HealthCareWorkerDTO>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                healthCareWorkers = response.ContentAsType <IEnumerable <HealthCareWorkerDTO> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(healthCareWorkers));
        }
Example #12
0
        public async Task <JsonResult> GetPatientsByDate(DateTime fromDate, DateTime toDate)
        {
            string url      = $"{PatientsApiUrl}GetPatientsByDate?fromSubmissionDate={fromDate}&toSubmissionDate={toDate}";
            var    patients = Enumerable.Empty <PatientDTO>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                patients = response.ContentAsType <IEnumerable <PatientDTO> >();
                return(Json(patients));
            }
            else
            {
                if (response.StatusCode != HttpStatusCode.NoContent)
                {
                    return(Json(HttpResponseHandler.Process(response)));
                }
                else
                {
                    return(Json(patients));
                }
            }
        }
Example #13
0
        public async Task <IActionResult> Index(int statusId)
        {
            if (statusId == 0)
            {
                if (_statusId == 0)
                {
                    return(RedirectToAction("Index", "PatientStatuses"));
                }
            }
            else
            {
                _statusId = statusId;
                var patientStatus = await GetPatientStatus(statusId);

                _patientStatusName = patientStatus.PatientStatusName;
            }
            ViewBag.PatientStatusName = _patientStatusName;

            string url = $"{ResourcesApiUrl}ResourcesAllocation/GetByPatientStatusId?statusId={_statusId}";
            var    resourcesAllocation = Enumerable.Empty <ResourceAllocationResponse>();

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Get(accessToken, url);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resourcesAllocation = response.ContentAsType <IEnumerable <ResourceAllocationResponse> >();
            }
            else
            {
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            return(View(resourcesAllocation));
        }
    public void createNewArt()
    {
        string artTitle = ArtTitle.GetComponent <Text>().text;
        string userId   = SettingsController.GetUserId().ToString();

        Debug.Log(artTitle);

        string url = "http://37.148.210.36:8081/createArt?userId=" + userId + "&artTitle=" + artTitle;

        byte[] array = null;

        HttpResponseHandler myHandler1 = (int statusCode, string responseText, byte[] responseData) =>
        {
            Debug.Log(statusCode);
            Debug.Log(responseText);
            if (statusCode == 200)
            {
                if (responseData != null)
                {
                    var artId = (int)JObject.Parse(responseText)["artId"];
                    Global.detailedItemId = artId;
                    Global.detailsOrAdd   = false;
                    SceneManager.LoadScene("Ocr");
                }
            }
        };

        HttpRequest.Send(this, "POST", url, null, array, myHandler1);
    }
Example #15
0
        public async Task HttpPostInvoke(string url, IEnumerable <Header> headers, IEnumerable <Header> contentHeader,
                                         Dictionary <string, string> postParameters, TimeSpan timeOut,
                                         HttpResponseHandler httpResponseHandler)
        {
            // Build the form data (exclude OAuth stuff that's already in the
            // header).
            var formData = new FormUrlEncodedContent(postParameters);

            contentHeader.ToList().ForEach(h => { formData.Headers.Add(h.Key, h.Value); });
            using (var httpClient = new HttpClient())
            {
                headers.ToList().ForEach(h => { httpClient.DefaultRequestHeaders.Add(h.Key, h.Value); });

                HttpResponseMessage httpResponse = await httpClient.PostAsync(url, formData);

                string respBody = await httpResponse.Content.ReadAsStringAsync();

                List <Header> responseHeaders = new List <Header>();
                responseHeaders.AddRange(
                    httpResponse.Headers.Select(c =>
                {
                    return(Header.CreateHeader(c.Key, c.Value));
                }));
                List <Header> responseContentHeaders = new List <Header>();
                responseContentHeaders.AddRange(
                    httpResponse.Content.Headers.Select(c =>
                {
                    return(Header.CreateHeader(c.Key, c.Value));
                }));

                httpResponseHandler?.Invoke(this,
                                            new HttpInvokerResponseArgs(new HttpInvokerResponse(httpResponse.StatusCode,
                                                                                                httpResponse.ReasonPhrase, responseHeaders, responseContentHeaders, String.Empty, true)));
            }
        }
Example #16
0
        public async Task <IActionResult> Create([Bind] TeamMappingResponse teamMappingResponse)
        {
            ResponseTeamMappingDTO responseTeamMember = new ResponseTeamMappingDTO
            {
                CreatedBy    = teamMappingResponse.CreatedBy,
                DistrictCode = teamMappingResponse.DistrictCode,
                MappingId    = teamMappingResponse.MappingId,
                TeamMemberId = teamMappingResponse.TeamMemberId
            };

            string url = $"{CoreApiUrl}ResponseTeamMappings/Add";

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Post(accessToken, url, responseTeamMember);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                AppContextHelper.SetToastMessage("Response team member has been successfully mapped", MessageType.Success, 1, Response);
                return(RedirectToAction(nameof(Index), new { teamMemberId = _teamMemberId, teamMemberName = _teamMemberName }));
            }
            else
            {
                AppContextHelper.SetToastMessage("Failed to map response team member", MessageType.Danger, 1, Response);
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }
            ViewBag.TeamMemberName = _teamMemberName;
            return(View(teamMappingResponse));
        }
        public async Task <IActionResult> Edit([Bind] ScheduledNotificationViewModel scheduledNotificationViewModel)
        {
            ScheduledNotificationDTO scheduledNotification = scheduledNotificationViewModel.ScheduledNotification;

            string url = $"{NotificationsApiUrl}ScheduledNotifications/Update";

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var response = await HttpRequestFactory.Put(accessToken, url, scheduledNotification);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                AppContextHelper.SetToastMessage("Scheduled notification has been successfully updated", MessageType.Success, 1, Response);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                AppContextHelper.SetToastMessage("Failed to update scheduled notification", MessageType.Danger, 1, Response);
                ModelState.AddModelError("", HttpResponseHandler.Process(response));
            }

            scheduledNotificationViewModel.EscalationRules = await GetEscalationRules();

            scheduledNotificationViewModel.NotificationTemplates = await GetNotificationTemplates();

            scheduledNotificationViewModel.NotificationChannels = await GetNotificationChannels();

            return(View(scheduledNotificationViewModel));
        }
Example #18
0
        public async Task HttpGetStreamInvokeAsync(string url, IEnumerable <Header> headers,
                                                   TimeSpan timeOut, HttpResponseHandler httpResponseHandler)
        {
            using (var httpClient = new HttpClient())
            {
                headers.ToList().ForEach(h =>
                {
                    httpClient.DefaultRequestHeaders.Add(h.Key, h.Value);
                });

                HttpResponseMessage httpResponse = await httpClient.GetAsync(url);

                string respBody = await httpResponse.Content.ReadAsStringAsync();

                List <Header> responseHeaders = new List <Header>();
                responseHeaders.AddRange(
                    httpResponse.Headers.Select(c =>
                {
                    return(Header.CreateHeader(c.Key, c.Value));
                }));
                List <Header> responseContentHeaders = new List <Header>();
                responseContentHeaders.AddRange(
                    httpResponse.Content.Headers.Select(c =>
                {
                    return(Header.CreateHeader(c.Key, c.Value));
                }));

                httpResponseHandler?.Invoke(this,
                                            new HttpInvokerResponseArgs(new HttpInvokerResponse(httpResponse.StatusCode,
                                                                                                httpResponse.ReasonPhrase, responseHeaders, responseContentHeaders,
                                                                                                String.Empty, true)));
            }
        }
 public ActiveDirectoryMetadatasController(IConfigurationRepository configurationRepository, IActiveDirectoryRepository activeDirectory, IOpenIdConnectIdentityProviderLogic oidcLogic)
 {
     this.oidcLogic = oidcLogic;
     this.configurationRepository = configurationRepository;
     this.http            = new HttpResponseHandler(this);
     this.activeDirectory = activeDirectory;
 }
Example #20
0
        public X excute <X, Y>(Request <Y> request, HttpResponseHandler <X> responseHandler, KS3Signer <Y> ks3Signer) where Y : KS3Request
        {
            this.setUserAgent(request);

            HttpWebRequest  httpRequest  = null;
            HttpWebResponse httpResponse = null;
            X result = default(X);

            for (int i = 0; i < Constants.RETRY_TIMES; i++)
            {
                try
                {
                    // Sign the request if a signer was provided
                    if (ks3Signer != null && request.getOriginalRequest().getRequestCredentials() != null)
                    {
                        ks3Signer.sign(request, request.getOriginalRequest().getRequestCredentials());
                    }
                    request.setResourcePath(request.getResourcePath().Replace("%5C", "/").Replace("//", "/%2F"));
                    if (request.getResourcePath().EndsWith("%2F"))
                    {
                        request.setResourcePath(request.getResourcePath().Substring(0, request.getResourcePath().Length - 3));
                    }
                    httpRequest  = HttpRequestFactory.createHttpRequest(request, this.config);
                    httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                    result = responseHandler.handle(httpResponse);
                    break;
                }
                catch (WebException we)
                {
                    HttpWebResponse  errorResponse    = (HttpWebResponse)we.Response;
                    ServiceException serviceException = null;
                    try
                    {
                        serviceException = errorResponseHandler.handle(errorResponse);
                    }
                    catch
                    {
                        throw we;
                    }
                    throw serviceException;
                }
                catch (IOException ex) {
                    if (i == Constants.RETRY_TIMES - 1)
                    {
                        throw ex;
                    }
                    Thread.Sleep(1000);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Close();
                    }
                }
            }
            return(result);
        }
Example #21
0
 public PendingCertificatesController(ICertificateRepository certRepo, IConfigurationRepository configRepo, IAuthorizationLogic authorizationLogic, IAuditLogic auditLogic)
 {
     this.certificateRepository   = certRepo;
     this.configurationRepository = configRepo;
     this.authorizationLogic      = authorizationLogic;
     this.http  = new HttpResponseHandler(this);
     this.audit = auditLogic;
 }
Example #22
0
        // Mutators
        public void SetLogHandlers(HttpRequestHandler request, HttpResponseHandler response, HttpCommandHandler command)
        {
#if DEBUG
            RequestHandler  = request;
            ResponseHandler = response;
            CommandHandler  = command;
#endif
        }
 public PkiConfigurationAdcsTemplateController(AdcsTemplateLogic templateLogic)
 {
     //this.configurationRepository = configurationRepository;
     //this.runtimeConfigurationState = runtimeConfigurationState;
     //this.adcsTemplateLogic = new AdcsTemplateLogic(configurationRepository, null);
     this.adcsTemplateLogic = templateLogic;
     this.http          = new HttpResponseHandler(this);
     this.dataTransform = new DataTransformation();
 }
    public void getLeaderboradEntriesForUser(ulong leaderboardId, HttpResponseHandler <GetLeaderboardEntriesResult> responseHandler)
    {
        GetLeaderboardEntriesParams baseParams = new GetLeaderboardEntriesParams();

        baseParams.leaderboardid = leaderboardId;
        baseParams.steamid       = SteamUser.GetSteamID().m_SteamID;
        baseParams.datarequest   = "RequestAroundUser";
        getLeaderboardEntries(baseParams, responseHandler);
    }
Example #25
0
        //RoleManagementLogic roleManagement;

        public AuthenticationController(IdentityAuthenticationLogic authenticationLogic, IRuntimeConfigurationState runtimeConfigurationState, IConfigurationRepository configRepo, CertificateManagementLogic certificateManagementLogic)
        {
            this.authenticationLogic = authenticationLogic;
            this.http                       = new HttpResponseHandler(this);
            this.allowDevBypass             = true;
            this.runtimeConfigurationState  = runtimeConfigurationState;
            this.configurationRepository    = configRepo;
            this.certificateManagementLogic = certificateManagementLogic;
        }
    public void getSteamUserInfo(List <string> userId, HttpResponseHandler <SteamUserInfoResult> responseHandler)
    {
        SteamUserInfoParams baseParams = new SteamUserInfoParams();
        string steamIds = DevUtil.listToStringBySplit(userId, ",");

        baseParams.steamids = steamIds;
        baseParams.key      = CommonInfo.Steam_Key_All;
        baseParams.appid    = CommonInfo.Steam_App_Id;
        requestGet("ISteamUser/GetPlayerSummaries/v2", baseParams, responseHandler);
    }
 public PrivateCertificateAuthorityController(ICertificateRepository certRepo, IConfigurationRepository configRepo, ICertificateProvider certProvider, IAuthorizationLogic authorizationLogic, IAuditLogic auditLogic, AdcsTemplateLogic templateLogic)
 {
     this.certificateRepository   = certRepo;
     this.configurationRepository = configRepo;
     this.certificateProvider     = certProvider;
     this.authorizationLogic      = authorizationLogic;
     this.http          = new HttpResponseHandler(this);
     this.audit         = auditLogic;
     this.templateLogic = templateLogic;
 }
Example #28
0
 public void HttpGetStreamInvoke(string url, IEnumerable <Header> headers,
                                 HttpInvocationCompletionOption httpInvocationCompletionOption, TimeSpan timeOut,
                                 HttpResponseHandler httpResponseHandler, CancellationToken cancellationToken)
 {
     Task.Run(async() =>
     {
         await HttpStreamInvokeAsync(url, HttpMethod.Get, headers, null,
                                     httpInvocationCompletionOption, null, timeOut, httpResponseHandler, cancellationToken);
     }, cancellationToken);
 }
        public GoogleCustomSearchResponse Search(string query)
        {
            string googleCustomSearchApiKeyUrl = ConfigurationManager.AppSettings[Constants.GOOGLE_CUSTOM_SEARCH_API_KEY_URL];
            string googleSearchEngine          = ConfigurationManager.AppSettings[Constants.GOOGLE_SEARCH_ENGINE];
            string googleCustomSearchApiKey    = ConfigurationManager.AppSettings[Constants.GOOGLE_CUSTOM_SEARCH_API_KEY];

            using (var httpWebResponse = (HttpWebResponse)WebRequest.Create(string.Format(googleCustomSearchApiKeyUrl, googleCustomSearchApiKey, googleSearchEngine, query)).GetResponse())
            {
                return(HttpResponseHandler.GetDeserializedObjectFromResponse <GoogleCustomSearchResponse>(httpWebResponse));
            }
        }
Example #30
0
 public void HttpPostStreamInvoke(string url, IEnumerable <Header> headers,
                                  IEnumerable <Header> contentHeaders, HttpInvocationCompletionOption httpCompletetionOption,
                                  string postParameters, TimeSpan timeOut, HttpResponseHandler httpResponseHandler,
                                  CancellationToken cancellationToken)
 {
     Task.Run(async() =>
     {
         await HttpStreamInvokeAsync(url, HttpMethod.Post, headers, contentHeaders,
                                     httpCompletetionOption, postParameters, timeOut, httpResponseHandler,
                                     cancellationToken);
     }, cancellationToken);
 }
        private int dispatch(HttpWebRequest webRequest, Authenticator authenticator, HttpResponseHandler responseHandler)
        {

            HttpWebResponse webResponse;
            try
            {
                webResponse = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                webResponse = (HttpWebResponse)e.Response;
            }

            Stream entityStream = null;
            try
            {
                entityStream = webResponse.GetResponseStream();

                WebHeaderCollection responseHeaders = webResponse.Headers;
                if (null != authenticator)
                {
                    authenticator.handleHttpResponseHeaders(responseHeaders);
                }

                int statusCode = (int)webResponse.StatusCode;

                if (statusCode >= 200 && statusCode < 300)
                {
                    // all is well
                    if (null == entityStream) // e.g. http 204 
                    {
                        responseHandler.handleResponseEntity(responseHeaders, null);
                    }
                    else
                    {
                        long contentLength = webResponse.ContentLength;
                        log.debug(contentLength, "contentLength");

                        StreamEntity responseEntity = new StreamEntity(contentLength, entityStream);
                        responseHandler.handleResponseEntity(responseHeaders, responseEntity);
                    }
                }
                return statusCode;

            }
            finally
            {
                if (null != entityStream)
                {
                    StreamHelper.close(entityStream, false, this);
                }
            }
        }
        public void post(HttpRequestAdapter requestAdapter, HttpResponseHandler responseAdapter)
        {
            HttpWebRequest request = buildPostRequest(requestAdapter, null);
            int statusCode = dispatch(request, null, responseAdapter);

            if (statusCode < 200 || statusCode > 299)
            {
                BaseException e = new BaseException(this, HttpStatus.getReason(statusCode));
                e.FaultCode = statusCode;
                String requestUri = requestAdapter.RequestUri;
                e.addContext("requestUri", requestUri);
                throw e;
            }

        }
        ////////////////////////////////////////////////////////////////////////////

        public void get(HttpRequestAdapter requestAdapter, Authenticator authenticator, HttpResponseHandler responseAdapter)
        {
            HttpWebRequest request = buildGetRequest(requestAdapter, authenticator);
            int statusCode = dispatch(request, authenticator, responseAdapter);

            if (401 == statusCode)
            {
                request = buildGetRequest(requestAdapter, authenticator);
                statusCode = dispatch(request, authenticator, responseAdapter);
            }

            if (statusCode < 200 || statusCode > 299)
            {
                BaseException e = new BaseException(this, HttpStatus.getReason(statusCode));
                e.FaultCode = statusCode;
                String requestUri = requestAdapter.RequestUri;
                e.addContext("requestUri", requestUri);
                throw e;
            }

        }