public ClientContext(string userName, string password, string serviceUri, IEnumerable <DelegatingHandler> handlers = null)
        {
            omniSession = new OmniSession();
            piiUser     = new User();

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(serviceUri))
            {
                throw new ArgumentNullException("username, password or service uri");
            }

            HttpMessageHandler innerHandler = null;
            var apiErrorHandler             = new XOMNIPublicApiErrorHandler();

            if (handlers != null)
            {
                var unifiedHandlers = handlers.ToList();
                unifiedHandlers.Insert(0, apiErrorHandler);
                innerHandler = HttpClientFactory.CreatePipeline(new HttpClientHandler(), unifiedHandlers);
            }
            else
            {
                innerHandler = HttpClientFactory.CreatePipeline(new HttpClientHandler(), new[] { apiErrorHandler });
            }

            this.UserName = userName;
            this.Password = password;
            this.Clients  = new ConcurrentDictionary <Type, object>();

            this.HttpClient             = new HttpClient(innerHandler);
            this.HttpClient.BaseAddress = new Uri(serviceUri);
            this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthenticationSchema,
                                                                                                Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", userName, password))));
            this.HttpClient.DefaultRequestHeaders.Accept.ParseAdd(string.Format("application/vnd.xomni.api-{0}", "v3_0"));
        }
 private void InitalizePIIToken(OmniSession value)
 {
     lock (piiUser)
     {
         if (value == null)
         {
             this.HttpClient.DefaultRequestHeaders.Remove(Constants.PIITokenHeaderKey);
         }
         else
         {
             var sessionHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format(sessionHeaderFormat, value.SessionGuid)));
             this.HttpClient.DefaultRequestHeaders.Add(Constants.PIITokenHeaderKey, sessionHeader);
             piiUser = null;
         }
     }
 }
 private void InitalizePIIToken(User value)
 {
     lock (omniSession)
     {
         if (value == null)
         {
             this.HttpClient.DefaultRequestHeaders.Remove(Constants.PIITokenHeaderKey);
         }
         else
         {
             var piiHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format(piiHeaderFormat, value.UserName, value.Password)));
             this.HttpClient.DefaultRequestHeaders.Add(Constants.PIITokenHeaderKey, piiHeader);
             omniSession = null;
         }
     }
 }
        private TClient GetClientWithHandlers(IEnumerable <DelegatingHandler> handlers, User piiUser = null, OmniSession omniSession = null)
        {
            var clientContext = new ClientContext(userName, password, serviceUri, handlers);

            if (piiUser != null)
            {
                clientContext.PIIUser = piiUser;
            }

            if (omniSession != null)
            {
                clientContext.OmniSession = omniSession;
            }

            return(clientContext.Of <TClient>());
        }
