예제 #1
0
        /// <summary>
        /// 执行http请求
        /// </summary>
        /// <returns>请求结果</returns>
        private async Task <TResponse> SendAsync <TResponse>()
        {
            TResponse result;

            using (var cancellation = this.CreateLinkedTokenSource())
            {
                var completionOption = HttpCompletionOption.ResponseContentRead;

                var response = await this.HttpApiConfig.HttpClient.SendAsync(this.RequestMessage, completionOption, cancellation.Token).ConfigureAwait(false);

                string responseString = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    throw GetFaildException(response);
                }

                try
                {
                    result = JsonExtensions.Deserialize <TResponse>(responseString);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(result);
        }
예제 #2
0
        public async void GetAuthorizedHubs()
        {
            var message = await Configuration.Post("/api/Account/GetAuthorizedHubs", null);

            var user = JsonExtensions.Deserialize <ReturnValue <DexihHub[]> >(message);

            Assert.True(user.Success);
        }
예제 #3
0
        public async Task <CepDTO.Retorno> ObterCep(CepDTO.Envio dto)
        {
            var response = await _httpClient.GetAsync(string.Format(_uri, dto.Cep));

            var retornoJson = response.Content.ReadAsStringAsync().Result;
            var endereco    = JsonExtensions.Deserialize <CepDTO.Retorno>(retornoJson);

            return(endereco);
        }
예제 #4
0
        public async void GetHub()
        {
            var hubKey  = new { HubKey = 2 };
            var message = await Configuration.Post("/api/Hub/GetHubCache", hubKey);

            var hubResult = JsonExtensions.Deserialize <ReturnValue <DexihHub> >(message);

            Assert.True(hubResult.Success);
        }
예제 #5
0
        public void DeserializeTest2()
        {
            string userStr = "{\"Id\":11, \"Name\":\"Xiaoming\"}";
            var    jsonDo  = JsonExtensions.Deserialize(userStr, typeof(UserDo));

            Assert.True(jsonDo is UserDo);
            var userDo = jsonDo as UserDo;

            Assert.NotNull(userDo);
            Assert.Equal(11, userDo.Id);
            Assert.Equal("Xiaoming", userDo.Name);
        }
예제 #6
0
        protected async Task <T> Put <T>(string url, string putData) where T : BaseResponse
        {
            var response = await Client.PutAsync(url, new StringContent(putData));

            T output = JsonExtensions.Deserialize <T>(await response.Content.ReadAsStringAsync());

            if (output.Errcode != 0)
            {
                throw new TencentHttpException(url, putData, output);
            }
            return(output);
        }
예제 #7
0
        public async void SaveHub()
        {
            var hub = new DexihHub()
            {
                Name          = HubName,
                Description   = "The description",
                EncryptionKey = "123"
            };

            var message = await Configuration.Post("/api/Account/SaveHub", hub);

            var user = JsonExtensions.Deserialize <ReturnValue <DexihHub> >(message);

            Assert.True(user.Success);
        }
예제 #8
0
        public void DeserializeTest()
        {
            string userStr = "{\"Id\":11, \"Name\":\"Xiaoming\"}";
            var    userDo  = JsonExtensions.Deserialize <UserDo>(userStr);

            Assert.NotNull(userDo);
            Assert.Equal(11, userDo.Id);
            Assert.Equal("Xiaoming", userDo.Name);

            string otherStr = "\"Key\":11, \"Index\":\"Xiaoming\"}";

            Assert.Throws <Newtonsoft.Json.JsonSerializationException>(() => JsonExtensions.Deserialize <UserDo>(otherStr));

            string otherStr2 = "{\"Key\":11, \"Index\":\"Xiaoming\"}";
            var    userDo2   = JsonExtensions.Deserialize <UserDo>(otherStr2);

            Assert.NotNull(userDo2);
            Assert.Equal(0, userDo2.Id);
            Assert.Null(userDo2.Name);
        }
예제 #9
0
        public static async Task Login()
        {
            var user = new
            {
                Email      = AppSettings["DexihEmail"],
                Password   = AppSettings["DexihPassword"],
                RememberMe = true
            };

            CookieContainer = new CookieContainer();

            var handler = new HttpClientHandler()
            {
                CookieContainer = CookieContainer
            };

            if (HttpClient == null)
            {
                HttpClient = new HttpClient(handler)
                {
                    Timeout = TimeSpan.FromSeconds(600)
                };
            }

            var result = await Post("/api/Account/Login", user);

            var message = JsonExtensions.Deserialize <ReturnValue>(result);

            Assert.True(message.Success);

            // Get user required to refresh the antiforgerytoken
            result = await Post("/api/Account/GetUser", null);

            var user2 = JsonExtensions.Deserialize <ReturnValue <ApplicationUser> >(result);

            Assert.True(user2.Success);

            Assert.Equal(user.Email, user2.Value.Email);
        }
예제 #10
0
        //public async Task<StatusEnum> SyncAsync<TSource, TModel>(ICollection<TSource> currentListEntities,
        //    List<TModel> newList, Func<TModel, CurrentUserViewModel, TSource> newEntity, Expression<Func<TSource, TModel, bool>> indentifier, Role[] allowedRoles, bool save) where TSource : BaseEntity
        //{
        //    var currentUser = CurrentUser();
        //    if (currentUser == null)
        //        return StatusEnum.UserIsNull;

        //    if (currentListEntities?.Any() == true)
        //    {
        //        var mustBeLeft = currentListEntities.Where(source => newList.Any(model => indentifier.Compile().Invoke(source, model))).ToList();
        //        var mustBeRemoved = currentListEntities.Where(x => !mustBeLeft.Contains(x)).ToList();
        //        if (mustBeRemoved.Count > 0)
        //            foreach (var redundant in mustBeRemoved)
        //                await RemoveAsync(redundant, null, DeleteEnum.Delete, false);
        //    }

        //    if (newList?.Any() != true)
        //        return await SaveChangesAsync();

        //    foreach (var model in newList)
        //    {
        //        var source = currentListEntities?.FirstOrDefault(entity => indentifier.Compile().Invoke(entity, model));
        //        if (source == null)
        //        {
        //            var newItem = newEntity.Invoke(model, currentUser);
        //            await AddAsync(newItem, allowedRoles, false);
        //        }
        //        else
        //        {
        //            if (!source.IsDeleted)
        //                continue;

        //            _unitOfWork.UnDelete(source, currentUser);
        //        }
        //    }

        //    return await SaveChangesAsync();
        //}

        public CurrentUserViewModel CurrentUser(List <Claim> claims)
        {
            if (claims.Count == 0)
            {
                return(null);
            }
            var result = new CurrentUserViewModel
            {
                Username          = claims.Find(x => x.Type == ClaimTypes.Name)?.Value,
                Mobile            = claims.Find(x => x.Type == ClaimTypes.MobilePhone)?.Value,
                Role              = claims.Find(x => x.Type == ClaimTypes.Role)?.Value.To <Role>() ?? Role.User,
                EncryptedPassword = claims.Find(x => x.Type == ClaimTypes.Hash)?.Value,
                Id                     = claims.Find(x => x.Type == ClaimTypes.NameIdentifier)?.Value,
                FirstName              = claims.Find(x => x.Type == "FirstName")?.Value,
                LastName               = claims.Find(x => x.Type == "LastName")?.Value,
                EmployeeId             = claims.Find(x => x.Type == "EmployeeId")?.Value,
                UserPropertyCategories = JsonExtensions.Deserialize <List <CategoryJsonViewModel> >(claims.Find(x => x.Type == "PropertyCategories")?.Value),
                UserItemCategories     = JsonExtensions.Deserialize <List <CategoryJsonViewModel> >(claims.Find(x => x.Type == "ItemCategories")?.Value),
                EmployeeDivisions      = JsonExtensions.Deserialize <List <DivisionJsonViewModel> >(claims.Find(x => x.Type == "EmployeeDivisions")?.Value),
            };

            return(result);
        }
예제 #11
0
        public async Task WebSocketEchoTests()
        {
            var cookies = new CookieContainer();
            var handler = new HttpClientHandler
            {
                CookieContainer = cookies
            };

            //Login to the web server to receive an authenicated cookie.
            using (var httpClient = new HttpClient(handler))
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

                var content  = new StringContent("{\"Email\":\"[email protected]\",\"Password\":\"dexIH-1\"}", Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(Url + "Account/Login", content);

                var result = await response.Content.ReadAsStringAsync();

                Assert.False(string.IsNullOrEmpty(result), "Error Account/Login");
                var loginResult = JsonExtensions.Deserialize <ReturnValue <object> >(result);
                Assert.True(loginResult.Success, "login failed: " + loginResult.Message);
            }
        }
예제 #12
0
        private TempCredentialResult GenTempCredential(Dictionary <string, object> values)
        {
            try
            {
                Dictionary <string, object> credential = STSClient.genCredential(values);

                TempCredentialResult output = new TempCredentialResult
                {
                    Bucket = values["bucket"].ToString(),
                    Region = values["region"].ToString()
                };
                IList <string> errs = new List <string>();
                foreach (KeyValuePair <string, object> kvp in credential)
                {
                    switch (kvp.Key)
                    {
                    case "Credentials":
                        output.Credential = JsonExtensions.Deserialize <TempCredential>(kvp.Value.ToString());
                        break;

                    case "ExpiredTime":


                        if (long.TryParse(kvp.Value.ToString(), out long et))
                        {
                            output.ExpiredTime = et;
                        }
                        else
                        {
                            errs.Add("ExpiredTime");
                            errs.Add("kvp.Value.ToString()");
                            // logger.LogError($"ExpiredTime:{kvp.Value}");
                        }

                        output.Expiration = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(output.ExpiredTime);
                        break;

                    case "StartTime":

                        if (long.TryParse(kvp.Value.ToString(), out long st))
                        {
                            output.StartTime = st;
                        }
                        else
                        {
                            errs.Add("StartTime");
                            errs.Add("kvp.Value.ToString()");
                        }
                        break;

                    case "RequestId": output.RequestId = kvp.Value.ToString(); break;
                        //case "Expiration": output.Expiration = JsonConvert.DeserializeObject<DateTimeOffset>(kvp.Value.ToString()); break;
                    }
                }
                return(output);
            }
            catch (Exception ex)
            {
                string[] p = new string[] {
                    "bucket", values["bucket"].ToString(),
                    "region", values["region"].ToString(),
                    "allowPrefix", values["allowPrefix"].ToString(),
                    "allowActions", string.Join(",", values["allowActions"] as string[]),
                    "ex", ex.Message
                };

                throw new WFwException(Results.OperationResultType.TencentCloudSdkStsErr, "", p);
            }
        }
예제 #13
0
        private async Task RenewSslCertificate(string certificatePath, CancellationToken cancellationToken)
        {
            try
            {
                var details = new RenewSslCertificateModel()
                {
                    Domain   = _remoteSettings.Network.DynamicDomain,
                    Password = _remoteSettings.Network.CertificatePassword
                };

                _logger.LogInformation("Attempting to generate a new ssl certificate...");

                var response =
                    await _sharedSettings.PostAsync("Remote/GenerateCertificate", details, cancellationToken);

                if (response != null)
                {
                    if (response.Content.Headers.ContentType.MediaType == "application/json")
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();

                        var message = JsonExtensions.Deserialize <ReturnValue>(jsonContent);
                        _logger.LogError("Ssl request generated the following error: " + message.ExceptionDetails);
                        throw new RemoteSecurityException(message.Message, message.Exception);
                    }

                    var certificate = await response.Content.ReadAsByteArrayAsync();

                    try
                    {
                        using (var cert =
                                   new X509Certificate2(certificate, _remoteSettings.Network.CertificatePassword))
                        {
                            var effectiveDate = DateTime.Parse(cert.GetEffectiveDateString());
                            var expiresDate   = DateTime.Parse(cert.GetExpirationDateString());

                            // if cert expires in next 14 days, then renew.
                            if (DateTime.Now > effectiveDate && DateTime.Now < expiresDate)
                            {
                                await File.WriteAllBytesAsync(certificatePath,
                                                              certificate, cancellationToken);

                                _logger.LogInformation(
                                    $"A new Ssl certificate has been successfully created at {certificatePath}.");
                            }
                            else
                            {
                                var reason =
                                    $"A new Ssl certificate was download but has effective dates between {effectiveDate} and {expiresDate}.  This certificate has not been saved.";
                                _logger.LogCritical(reason);
                                throw new RemoteSecurityException(reason);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var reason =
                            $"There was an error with the downloaded SSL certificate.  {ex.Message}";
                        _logger.LogCritical(reason, ex);
                        throw new RemoteSecurityException(reason, ex);
                    }
                }
                else
                {
                    var reason = $"The ssl certificate renewal failed.  {response.ReasonPhrase}.";
                    _logger.LogCritical(reason);
                    throw new RemoteSecurityException(reason);
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical("There was an issue generating a new SSL certificate.  The existing certificate will be used, or if there is not a current certificate, then HTTP connections will not be available.", ex);
            }
        }
예제 #14
0
        public async void GetHubPerformance(int concurrent, int delay)
        {
            await Configuration.Login();

            var timer     = Stopwatch.StartNew();
            var bestTime  = long.MaxValue;
            var worstTime = 0L;
            var totalTime = 0L;

            var data   = new long[concurrent];
            var errors = new string[concurrent];

            var tasks = Enumerable.Range(0, concurrent).Select(i => Task.Run(async() =>
            {
                await Task.Delay(delay * i);
                var loopTimer = Stopwatch.StartNew();

                try
                {
                    var hubKey   = new { HubKey = 2 };
                    var response = await Configuration.Post("/api/Hub/GetHubCache", hubKey);

                    var hubCache = JsonExtensions.Deserialize <ReturnValue <DexihHub> >(response);

                    if (!hubCache.Success)
                    {
                        errors[i] = hubCache.Message;
                    }
                }
                catch (Exception e)
                {
                    errors[i] = e.Message;
                }
                finally
                {
                    loopTimer.Stop();
                    var elapsed = loopTimer.ElapsedMilliseconds;
                    data[i]     = elapsed;
                    if (elapsed < bestTime)
                    {
                        bestTime = elapsed;
                    }
                    if (elapsed > worstTime)
                    {
                        worstTime = elapsed;
                    }
                    Interlocked.Add(ref totalTime, elapsed);
                }
            }));

            await Task.WhenAll(tasks);

            for (var i = 0; i < concurrent; i++)
            {
                _output.WriteLine($"{data[i]}\t{errors[i]}");
            }

            timer.Stop();

            _output.WriteLine($"Best Time - {bestTime}.");
            _output.WriteLine($"Worst Time - {worstTime}.");
            _output.WriteLine($"Total Time - {timer.ElapsedMilliseconds}.");
            _output.WriteLine($"Average Time - {totalTime / concurrent}");
        }
예제 #15
0
        /// <summary>
        /// Gets any libraries which are contained on the remote server, but not in the global server cache.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task <RemoteLibraries> GetRemoteLibraries(CancellationToken cancellationToken)
        {
            if (_remoteLibraries != null)
            {
                return(_remoteLibraries);
            }

            HttpResponseMessage response;

            try
            {
                response = await _httpClient.GetAsync(_apiUri + "Account/GetGlobalCache", cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(10, ex, "Internal error connecting to the server at location: {0}",
                                    "Account/GetGlobalCache");
                throw;
            }

            if (!response.IsSuccessStatusCode)
            {
                var message =
                    $"Could not connect with server.  Status = {response.StatusCode.ToString()}, {response.ReasonPhrase}";
                _logger.LogCritical(4, message);
                throw new Exception(message);
            }


            try
            {
                // get the global cache from the server, and return remote libraries which are missing.
                var serverResponse = await response.Content.ReadAsStringAsync();

                var globalCache = JsonExtensions.Deserialize <CacheManager>(serverResponse);

                var globalFunctions = globalCache.DefaultRemoteLibraries.Functions
                                      .ToDictionary(c => (c.FunctionAssemblyName, c.FunctionClassName, c.FunctionMethodName));

                var functions = Functions.GetAllFunctions().Where(c => !globalFunctions.ContainsKey((
                                                                                                        c.FunctionAssemblyName, c.FunctionClassName,
                                                                                                        c.FunctionMethodName))).ToList();

                var globalConnections = globalCache.DefaultRemoteLibraries.Connections
                                        .ToDictionary(c => (c.ConnectionAssemblyName, c.ConnectionClassName));

                var connections = Connections.GetAllConnections().Where(c => !globalConnections.ContainsKey((
                                                                                                                c.ConnectionAssemblyName, c.ConnectionClassName))).ToList();

                var globalTransforms = globalCache.DefaultRemoteLibraries.Transforms
                                       .ToDictionary(c => (c.TransformAssemblyName, c.TransformClassName));

                var transforms = Transforms.GetAllTransforms().Where(c => !globalTransforms.ContainsKey((
                                                                                                            c.TransformAssemblyName, c.TransformClassName))).ToList();

                var remoteLibraries = new RemoteLibraries()
                {
                    Functions   = functions,
                    Connections = connections,
                    Transforms  = transforms
                };

                _remoteLibraries = remoteLibraries;

                return(remoteLibraries);
            }
            catch (Exception ex)
            {
                _logger.LogCritical(4,
                                    $"An invalid response was returned connecting with server.  Response was: \"{ex.Message}\".");
                throw;
            }
        }
예제 #16
0
        public async Task <ActionResult> GenerateCertificate([FromBody] GenerateCertificateModel data, CancellationToken cancellationToken)
        {
            var appUser = await _operations.RepositoryManager.GetUserAsync(User, cancellationToken);

            _logger.LogInformation($"Generating ssl certificate for user {appUser.Email}, stored certificate expires: {appUser.CertificateExpiry}.");

            CertificateChain cert;
            IKey             privateKey;

            // if the certificate expires in more than 30 days, use the stored one, otherwise create a new one.
            if (appUser.CertificateExpiry != null && appUser.CertificateExpiry >= DateTime.Now.AddDays(30))
            {
                cert       = new CertificateChain(appUser.CertificateChain);
                privateKey = KeyFactory.FromPem(appUser.PrivateKey);
                _logger.LogDebug($"Used stored certificate chain for user {appUser.Email}.");
            }
            else
            {
                _logger.LogDebug($"Generating new certificate for user {appUser.Email}.");

                // the domain for the certificate is a hash of the userid.domain.
                var hash   = appUser.Id.CreateSHA1();
                var domain = $"{hash}.{data.domain}";

                var txtName = $"_acme-challenge.{domain}";

                AcmeContext acme;
                var         server = _webHostEnvironment.IsDevelopment()
                    ? WellKnownServers.LetsEncryptStagingV2
                    : WellKnownServers.LetsEncryptV2;

                // Load the saved account key
                if (System.IO.File.Exists("letsencrypt.pem"))
                {
                    _logger.LogDebug($"Using existing letsencrypt account.");
                    var pemKey = await System.IO.File.ReadAllTextAsync("letsencrypt.pem", cancellationToken);

                    var accountKey = KeyFactory.FromPem(pemKey);
                    acme = new AcmeContext(server, accountKey);
                }
                else
                {
                    _logger.LogDebug($"Creating new letsencrypt account.");
                    acme = new AcmeContext(server);
                    if (string.IsNullOrEmpty(_operations.Config.LetsEncryptAccount))
                    {
                        throw new RemoteAgentException("There was no LetsEncryptAccount specific in the appsettings.json file on the web server.");
                    }
                    await acme.NewAccount(_operations.Config.LetsEncryptAccount, true);

                    // Save the account key for later use
                    var pemKey = acme.AccountKey.ToPem();
                    await System.IO.File.WriteAllTextAsync("letsencrypt.pem", pemKey, cancellationToken);
                }

                _logger.LogDebug($"Placing order for new certificate on domain *.{domain}.");
                // place order for new certificate
                var order = await acme.NewOrder(new[] { $"*.{domain}" });

                // update the distributed cache with the new record.
                var txtItemsJson = await _distributedCache.GetStringAsync("txtRecords", token : cancellationToken);

                List <KeyValuePair <string, string> > txtItems;

                if (txtItemsJson == null)
                {
                    txtItems = new List <KeyValuePair <string, string> >();
                }
                else
                {
                    txtItems = JsonExtensions.Deserialize <List <KeyValuePair <string, string> > >(txtItemsJson);
                }

                // generate the dns challenge
                foreach (var authz in await order.Authorizations())
                {
                    var dnsChallenge = await authz.Dns();

                    var dnxText = acme.AccountKey.DnsTxt(dnsChallenge.Token);
                    var pair    = new KeyValuePair <string, string>(txtName, dnxText);

                    txtItems.Add(pair);
                }

                txtItemsJson = JsonExtensions.Serialize(txtItems);

                _logger.LogTrace($"Updating txt records: ${txtItemsJson}");

                var txtItemsByte = Encoding.ASCII.GetBytes(txtItemsJson);
                var options      = new DistributedCacheEntryOptions()
                {
                    SlidingExpiration = TimeSpan.FromSeconds(60)
                };
                await _distributedCache.SetAsync("txtRecords", txtItemsByte, options, cancellationToken);

                try
                {
                    foreach (var authz in await order.Authorizations())
                    {
                        var dnsChallenge = await authz.Dns();

                        // validate certificate
                        var challenge = await dnsChallenge.Validate();

                        if (challenge.Error != null)
                        {
                            var message = $"Error running letsEncrypt challenge.  {challenge.Error.Detail}";
                            _errorLogger.LogEvent(message);
                            throw new RemoteAgentException(message);
                        }

                        while (true)
                        {
                            await Task.Delay(100, cancellationToken);

                            var a = await authz.Resource();

                            if (AuthorizationStatus.Invalid == a.Status)
                            {
                                if (a.Challenges != null)
                                {
                                    foreach (var c in a.Challenges)
                                    {
                                        var message =
                                            $"Error running letsEncrypt challenge.  The authorization status is invalid.  Details:{c.Error?.Detail ?? "none"}";
                                        _errorLogger.LogEvent(message);
                                        throw new RemoteAgentException(message);
                                    }
                                }
                                else
                                {
                                    var message =
                                        $"Error running letsEncrypt challenge.  Details:{challenge.Error?.Detail ?? "none"}";
                                    _errorLogger.LogEvent(message);
                                    throw new RemoteAgentException(message);
                                }
                            }

                            var status = a.Status ?? AuthorizationStatus.Pending;

                            if (status == AuthorizationStatus.Valid)
                            {
                                break;
                            }
                        }
                    }
                } finally
                {
                    await _distributedCache.RemoveAsync(txtName, cancellationToken);
                }

                // download certificate once validation is complete
                privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);
                cert       = await order.Generate(new CsrInfo
                {
                    CountryName      = "AU",
                    State            = "Victoria",
                    Locality         = "Melbourne",
                    Organization     = "Data Experts Group",
                    OrganizationUnit = "Integration Hub",
                    CommonName       = $"*.{domain}",
                }, privateKey);

                // save the certificate for future usage
                appUser.PrivateKey        = privateKey.ToPem();
                appUser.CertificateChain  = cert.ToPem();
                appUser.CertificateExpiry = DateTime.Now.AddDays(90); // let's encrypt default expiry date.
                await _operations.RepositoryManager.UpdateUserAsync(appUser, cancellationToken);
            }

            // build the pfx file
            var pfxBuilder = cert.ToPfx(privateKey);
            var pfx        = pfxBuilder.Build("Data Experts Integration Hub Certificate", data.password);

            return(File(pfx, "application/octet-stream", "dexih.pfx"));
        }