Exemplo n.º 1
0
 public async Task <List <NoteDTO> > GetAllAsync()
 {
     return((await _httpService.GetAsync <IEnumerable <NoteDTO> >(_notesUrl)).ToList());
 }
        public async Task <int> CreateInventoryDocumentAsync(FPReturnInvToPurchasing model, string Type)
        {
            string storageURI = "master/storages";
            string uomURI     = "master/uoms";

            IHttpService httpClient = (IHttpService)this.ServiceProvider.GetService(typeof(IHttpService));

            #region UOM

            Dictionary <string, object> filterUOM = new Dictionary <string, object> {
                { "unit", "MTR" }
            };
            var responseUOM = httpClient.GetAsync($@"{APIEndpoint.Core}{uomURI}?filter=" + JsonConvert.SerializeObject(filterUOM)).Result.Content.ReadAsStringAsync();
            Dictionary <string, object> resultUOM = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseUOM.Result);
            var jsonUOM = resultUOM.Single(p => p.Key.Equals("data")).Value;
            Dictionary <string, object> uom = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonUOM.ToString())[0];

            #endregion UOM

            #region Storage

            var storageName = model.UnitName.Equals("PRINTING") ? "Gudang Greige Printing" : "Gudang Greige Finishing";
            Dictionary <string, object> filterStorage = new Dictionary <string, object> {
                { "name", storageName }
            };
            var responseStorage = httpClient.GetAsync($@"{APIEndpoint.Core}{storageURI}?filter=" + JsonConvert.SerializeObject(filterStorage)).Result.Content.ReadAsStringAsync();
            Dictionary <string, object> resultStorage = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseStorage.Result);
            var jsonStorage = resultStorage.Single(p => p.Key.Equals("data")).Value;
            Dictionary <string, object> storage = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonStorage.ToString())[0];

            #endregion Storage

            #region Inventory Document

            List <InventoryDocumentItem> inventoryDocumentItems = new List <InventoryDocumentItem>();

            foreach (FPReturnInvToPurchasingDetail detail in model.FPReturnInvToPurchasingDetails)
            {
                InventoryDocumentItem inventoryDocumentItem = new InventoryDocumentItem
                {
                    ProductId   = int.Parse(detail.ProductId),
                    ProductCode = detail.ProductCode,
                    ProductName = detail.ProductName,
                    Quantity    = detail.Length,
                    UomId       = int.Parse(uom["Id"].ToString()),
                    UomUnit     = uom["Unit"].ToString()
                };

                inventoryDocumentItems.Add(inventoryDocumentItem);
            }

            InventoryDocument inventoryDocument = new InventoryDocument
            {
                Date          = DateTimeOffset.UtcNow,
                ReferenceNo   = model.No,
                ReferenceType = "Bon Retur Barang - Pembelian",
                Type          = Type,
                StorageId     = int.Parse(storage["_id"].ToString()),
                StorageCode   = storage["code"].ToString(),
                StorageName   = storage["name"].ToString(),
                Items         = inventoryDocumentItems
            };

            var inventoryDocumentFacade = ServiceProvider.GetService <IInventoryDocumentService>();
            return(await inventoryDocumentFacade.Create(inventoryDocument));

            #endregion Inventory Document
        }
        /// <summary>
        /// Gets the user details for the current Api Token.
        /// </summary>
        /// <returns>Returns a PivotalUser.</returns>
        public async Task <PivotalUser> GetUserAsync()
        {
            var resp = await HttpService.GetAsync("me");

            // Gets current user data for the user of the current Api token
            //var response = await HttpService.GetAsync("me");

            return(HandleResponse <PivotalUser>(resp));
        }
 protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
 {
     var baseUrl = GetBaseUrl();
     var url     = $"{baseUrl}api/unsubscribe/{message.CorrelationId.ToString()}";
     await _httpService.GetAsync(url, false);
 }