Ejemplo n.º 5
0
        public IActionResult Upload(IFormFile file)
        {
            // Bail out of the file was not uploaded
            if (file == null)
            {
                // No file
                ModelState.AddModelError("cabinet", "NULL file passed to Upload action in Import controller");
                return(RedirectToAction("Index"));
            }
            if (Path.GetExtension(file.FileName) != ".xlsx")
            {
                // Invalid file type (extension)
                ModelState.AddModelError("cabinet", "Invalid file extension to Upload action in Import controller");
                return(RedirectToAction("Index"));
            }

            long size = file.Length;

            if (file.Length > 0)
            {
                //var appUser = await GetCurrentUserAsync();
                var appUser = _userRepository.CurrentUser();

                // process uploaded file
                // Don't rely on or trust the FileName property without validation.
                using (var pck = new OfficeOpenXml.ExcelPackage())
                {
                    using (var stream = file.OpenReadStream())
                    {
                        pck.Load(stream);
                    }

                    var wsCount = pck.Workbook.Worksheets.Count();

                    // There should be four worksheets
                    if (wsCount < 4)
                    {
                        // Not enough worksheets
                        ModelState.AddModelError("cabinet", $"Not enough worksheets -> {pck.Workbook.Worksheets.Count}");
                        return(RedirectToAction("Index"));
                    }
                    OmniSession session = ReadSessionWorkSheet(pck.Workbook.Worksheets[0]);
                    if (session == null)
                    {
                        return(RedirectToAction("Index"));
                    }
                    var viewModel = new TokenStringViewModel(session);

                    var patientList = ReadPatientWorkSheet(viewModel, pck.Workbook.Worksheets[1]);

                    var medicationOrderList = ReadMedicationOrderWorkSheet(viewModel, pck.Workbook.Worksheets[2]);

                    var notInFormularyList = ReadNotInFormularyWorkSheet(viewModel, pck.Workbook.Worksheets[3]);

                    viewModel.WriteToFiles();

                    return(View(viewModel));
                }
            }
            return(NotFound());
        }
        protected async Task SDKExceptionResponseTestAsync(Func <TClient, Task> actAsync, Exception expectedException, User piiUser = null, OmniSession omniSession = null)
        {
            var  mockedClient    = InitalizeMockedClient(piiUser: piiUser, omniSession: omniSession);
            bool exceptionRaised = true;

            try
            {
                await actAsync(mockedClient);

                exceptionRaised = false;
            }
            catch (Exception ex)
            {
                AssertExtensions.AreDeeplyEqual(expectedException, ex);
            }

            if (!exceptionRaised)
            {
                Assert.Fail("Expected exception is not raised.");
            }
        }
        protected async Task DefaultRequestHeadersTestAsync(Func <TClient, Task> actAsync, User piiUser = null, OmniSession omniSession = null)
        {
            Action <HttpRequestMessage, CancellationToken> testCallback = (req, can) =>
            {
                Assert.AreEqual(req.Headers.GetValues(authorizationHeaderKey).First(), "Basic dGVzdFVzZXI6dGVzdFBhc3M=");
                Assert.AreEqual(req.Headers.GetValues(versionHeaderKey).Where(t => t.StartsWith(xomniVersionPrefix)).First(), "application/vnd.xomni.api-v3_0");

                if (piiUser != null)
                {
                    var piiToken = req.Headers.GetValues(piiTokenHeaderKey).First();
                    Assert.IsNotNull(piiToken);

                    var piiTokenArray = Encoding.UTF8.GetString(Convert.FromBase64String(piiToken)).Split(';');
                    var piiUserName   = piiTokenArray[0].Split(':')[1];
                    var piiPassword   = piiTokenArray[1].Split(':')[1];

                    Assert.AreEqual(piiUser.UserName, piiUserName);
                    Assert.AreEqual(piiUser.Password, piiPassword);
                }

                if (omniSession != null)
                {
                    var piiToken = req.Headers.GetValues(piiTokenHeaderKey).First();
                    Assert.IsNotNull(piiToken);

                    var sessionGuid = Guid.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(piiToken)).Split(':')[1]);

                    Assert.AreEqual(omniSession.SessionGuid, sessionGuid);
                }
            };

            var mockedClient = InitalizeMockedClient(testCallback: testCallback, piiUser: piiUser, omniSession: omniSession);

            await actAsync(mockedClient);
        }
        protected async Task UriTestAsync(Func <TClient, Task> actAsync, string expectedUri, User piiUser = null, OmniSession omniSession = null)
        {
            Action <HttpRequestMessage, CancellationToken> testCallback = (req, can) =>
            {
                Assert.AreEqual(expectedUri, req.RequestUri.PathAndQuery);
            };

            var mockedClient = InitalizeMockedClient(testCallback: testCallback, piiUser: piiUser, omniSession: omniSession);

            await actAsync(mockedClient);
        }
        protected async Task APIExceptionResponseTestAsync(Func <TClient, Task> actAsync, HttpResponseMessage mockedHttpResponseMessage, ExceptionResult expectedExceptionResult, User piiUser = null, OmniSession omniSession = null)
        {
            var  mockedClient    = InitalizeMockedClient(mockedHttpResponseMessage, piiUser: piiUser, omniSession: omniSession);
            bool exceptionRaised = true;

            try
            {
                await actAsync(mockedClient);

                exceptionRaised = false;
            }
            catch (XOMNIPublicAPIException ex)
            {
                AssertExtensions.AreDeeplyEqual(expectedExceptionResult, ex.ApiExceptionResult);
            }
            if (!exceptionRaised)
            {
                Assert.Fail("Expected exception is not raised.");
            }
        }
        protected async Task RequestParseTestAsync <TRequest>(Func <TClient, Task> actAsync, string validAPIRequestJson, User piiUser = null, OmniSession omniSession = null)
        {
            Action <HttpRequestMessage, CancellationToken> testCallback = (req, can) =>
            {
                var actualRequest = req.Content.ReadAsAsync <TRequest>().Result;
                AssertExtensions.AreDeeplyEqual(JsonConvert.DeserializeObject <TRequest>(validAPIRequestJson), actualRequest);
            };

            var mockedClient = InitalizeMockedClient(testCallback: testCallback, piiUser: piiUser, omniSession: omniSession);

            await actAsync(mockedClient);
        }
        protected async Task HttpMethodTestAsync(Func <TClient, Task> actAsync, HttpMethod expectedHttpMethod, User piiUser = null, OmniSession omniSession = null)
        {
            Action <HttpRequestMessage, CancellationToken> testCallback = (req, can) =>
            {
                Assert.AreEqual(expectedHttpMethod, req.Method);
            };

            var mockedClient = InitalizeMockedClient(testCallback: testCallback, piiUser: piiUser, omniSession: omniSession);

            await actAsync(mockedClient);
        }
        protected async Task ResponseParseTestAsync(Func <TClient, Task <byte[]> > actAsync, HttpResponseMessage mockedHttpResponseMessage, byte[] validAPIResponseByteArray, User piiUser = null, OmniSession omniSession = null)
        {
            var mockedClient   = InitalizeMockedClient(mockedHttpResponseMessage, piiUser: piiUser, omniSession: omniSession);
            var actualResponse = await actAsync(mockedClient);

            AssertExtensions.AreDeeplyEqual(validAPIResponseByteArray, actualResponse);
        }
        protected async Task ResponseParseTestAsync <TResponse>(Func <TClient, Task <TResponse> > actAsync, HttpResponseMessage mockedHttpResponseMessage, string validAPIResponseJson, User piiUser = null, OmniSession omniSession = null)
        {
            var mockedClient = InitalizeMockedClient(mockedHttpResponseMessage, piiUser: piiUser, omniSession: omniSession);

            var actualResponse = await actAsync(mockedClient);

            AssertExtensions.AreDeeplyEqual(JsonConvert.DeserializeObject <TResponse>(validAPIResponseJson), actualResponse);
        }
        protected TClient InitalizeMockedClient(HttpResponseMessage mockedHttpResponseMessage = null, Action <HttpRequestMessage, CancellationToken> testCallback = null, User piiUser = null, OmniSession omniSession = null)
        {
            var handler      = new Mock <DelegatingHandler>();
            var handlerSetup = handler
                               .Protected()
                               .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());

            if (mockedHttpResponseMessage != null)
            {
                handlerSetup.Returns(Task.FromResult(mockedHttpResponseMessage));
            }
            else
            {
                handlerSetup.Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new StringContent("")
                }));
            }

            if (testCallback != null)
            {
                handlerSetup.Callback(testCallback);
            }

            return(GetClientWithHandler(handler.Object, piiUser, omniSession));
        }
 private TClient GetClientWithHandler(DelegatingHandler handler, User piiUser = null, OmniSession omniSession = null)
 {
     return(GetClientWithHandlers(new[] { handler }, piiUser, omniSession));
 }
Ejemplo n.º 16
0
 protected async Task MetadataResponseParseTestAsync(Func <TClient, Task <ApiResponse <List <Metadata> > > > actAsync, HttpResponseMessage mockedHttpResponseMessage, string validAPIResponseJson, User piiUser = null, OmniSession omniSession = null)
 {
     await base.ResponseParseTestAsync <ApiResponse <List <Metadata> > >(actAsync, mockedHttpResponseMessage, validAPIResponseJson, piiUser, omniSession);
 }