Exemplo n.º 5
0
        /// <summary>
        ///     Retrieves user salt from server
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task <Try <string> > GetSalt(string email)
        {
            var res = await httpService.GetAsync($"api/salt/{email}");

            return(ProcessResponse(res, "Email does not exist"));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Get()
        {
            var data = await _httpService.GetAsync <IEnumerable <WeatherForecast> >(_configuration.WeatherService.GetAll);

            return(Ok(data));
        }
        public async Task <bool> BuildScriptAsync(ScriptDTO model, bool build = true)
        {
            try
            {
                if (model.RequiredJsArray != null)
                {
                    var scriptContent = new StringBuilder();
                    if (build)
                    {
                        scriptContent.AppendLine("(function() {");
                        foreach (var item in model.RequiredJsArray)
                        {
                            try
                            {
                                var scriptInfo = await httpService.GetAsync <string>(item);

                                scriptContent.AppendLine(scriptInfo);
                            }
                            catch (Exception e)
                            {
                                var errorMsg = SR.Script_BuildDownloadError.Format(model.Name, item);
                                logger.LogError(e, errorMsg);
                                toast.Show(errorMsg);
                            }
                        }
                        scriptContent.AppendLine(model.Content);
                        scriptContent.AppendLine("})( )");
                    }
                    else
                    {
                        scriptContent.Append(model.Content);
                    }
                    var cachePath = Path.Combine(IOPath.CacheDirectory, model.CachePath);
                    var fileInfo  = new FileInfo(cachePath);
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                    if (fileInfo.Exists)
                    {
                        fileInfo.Delete();
                    }
                    using (var stream = fileInfo.CreateText())
                    {
                        stream.Write(scriptContent);
                        await stream.FlushAsync();

                        await stream.DisposeAsync();

                        //stream
                    }

                    return(true);
                    //var scriptRequired = new string[model.RequiredJsArray.Length];
                    //Parallel.ForEach(model.RequiredJsArray, async (item,index)=>
                    //{
                    //	var scriptInfo = await httpService.GetAsync<string>(item);
                    //});
                }
            }
            catch (Exception e)
            {
                var msg = SR.Script_BuildError.Format(e.GetAllMessage());
                logger.LogError(e, msg);
                toast.Show(msg);
            }
            return(false);
        }
        public async Task <int> CreateInventoryDocument(MaterialDistributionNote Model, string Type)
        {
            string storageURI = "master/storages";
            string uomURI     = "master/uoms";

            IHttpService httpClient = (IHttpService)this.ServiceProvider.GetService(typeof(IHttpService));
            /* Get UOM */
            Dictionary <string, object> filterUOM = new Dictionary <string, object> {
                { "unit", "MTR" }
            };
            var responseUOM = httpClient.GetAsync($@"{APIEndpoint.Core}{uomURI}?filter=" + JsonConvert.SerializeObject(filterUOM)).Result.Content.ReadAsStringAsync();
            Dictionary <string, object> resultUOM = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseUOM.Result);
            var jsonUOM = resultUOM.Single(p => p.Key.Equals("data")).Value;
            Dictionary <string, object> uom = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonUOM.ToString())[0];

            /* Get Storage */
            var storageName = Model.UnitName.Equals("PRINTING") ? "Gudang Greige Printing" : "Gudang Greige Finishing";
            Dictionary <string, object> filterStorage = new Dictionary <string, object> {
                { "name", storageName }
            };
            var responseStorage = httpClient.GetAsync($@"{APIEndpoint.Core}{storageURI}?filter=" + JsonConvert.SerializeObject(filterStorage)).Result.Content.ReadAsStringAsync();
            Dictionary <string, object> resultStorage = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseStorage.Result);
            var jsonStorage = resultStorage.Single(p => p.Key.Equals("data")).Value;
            Dictionary <string, object> storage = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonStorage.ToString())[0];

            /* Create Inventory Document */
            List <InventoryDocumentItem>          inventoryDocumentItems = new List <InventoryDocumentItem>();
            List <MaterialDistributionNoteDetail> mdnds = new List <MaterialDistributionNoteDetail>();

            foreach (MaterialDistributionNoteItem mdni in Model.MaterialDistributionNoteItems)
            {
                mdnds.AddRange(mdni.MaterialDistributionNoteDetails);
            }

            //List<MaterialDistributionNoteDetail> list = mdnds
            //        .GroupBy(m => new { m.ProductId, m.ProductCode, m.ProductName })
            //        .Select(s => new MaterialDistributionNoteDetail
            //        {
            //            ProductId = s.First().ProductId,
            //            ProductCode = s.First().ProductCode,
            //            ProductName = s.First().ProductName,
            //            ReceivedLength = s.Sum(d => d.ReceivedLength),
            //            MaterialRequestNoteItemLength = s.Sum(d => d.MaterialRequestNoteItemLength)
            //        }).ToList();

            foreach (MaterialDistributionNoteDetail mdnd in mdnds)
            {
                InventoryDocumentItem inventoryDocumentItem = new InventoryDocumentItem
                {
                    ProductId     = int.Parse(mdnd.ProductId),
                    ProductCode   = mdnd.ProductCode,
                    ProductName   = mdnd.ProductName,
                    Quantity      = mdnd.ReceivedLength,
                    StockPlanning = Model.Type != "RE-GRADING" ? (mdnd.DistributedLength == 0 ? mdnd.MaterialRequestNoteItemLength - mdnd.ReceivedLength : mdnd.ReceivedLength * -1) : mdnd.ReceivedLength * -1,
                    UomId         = int.Parse(uom["Id"].ToString()),
                    UomUnit       = uom["Unit"].ToString()
                };

                inventoryDocumentItems.Add(inventoryDocumentItem);
            }

            List <InventoryDocumentItem> list = inventoryDocumentItems
                                                .GroupBy(m => new { m.ProductId, m.ProductCode, m.ProductName })
                                                .Select(s => new InventoryDocumentItem
            {
                ProductId     = s.First().ProductId,
                ProductCode   = s.First().ProductCode,
                ProductName   = s.First().ProductName,
                Quantity      = s.Sum(d => d.Quantity),
                StockPlanning = s.Sum(d => d.StockPlanning),
                UomUnit       = s.First().UomUnit,
                UomId         = s.First().UomId
            }).ToList();

            InventoryDocument inventoryDocument = new InventoryDocument
            {
                Date          = DateTimeOffset.UtcNow,
                ReferenceNo   = Model.No,
                ReferenceType = "Bon Pengantar Greige",
                Type          = Type,
                StorageId     = int.Parse(storage["_id"].ToString()),
                StorageCode   = storage["code"].ToString(),
                StorageName   = storage["name"].ToString(),
                Items         = list
            };

            var inventoryDocumentFacade = ServiceProvider.GetService <IInventoryDocumentService>();

            return(await inventoryDocumentFacade.Create(inventoryDocument));
        }
Exemplo n.º 9
0
        /// <summary>
        /// 阿里云发送短信验证码
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="jsonData">Json数据</param>
        /// <param name="templateCode">templateCode</param>
        /// <returns></returns>
        private async Task <ApiResult> SendAsync(string mobile, string jsonData, string templateCode)
        {
            if (!ValidateHelper.IsCellPhone(mobile))
            {
                return(ApiResult.ValidateFail());
            }

            if (!_apiEnabled)
            {
                return(ApiResult.Error("管理员禁用短信发送Api"));
            }

            string EndPoint        = _config["SMSAli:EndPoint"];
            string AccessKeyId     = _config["SMSAli:AccessKeyId"];
            string AccessKeySecret = _config["SMSAli:AccessKeySecret"];
            string SignName        = _config["SMSAli:SignName"];

            if (SignName.IsNull())
            {
                return(ApiResult.Error("管理员未配置短信发送相关参数"));
            }

            string nowDate = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); //GTM时间
            Dictionary <string, string> keyValues = new Dictionary <string, string>();            //声明一个字典

            //1.系统参数
            keyValues.Add("SignatureMethod", "HMAC-SHA1");
            keyValues.Add("SignatureNonce", Guid.NewGuid().ToString());
            keyValues.Add("AccessKeyId", AccessKeyId);
            keyValues.Add("SignatureVersion", "1.0");
            keyValues.Add("Timestamp", nowDate);
            keyValues.Add("Format", "Json");//可换成xml

            //2.业务api参数
            keyValues.Add("Action", "SendSms");
            keyValues.Add("Version", "2017-05-25");
            keyValues.Add("RegionId", "cn-hangzhou");
            keyValues.Add("PhoneNumbers", mobile);
            keyValues.Add("SignName", SignName);
            keyValues.Add("TemplateParam", jsonData);
            keyValues.Add("TemplateCode", templateCode);
            keyValues.Add("OutId", "");

            //3.去除签名关键字key
            if (keyValues.ContainsKey("Signature"))
            {
                keyValues.Remove("Signature");
            }

            //4.参数key排序
            Dictionary <string, string> ascDic = keyValues.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value.ObjToString());
            //System.Diagnostics.Trace.WriteLine(">>>>>>>>>>>>>>>>>>"+JsonHelper.Serialize(ascDic));
            //5.构造待签名的字符串
            StringBuilder builder = new StringBuilder();

            foreach (var item in ascDic)
            {
                if (item.Key == "SignName")
                {
                }
                else
                {
                    builder.Append('&').Append(specialUrlEncode(item.Key)).Append('=').Append(specialUrlEncode(item.Value));
                }
                if (item.Key == "RegionId")
                {
                    builder.Append('&').Append(specialUrlEncode("SignName")).Append('=').Append(specialUrlEncode(keyValues["SignName"]));
                }
            }
            string sorteQueryString = builder.ToString().Substring(1);

            StringBuilder stringToSign = new StringBuilder();

            stringToSign.Append("GET").Append('&');
            stringToSign.Append(specialUrlEncode("/")).Append('&');
            stringToSign.Append(specialUrlEncode(sorteQueryString));

            string Sign = MySign(AccessKeySecret + "&", stringToSign.ToString());
            //6.签名最后也要做特殊URL编码
            string signture = specialUrlEncode(Sign);

            //最终打印出合法GET请求的URL
            string url    = string.Format("http://{0}/?Signature={1}{2}", EndPoint, signture, builder);
            var    result = await _httpService.GetAsync(url);

            if (result.IsNull())
            {
                _logger.LogError($"【阿里云SMS】手机号:{mobile},模板内容:{jsonData},返回结果为空");
            }
            _logger.LogInformation($"【阿里云SMS】手机号:{mobile},模板内容:{jsonData},返回结果:{result}");
            if (result == "OK")
            {
                return(ApiResult.OK("OK", jsonData));
            }
            else
            {
                return(ApiResult.ValidateFail(result, jsonData));
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Index(CancellationToken cancellationToken)
        {
            var list = new List <AdminUsers>();

            for (var ndx = 0; ndx < 10; ndx++)
            {
                var user = new AdminUsers
                {
                    Company       = "test",
                    CreatedTime   = DateTime.Now,
                    Location      = "test",
                    LoginCount    = 0,
                    LoginLastIp   = "127.0.0.1",
                    LoginLastTime = DateTime.Now,
                    Mobile        = "17710146178",
                    Name          = $"徐毅{ndx}",
                    Password      = "******",
                    Picture       = $"徐毅{ndx}",
                    Position      = $"徐毅{ ndx }",
                    Status        = true,
                    UserName      = "******"
                };
                list.Add(user);
            }
            var res0 = _dbAdminUsersServiceProvider.Insert(list.ToArray());
            var re2  = await _dbAdminUsersServiceProvider.BatchUpdateAsync(c => c.Id > 22, c => new AdminUsers()
            {
                Name = "哈德斯", Location = "吹牛逼总监", Company = "大牛逼公司"
            });

            var re1 = await _dbAdminUsersServiceProvider.BatchDeleteAsync(c => c.Id > 22);


            var ur2 = UrlArguments.Create("api/messagepack/add");

            var resData = await _httpMessage.CreateClient("msgtest").SetHeaderAccept(HttpMediaType.MessagePack).PostAsync <User>(ur2, null, cancellationToken);

            if (resData.IsSuccessStatusCode)
            {
            }

            var m = await resData.Content.ReadAsAsync <User>(HttpMediaType.MessagePack);



            var url = UrlArguments.Create("msgpack", "api/messagepack/get");

            var res = await _httpService.GetAsync <User>(url, cancellationToken);

            var postUrl = UrlArguments.Create("msgpack", "api/messagepack/add");

            var res1 = await _httpService.PostAsync <User, User>(postUrl, res, cancellationToken);

            var url1 = UrlArguments.Create("test", $"/api/CommentsLive/GetPaged")
                       .Add("aid", 1539)
                       .Add("commentId", 0)
                       .Add("pageSize", 10000);

            var res2 = await _httpService.GetAsync <ReturnModel>(url1, cancellationToken);

            return(View(res2));
        }
Exemplo n.º 11
0
        private async Task DeepAdd(string userId, string id, Uri uri,
                                   Uri mainUri, int deepCount, CancellationToken token)
        {
            try
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                if (mainUri == null || this.UriHaveCircle(uri) || deepCount <= 0)
                {
                    return;
                }

                deepCount--;

                var baseDomain = mainUri.Host.Replace("www.", string.Empty);

                var thisDomain = uri.Host.Replace("www.", string.Empty);

                var isbaseDomain = (!string.IsNullOrWhiteSpace(baseDomain) || !string.IsNullOrWhiteSpace(thisDomain)) &&
                                   (baseDomain.Contains(thisDomain) || thisDomain.Contains(baseDomain));

                if (isbaseDomain && uri.ToString() != "#" &&
                    await this._htmlNotification.PushUri(uri, id, userId))
                {
                    var html = await _httpService.GetAsync(uri);

                    var emails = this._htmlParser.Aegis(html);

                    foreach (var email in emails)
                    {
                        if (!token.IsCancellationRequested && this._emailValidation.IsValidEmail(email))
                        {
                            await this._htmlNotification.PushEmail(email, uri, id, userId);
                        }
                    }

                    var urls = _htmlParser.GetLinks(html, uri).ToList();

                    foreach (var url in urls)
                    {
                        if (Uri.TryCreate(url, UriKind.Absolute, out Uri u))
                        {
                            if (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps)
                            {
                                await this.DeepAdd(userId, id, u, mainUri, deepCount, token);
                            }
                            else if (u.Scheme == Uri.UriSchemeMailto)
                            {
                                var email = this._htmlParser.Aegis(url).FirstOrDefault();

                                if (!token.IsCancellationRequested && !string.IsNullOrWhiteSpace(email) && this._emailValidation.IsValidEmail(email))
                                {
                                    await _htmlNotification.PushEmail(email, uri, id, userId);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await this._telegramService.SendMessageExceptionAsync(ex);
            }
        }
Exemplo n.º 12
0
        public async Task <string> FetchXsrfTokenAsync(CancellationToken?cancellationToken = null)
        {
            var initialResponse = await _httpService.GetAsync(CsrfTokenUrl, null, cancellationToken);

            return(!initialResponse.Success ? null : ParseXsrfTokenFromHeaders(initialResponse.Headers));
        }
 /// <summary>
 /// Get the status of your dragonchain
 /// </summary>
 public async Task <ApiResponse <L1DragonchainStatusResult> > GetStatus()
 {
     return(await _httpService.GetAsync <L1DragonchainStatusResult>("/status"));
 }
        public async Task <string> GetAllSteamAppsString()
        {
            var rsp = await s.GetAsync <string>(SteamApiUrls.STEAMAPP_LIST_URL);

            return(rsp ?? string.Empty);
        }